PocketMine-MP 5.25.1 git-694aa17cc916a954b10fe12721c81b1dc73eecd5
Loading...
Searching...
No Matches
Utils.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
28namespace pocketmine\utils;
29
35use Ramsey\Uuid\Uuid;
36use Ramsey\Uuid\UuidInterface;
37use function array_combine;
38use function array_map;
39use function array_reverse;
40use function array_values;
41use function bin2hex;
42use function chunk_split;
43use function class_exists;
44use function count;
45use function debug_zval_dump;
46use function dechex;
47use function exec;
48use function explode;
49use function file;
50use function file_exists;
51use function file_get_contents;
52use function function_exists;
53use function get_class;
54use function get_current_user;
55use function get_loaded_extensions;
56use function getenv;
57use function gettype;
58use function implode;
59use function interface_exists;
60use function is_a;
61use function is_array;
62use function is_bool;
63use function is_float;
64use function is_infinite;
65use function is_int;
66use function is_nan;
67use function is_object;
68use function is_string;
69use function mb_check_encoding;
70use function mt_getrandmax;
71use function mt_rand;
72use function ob_end_clean;
73use function ob_get_contents;
74use function ob_start;
75use function opcache_get_status;
76use function ord;
77use function php_uname;
78use function phpversion;
79use function preg_grep;
80use function preg_match;
81use function preg_match_all;
82use function preg_replace;
83use function shell_exec;
84use function spl_object_id;
85use function str_contains;
86use function str_pad;
87use function str_split;
88use function str_starts_with;
89use function stripos;
90use function strlen;
91use function substr;
92use function sys_get_temp_dir;
93use function trim;
94use function xdebug_get_function_stack;
95use const PHP_EOL;
96use const PHP_INT_MAX;
97use const PHP_INT_SIZE;
98use const PHP_MAXPATHLEN;
99use const STR_PAD_LEFT;
100use const STR_PAD_RIGHT;
101
105final class Utils{
106 public const OS_WINDOWS = "win";
107 public const OS_IOS = "ios";
108 public const OS_MACOS = "mac";
109 public const OS_ANDROID = "android";
110 public const OS_LINUX = "linux";
111 public const OS_BSD = "bsd";
112 public const OS_UNKNOWN = "other";
113
114 private static ?string $os = null;
115 private static ?UuidInterface $serverUniqueId = null;
116 private static ?int $cpuCores = null;
117
124 public static function getNiceClosureName(\Closure $closure) : string{
125 $func = new \ReflectionFunction($closure);
126 if(!str_contains($func->getName(), '{closure')){
127 //closure wraps a named function, can be done with reflection or fromCallable()
128 //isClosure() is useless here because it just tells us if $func is reflecting a Closure object
129
130 $scope = $func->getClosureScopeClass();
131 if($scope !== null){ //class method
132 return
133 $scope->getName() .
134 ($func->getClosureThis() !== null ? "->" : "::") .
135 $func->getName(); //name doesn't include class in this case
136 }
137
138 //non-class function
139 return $func->getName();
140 }
141 $filename = $func->getFileName();
142
143 return "closure@" . ($filename !== false ?
144 Filesystem::cleanPath($filename) . "#L" . $func->getStartLine() :
145 "internal"
146 );
147 }
148
154 public static function getNiceClassName(object $obj) : string{
155 $reflect = new \ReflectionClass($obj);
156 if($reflect->isAnonymous()){
157 $filename = $reflect->getFileName();
158
159 return "anonymous@" . ($filename !== false ?
160 Filesystem::cleanPath($filename) . "#L" . $reflect->getStartLine() :
161 "internal"
162 );
163 }
164
165 return $reflect->getName();
166 }
167
172 public static function cloneCallback() : \Closure{
173 return static function(object $o){
174 return clone $o;
175 };
176 }
177
188 public static function cloneObjectArray(array $array) : array{
189 return array_map(fn(object $o) => clone $o, $array);
190 }
191
200 public static function getMachineUniqueId(string $extra = "") : UuidInterface{
201 if(self::$serverUniqueId !== null && $extra === ""){
202 return self::$serverUniqueId;
203 }
204
205 $machine = php_uname("a");
206 $cpuinfo = @file("/proc/cpuinfo");
207 if($cpuinfo !== false){
208 $cpuinfoLines = preg_grep("/(model name|Processor|Serial)/", $cpuinfo);
209 if($cpuinfoLines === false){
210 throw new AssumptionFailedError("Pattern is valid, so this shouldn't fail ...");
211 }
212 $machine .= implode("", $cpuinfoLines);
213 }
214 $machine .= sys_get_temp_dir();
215 $machine .= $extra;
216 $os = Utils::getOS();
217 if($os === Utils::OS_WINDOWS){
218 @exec("ipconfig /ALL", $mac);
219 $mac = implode("\n", $mac);
220 if(preg_match_all("#Physical Address[. ]{1,}: ([0-9A-F\\-]{17})#", $mac, $matches) > 0){
221 foreach($matches[1] as $i => $v){
222 if($v === "00-00-00-00-00-00"){
223 unset($matches[1][$i]);
224 }
225 }
226 $machine .= implode(" ", $matches[1]); //Mac Addresses
227 }
228 }elseif($os === Utils::OS_LINUX){
229 if(file_exists("/etc/machine-id")){
230 $machine .= file_get_contents("/etc/machine-id");
231 }else{
232 @exec("ifconfig 2>/dev/null", $mac);
233 $mac = implode("\n", $mac);
234 if(preg_match_all("#HWaddr[ \t]{1,}([0-9a-f:]{17})#", $mac, $matches) > 0){
235 foreach($matches[1] as $i => $v){
236 if($v === "00:00:00:00:00:00"){
237 unset($matches[1][$i]);
238 }
239 }
240 $machine .= implode(" ", $matches[1]); //Mac Addresses
241 }
242 }
243 }elseif($os === Utils::OS_ANDROID){
244 $machine .= @file_get_contents("/system/build.prop");
245 }elseif($os === Utils::OS_MACOS){
246 $machine .= shell_exec("system_profiler SPHardwareDataType | grep UUID");
247 }
248 $data = $machine . PHP_MAXPATHLEN;
249 $data .= PHP_INT_MAX;
250 $data .= PHP_INT_SIZE;
251 $data .= get_current_user();
252 foreach(get_loaded_extensions() as $ext){
253 $data .= $ext . ":" . phpversion($ext);
254 }
255
256 //TODO: use of NIL as namespace is a hack; it works for now, but we should have a proper namespace UUID
257 $uuid = Uuid::uuid3(Uuid::NIL, $data);
258
259 if($extra === ""){
260 self::$serverUniqueId = $uuid;
261 }
262
263 return $uuid;
264 }
265
269 public static function getOS(bool $recalculate = false) : string{
270 if(self::$os === null || $recalculate){
271 $uname = php_uname("s");
272 if(stripos($uname, "Darwin") !== false){
273 if(str_starts_with(php_uname("m"), "iP")){
274 self::$os = self::OS_IOS;
275 }else{
276 self::$os = self::OS_MACOS;
277 }
278 }elseif(stripos($uname, "Win") !== false || $uname === "Msys"){
279 self::$os = self::OS_WINDOWS;
280 }elseif(stripos($uname, "Linux") !== false){
281 if(@file_exists("/system/build.prop")){
282 self::$os = self::OS_ANDROID;
283 }else{
284 self::$os = self::OS_LINUX;
285 }
286 }elseif(stripos($uname, "BSD") !== false || $uname === "DragonFly"){
287 self::$os = self::OS_BSD;
288 }else{
289 self::$os = self::OS_UNKNOWN;
290 }
291 }
292
293 return self::$os;
294 }
295
296 public static function getCoreCount(bool $recalculate = false) : int{
297 if(self::$cpuCores !== null && !$recalculate){
298 return self::$cpuCores;
299 }
300
301 $processors = 0;
302 switch(Utils::getOS()){
303 case Utils::OS_LINUX:
304 case Utils::OS_ANDROID:
305 if(($cpuinfo = @file('/proc/cpuinfo')) !== false){
306 foreach($cpuinfo as $l){
307 if(preg_match('/^processor[ \t]*:[ \t]*[0-9]+$/m', $l) > 0){
308 ++$processors;
309 }
310 }
311 }elseif(($cpuPresent = @file_get_contents("/sys/devices/system/cpu/present")) !== false){
312 if(preg_match("/^([0-9]+)\\-([0-9]+)$/", trim($cpuPresent), $matches) > 0){
313 $processors = ((int) $matches[2]) - ((int) $matches[1]);
314 }
315 }
316 break;
317 case Utils::OS_BSD:
318 case Utils::OS_MACOS:
319 $processors = (int) shell_exec("sysctl -n hw.ncpu");
320 break;
321 case Utils::OS_WINDOWS:
322 $processors = (int) getenv("NUMBER_OF_PROCESSORS");
323 break;
324 }
325 return self::$cpuCores = $processors;
326 }
327
331 public static function hexdump(string $bin) : string{
332 $output = "";
333 $bin = str_split($bin, 16);
334 foreach($bin as $counter => $line){
335 $hex = chunk_split(chunk_split(str_pad(bin2hex($line), 32, " ", STR_PAD_RIGHT), 2, " "), 24, " ");
336 $ascii = preg_replace('#([^\x20-\x7E])#', ".", $line);
337 $output .= str_pad(dechex($counter << 4), 4, "0", STR_PAD_LEFT) . " " . $hex . " " . $ascii . PHP_EOL;
338 }
339
340 return $output;
341 }
342
346 public static function printable(mixed $str) : string{
347 if(!is_string($str)){
348 return gettype($str);
349 }
350
351 return preg_replace('#([^\x20-\x7E])#', '.', $str);
352 }
353
354 public static function javaStringHash(string $string) : int{
355 $hash = 0;
356 for($i = 0, $len = strlen($string); $i < $len; $i++){
357 $ord = ord($string[$i]);
358 if(($ord & 0x80) !== 0){
359 $ord -= 0x100;
360 }
361 $hash = 31 * $hash + $ord;
362 $hash &= 0xFFFFFFFF;
363 }
364 return $hash;
365 }
366
367 public static function getReferenceCount(object $value, bool $includeCurrent = true) : int{
368 ob_start();
369 debug_zval_dump($value);
370 $contents = ob_get_contents();
371 if($contents === false) throw new AssumptionFailedError("ob_get_contents() should never return false here");
372 $ret = explode("\n", $contents);
373 ob_end_clean();
374
375 if(preg_match('/^.* refcount\\(([0-9]+)\\)\\{$/', trim($ret[0]), $m) > 0){
376 return ((int) $m[1]) - ($includeCurrent ? 3 : 4); //$value + zval call + extra call
377 }
378 return -1;
379 }
380
381 private static function printableExceptionMessage(\Throwable $e) : string{
382 $errstr = preg_replace('/\s+/', ' ', trim($e->getMessage()));
383
384 $errno = $e->getCode();
385 if(is_int($errno)){
386 try{
387 $errno = ErrorTypeToStringMap::get($errno);
388 }catch(\InvalidArgumentException $ex){
389 //pass
390 }
391 }
392
393 $errfile = Filesystem::cleanPath($e->getFile());
394 $errline = $e->getLine();
395
396 return get_class($e) . ": \"$errstr\" ($errno) in \"$errfile\" at line $errline";
397 }
398
404 public static function printableExceptionInfo(\Throwable $e, $trace = null) : array{
405 if($trace === null){
406 $trace = $e->getTrace();
407 }
408
409 $lines = [self::printableExceptionMessage($e)];
410 $lines[] = "--- Stack trace ---";
411 foreach(Utils::printableTrace($trace) as $line){
412 $lines[] = " " . $line;
413 }
414 for($prev = $e->getPrevious(); $prev !== null; $prev = $prev->getPrevious()){
415 $lines[] = "--- Previous ---";
416 $lines[] = self::printableExceptionMessage($prev);
417 foreach(Utils::printableTrace($prev->getTrace()) as $line){
418 $lines[] = " " . $line;
419 }
420 }
421 $lines[] = "--- End of exception information ---";
422 return $lines;
423 }
424
425 private static function stringifyValueForTrace(mixed $value, int $maxStringLength) : string{
426 return match(true){
427 is_object($value) => "object " . self::getNiceClassName($value) . "#" . spl_object_id($value),
428 is_array($value) => "array[" . count($value) . "]",
429 is_string($value) => "string[" . strlen($value) . "] " . substr(Utils::printable($value), 0, $maxStringLength),
430 is_bool($value) => $value ? "true" : "false",
431 is_int($value) => "int " . $value,
432 is_float($value) => "float " . $value,
433 $value === null => "null",
434 default => gettype($value) . " " . Utils::printable((string) $value)
435 };
436 }
437
445 public static function printableTrace(array $trace, int $maxStringLength = 80) : array{
446 $messages = [];
447 for($i = 0; isset($trace[$i]); ++$i){
448 $params = "";
449 if(isset($trace[$i]["args"]) || isset($trace[$i]["params"])){
450 if(isset($trace[$i]["args"])){
451 $args = $trace[$i]["args"];
452 }else{
453 $args = $trace[$i]["params"];
454 }
457 $paramsList = [];
458 $offset = 0;
459 foreach($args as $argId => $value){
460 $paramsList[] = ($argId === $offset ? "" : "$argId: ") . self::stringifyValueForTrace($value, $maxStringLength);
461 $offset++;
462 }
463 $params = implode(", ", $paramsList);
464 }
465 $messages[] = "#$i " .
466 (isset($trace[$i]["file"]) ? Filesystem::cleanPath($trace[$i]["file"]) : "") .
467 "(" . (isset($trace[$i]["line"]) ? $trace[$i]["line"] : "") . "): " .
468 (isset($trace[$i]["class"]) ?
469 $trace[$i]["class"] . (($trace[$i]["type"] === "dynamic" || $trace[$i]["type"] === "->") ? "->" : "::") :
470 ""
471 ) .
472 $trace[$i]["function"] .
473 "(" . Utils::printable($params) . ")";
474 }
475 return $messages;
476 }
477
487 public static function printableTraceWithMetadata(array $rawTrace, int $maxStringLength = 80) : array{
488 $printableTrace = self::printableTrace($rawTrace, $maxStringLength);
489 $safeTrace = [];
490 foreach($printableTrace as $frameId => $printableFrame){
491 $rawFrame = $rawTrace[$frameId];
492 $safeTrace[$frameId] = new ThreadCrashInfoFrame(
493 $printableFrame,
494 $rawFrame["file"] ?? null,
495 $rawFrame["line"] ?? 0
496 );
497 }
498
499 return $safeTrace;
500 }
501
506 public static function currentTrace(int $skipFrames = 0) : array{
507 ++$skipFrames; //omit this frame from trace, in addition to other skipped frames
508 if(function_exists("xdebug_get_function_stack") && count($trace = @xdebug_get_function_stack()) !== 0){
509 $trace = array_reverse($trace);
510 }else{
511 $e = new \Exception();
512 $trace = $e->getTrace();
513 }
514 for($i = 0; $i < $skipFrames; ++$i){
515 unset($trace[$i]);
516 }
517 return array_values($trace);
518 }
519
523 public static function printableCurrentTrace(int $skipFrames = 0) : array{
524 return self::printableTrace(self::currentTrace(++$skipFrames));
525 }
526
532 public static function parseDocComment(string $docComment) : array{
533 $rawDocComment = substr($docComment, 3, -2); //remove the opening and closing markers
534 preg_match_all('/(*ANYCRLF)^[\t ]*(?:\* )?@([a-zA-Z\-]+)(?:[\t ]+(.+?))?[\t ]*$/m', $rawDocComment, $matches);
535
536 return array_combine($matches[1], $matches[2]);
537 }
538
543 public static function testValidInstance(string $className, string $baseName) : void{
544 $baseInterface = false;
545 if(!class_exists($baseName)){
546 if(!interface_exists($baseName)){
547 throw new \InvalidArgumentException("Base class $baseName does not exist");
548 }
549 $baseInterface = true;
550 }
551 if(!class_exists($className)){
552 throw new \InvalidArgumentException("Class $className does not exist or is not a class");
553 }
554 if(!is_a($className, $baseName, true)){
555 throw new \InvalidArgumentException("Class $className does not " . ($baseInterface ? "implement" : "extend") . " $baseName");
556 }
557 $class = new \ReflectionClass($className);
558 if(!$class->isInstantiable()){
559 throw new \InvalidArgumentException("Class $className cannot be constructed");
560 }
561 }
562
575 public static function validateCallableSignature(callable|CallbackType $signature, callable $subject) : void{
576 if(!($signature instanceof CallbackType)){
577 $signature = CallbackType::createFromCallable($signature);
578 }
579 if(!$signature->isSatisfiedBy($subject)){
580 throw new \TypeError("Declaration of callable `" . CallbackType::createFromCallable($subject) . "` must be compatible with `" . $signature . "`");
581 }
582 }
583
589 public static function validateArrayValueType(array $array, \Closure $validator) : void{
590 foreach($array as $k => $v){
591 try{
592 $validator($v);
593 }catch(\TypeError $e){
594 throw new \TypeError("Incorrect type of element at \"$k\": " . $e->getMessage(), 0, $e);
595 }
596 }
597 }
598
609 public static function stringifyKeys(array $array) : \Generator{
610 foreach($array as $key => $value){ // @phpstan-ignore-line - this is where we fix the stupid bullshit with array keys :)
611 yield (string) $key => $value;
612 }
613 }
614
623 public static function promoteKeys(array $array) : array{
624 return $array;
625 }
626
627 public static function checkUTF8(string $string) : void{
628 if(!mb_check_encoding($string, 'UTF-8')){
629 throw new \InvalidArgumentException("Text must be valid UTF-8");
630 }
631 }
632
639 public static function assumeNotFalse(mixed $value, \Closure|string $context = "This should never be false") : mixed{
640 if($value === false){
641 throw new AssumptionFailedError("Assumption failure: " . (is_string($context) ? $context : $context()) . " (THIS IS A BUG)");
642 }
643 return $value;
644 }
645
646 public static function checkFloatNotInfOrNaN(string $name, float $float) : void{
647 if(is_nan($float)){
648 throw new \InvalidArgumentException("$name cannot be NaN");
649 }
650 if(is_infinite($float)){
651 throw new \InvalidArgumentException("$name cannot be infinite");
652 }
653 }
654
655 public static function checkVector3NotInfOrNaN(Vector3 $vector3) : void{
656 if($vector3 instanceof Location){ //location could be masquerading as vector3
657 self::checkFloatNotInfOrNaN("yaw", $vector3->yaw);
658 self::checkFloatNotInfOrNaN("pitch", $vector3->pitch);
659 }
660 self::checkFloatNotInfOrNaN("x", $vector3->x);
661 self::checkFloatNotInfOrNaN("y", $vector3->y);
662 self::checkFloatNotInfOrNaN("z", $vector3->z);
663 }
664
665 public static function checkLocationNotInfOrNaN(Location $location) : void{
666 self::checkVector3NotInfOrNaN($location);
667 }
668
673 public static function getOpcacheJitMode() : ?int{
674 if(
675 function_exists('opcache_get_status') &&
676 ($opcacheStatus = opcache_get_status(false)) !== false &&
677 isset($opcacheStatus["jit"]["on"])
678 ){
679 $jit = $opcacheStatus["jit"];
680 if($jit["on"] === true){
681 return (($jit["opt_flags"] >> 2) * 1000) +
682 (($jit["opt_flags"] & 0x03) * 100) +
683 ($jit["kind"] * 10) +
684 $jit["opt_level"];
685 }
686
687 //jit available, but disabled
688 return 0;
689 }
690
691 //jit not available
692 return null;
693 }
694
699 public static function getRandomFloat() : float{
700 return mt_rand() / mt_getrandmax();
701 }
702}
static printableExceptionInfo(\Throwable $e, $trace=null)
Definition Utils.php:404
static parseDocComment(string $docComment)
Definition Utils.php:532
static assumeNotFalse(mixed $value, \Closure|string $context="This should never be false")
Definition Utils.php:639
static validateArrayValueType(array $array, \Closure $validator)
Definition Utils.php:589
static validateCallableSignature(callable|CallbackType $signature, callable $subject)
Definition Utils.php:575
static getMachineUniqueId(string $extra="")
Definition Utils.php:200
static stringifyKeys(array $array)
Definition Utils.php:609
static hexdump(string $bin)
Definition Utils.php:331
static getNiceClosureName(\Closure $closure)
Definition Utils.php:124
static getOS(bool $recalculate=false)
Definition Utils.php:269
static currentTrace(int $skipFrames=0)
Definition Utils.php:506
static printable(mixed $str)
Definition Utils.php:346
static printableTraceWithMetadata(array $rawTrace, int $maxStringLength=80)
Definition Utils.php:487
static testValidInstance(string $className, string $baseName)
Definition Utils.php:543
static getOpcacheJitMode()
Definition Utils.php:673
static getNiceClassName(object $obj)
Definition Utils.php:154
static cloneCallback()
Definition Utils.php:172
static cloneObjectArray(array $array)
Definition Utils.php:188
static getRandomFloat()
Definition Utils.php:699
static printableTrace(array $trace, int $maxStringLength=80)
Definition Utils.php:445
static printableCurrentTrace(int $skipFrames=0)
Definition Utils.php:523
static promoteKeys(array $array)
Definition Utils.php:623