PocketMine-MP 5.23.3 git-4a4572131f27ab967701ceaaf2020cfbe26e375c
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
171 public static function cloneCallback() : \Closure{
172 return static function(object $o){
173 return clone $o;
174 };
175 }
176
187 public static function cloneObjectArray(array $array) : array{
189 $callback = self::cloneCallback();
190 return array_map($callback, $array);
191 }
192
201 public static function getMachineUniqueId(string $extra = "") : UuidInterface{
202 if(self::$serverUniqueId !== null && $extra === ""){
203 return self::$serverUniqueId;
204 }
205
206 $machine = php_uname("a");
207 $cpuinfo = @file("/proc/cpuinfo");
208 if($cpuinfo !== false){
209 $cpuinfoLines = preg_grep("/(model name|Processor|Serial)/", $cpuinfo);
210 if($cpuinfoLines === false){
211 throw new AssumptionFailedError("Pattern is valid, so this shouldn't fail ...");
212 }
213 $machine .= implode("", $cpuinfoLines);
214 }
215 $machine .= sys_get_temp_dir();
216 $machine .= $extra;
217 $os = Utils::getOS();
218 if($os === Utils::OS_WINDOWS){
219 @exec("ipconfig /ALL", $mac);
220 $mac = implode("\n", $mac);
221 if(preg_match_all("#Physical Address[. ]{1,}: ([0-9A-F\\-]{17})#", $mac, $matches) > 0){
222 foreach($matches[1] as $i => $v){
223 if($v == "00-00-00-00-00-00"){
224 unset($matches[1][$i]);
225 }
226 }
227 $machine .= implode(" ", $matches[1]); //Mac Addresses
228 }
229 }elseif($os === Utils::OS_LINUX){
230 if(file_exists("/etc/machine-id")){
231 $machine .= file_get_contents("/etc/machine-id");
232 }else{
233 @exec("ifconfig 2>/dev/null", $mac);
234 $mac = implode("\n", $mac);
235 if(preg_match_all("#HWaddr[ \t]{1,}([0-9a-f:]{17})#", $mac, $matches) > 0){
236 foreach($matches[1] as $i => $v){
237 if($v == "00:00:00:00:00:00"){
238 unset($matches[1][$i]);
239 }
240 }
241 $machine .= implode(" ", $matches[1]); //Mac Addresses
242 }
243 }
244 }elseif($os === Utils::OS_ANDROID){
245 $machine .= @file_get_contents("/system/build.prop");
246 }elseif($os === Utils::OS_MACOS){
247 $machine .= shell_exec("system_profiler SPHardwareDataType | grep UUID");
248 }
249 $data = $machine . PHP_MAXPATHLEN;
250 $data .= PHP_INT_MAX;
251 $data .= PHP_INT_SIZE;
252 $data .= get_current_user();
253 foreach(get_loaded_extensions() as $ext){
254 $data .= $ext . ":" . phpversion($ext);
255 }
256
257 //TODO: use of NIL as namespace is a hack; it works for now, but we should have a proper namespace UUID
258 $uuid = Uuid::uuid3(Uuid::NIL, $data);
259
260 if($extra === ""){
261 self::$serverUniqueId = $uuid;
262 }
263
264 return $uuid;
265 }
266
277 public static function getOS(bool $recalculate = false) : string{
278 if(self::$os === null || $recalculate){
279 $uname = php_uname("s");
280 if(stripos($uname, "Darwin") !== false){
281 if(str_starts_with(php_uname("m"), "iP")){
282 self::$os = self::OS_IOS;
283 }else{
284 self::$os = self::OS_MACOS;
285 }
286 }elseif(stripos($uname, "Win") !== false || $uname === "Msys"){
287 self::$os = self::OS_WINDOWS;
288 }elseif(stripos($uname, "Linux") !== false){
289 if(@file_exists("/system/build.prop")){
290 self::$os = self::OS_ANDROID;
291 }else{
292 self::$os = self::OS_LINUX;
293 }
294 }elseif(stripos($uname, "BSD") !== false || $uname === "DragonFly"){
295 self::$os = self::OS_BSD;
296 }else{
297 self::$os = self::OS_UNKNOWN;
298 }
299 }
300
301 return self::$os;
302 }
303
304 public static function getCoreCount(bool $recalculate = false) : int{
305 if(self::$cpuCores !== null && !$recalculate){
306 return self::$cpuCores;
307 }
308
309 $processors = 0;
310 switch(Utils::getOS()){
311 case Utils::OS_LINUX:
312 case Utils::OS_ANDROID:
313 if(($cpuinfo = @file('/proc/cpuinfo')) !== false){
314 foreach($cpuinfo as $l){
315 if(preg_match('/^processor[ \t]*:[ \t]*[0-9]+$/m', $l) > 0){
316 ++$processors;
317 }
318 }
319 }elseif(($cpuPresent = @file_get_contents("/sys/devices/system/cpu/present")) !== false){
320 if(preg_match("/^([0-9]+)\\-([0-9]+)$/", trim($cpuPresent), $matches) > 0){
321 $processors = ((int) $matches[2]) - ((int) $matches[1]);
322 }
323 }
324 break;
325 case Utils::OS_BSD:
326 case Utils::OS_MACOS:
327 $processors = (int) shell_exec("sysctl -n hw.ncpu");
328 break;
329 case Utils::OS_WINDOWS:
330 $processors = (int) getenv("NUMBER_OF_PROCESSORS");
331 break;
332 }
333 return self::$cpuCores = $processors;
334 }
335
339 public static function hexdump(string $bin) : string{
340 $output = "";
341 $bin = str_split($bin, 16);
342 foreach($bin as $counter => $line){
343 $hex = chunk_split(chunk_split(str_pad(bin2hex($line), 32, " ", STR_PAD_RIGHT), 2, " "), 24, " ");
344 $ascii = preg_replace('#([^\x20-\x7E])#', ".", $line);
345 $output .= str_pad(dechex($counter << 4), 4, "0", STR_PAD_LEFT) . " " . $hex . " " . $ascii . PHP_EOL;
346 }
347
348 return $output;
349 }
350
354 public static function printable(mixed $str) : string{
355 if(!is_string($str)){
356 return gettype($str);
357 }
358
359 return preg_replace('#([^\x20-\x7E])#', '.', $str);
360 }
361
362 public static function javaStringHash(string $string) : int{
363 $hash = 0;
364 for($i = 0, $len = strlen($string); $i < $len; $i++){
365 $ord = ord($string[$i]);
366 if(($ord & 0x80) !== 0){
367 $ord -= 0x100;
368 }
369 $hash = 31 * $hash + $ord;
370 $hash &= 0xFFFFFFFF;
371 }
372 return $hash;
373 }
374
375 public static function getReferenceCount(object $value, bool $includeCurrent = true) : int{
376 ob_start();
377 debug_zval_dump($value);
378 $contents = ob_get_contents();
379 if($contents === false) throw new AssumptionFailedError("ob_get_contents() should never return false here");
380 $ret = explode("\n", $contents);
381 ob_end_clean();
382
383 if(preg_match('/^.* refcount\\(([0-9]+)\\)\\{$/', trim($ret[0]), $m) > 0){
384 return ((int) $m[1]) - ($includeCurrent ? 3 : 4); //$value + zval call + extra call
385 }
386 return -1;
387 }
388
389 private static function printableExceptionMessage(\Throwable $e) : string{
390 $errstr = preg_replace('/\s+/', ' ', trim($e->getMessage()));
391
392 $errno = $e->getCode();
393 if(is_int($errno)){
394 try{
395 $errno = ErrorTypeToStringMap::get($errno);
396 }catch(\InvalidArgumentException $ex){
397 //pass
398 }
399 }
400
401 $errfile = Filesystem::cleanPath($e->getFile());
402 $errline = $e->getLine();
403
404 return get_class($e) . ": \"$errstr\" ($errno) in \"$errfile\" at line $errline";
405 }
406
411 public static function printableExceptionInfo(\Throwable $e, $trace = null) : array{
412 if($trace === null){
413 $trace = $e->getTrace();
414 }
415
416 $lines = [self::printableExceptionMessage($e)];
417 $lines[] = "--- Stack trace ---";
418 foreach(Utils::printableTrace($trace) as $line){
419 $lines[] = " " . $line;
420 }
421 for($prev = $e->getPrevious(); $prev !== null; $prev = $prev->getPrevious()){
422 $lines[] = "--- Previous ---";
423 $lines[] = self::printableExceptionMessage($prev);
424 foreach(Utils::printableTrace($prev->getTrace()) as $line){
425 $lines[] = " " . $line;
426 }
427 }
428 $lines[] = "--- End of exception information ---";
429 return $lines;
430 }
431
432 private static function stringifyValueForTrace(mixed $value, int $maxStringLength) : string{
433 return match(true){
434 is_object($value) => "object " . self::getNiceClassName($value) . "#" . spl_object_id($value),
435 is_array($value) => "array[" . count($value) . "]",
436 is_string($value) => "string[" . strlen($value) . "] " . substr(Utils::printable($value), 0, $maxStringLength),
437 is_bool($value) => $value ? "true" : "false",
438 is_int($value) => "int " . $value,
439 is_float($value) => "float " . $value,
440 $value === null => "null",
441 default => gettype($value) . " " . Utils::printable((string) $value)
442 };
443 }
444
452 public static function printableTrace(array $trace, int $maxStringLength = 80) : array{
453 $messages = [];
454 for($i = 0; isset($trace[$i]); ++$i){
455 $params = "";
456 if(isset($trace[$i]["args"]) || isset($trace[$i]["params"])){
457 if(isset($trace[$i]["args"])){
458 $args = $trace[$i]["args"];
459 }else{
460 $args = $trace[$i]["params"];
461 }
464 $paramsList = [];
465 $offset = 0;
466 foreach($args as $argId => $value){
467 $paramsList[] = ($argId === $offset ? "" : "$argId: ") . self::stringifyValueForTrace($value, $maxStringLength);
468 $offset++;
469 }
470 $params = implode(", ", $paramsList);
471 }
472 $messages[] = "#$i " . (isset($trace[$i]["file"]) ? Filesystem::cleanPath($trace[$i]["file"]) : "") . "(" . (isset($trace[$i]["line"]) ? $trace[$i]["line"] : "") . "): " . (isset($trace[$i]["class"]) ? $trace[$i]["class"] . (($trace[$i]["type"] === "dynamic" || $trace[$i]["type"] === "->") ? "->" : "::") : "") . $trace[$i]["function"] . "(" . Utils::printable($params) . ")";
473 }
474 return $messages;
475 }
476
486 public static function printableTraceWithMetadata(array $rawTrace, int $maxStringLength = 80) : array{
487 $printableTrace = self::printableTrace($rawTrace, $maxStringLength);
488 $safeTrace = [];
489 foreach($printableTrace as $frameId => $printableFrame){
490 $rawFrame = $rawTrace[$frameId];
491 $safeTrace[$frameId] = new ThreadCrashInfoFrame(
492 $printableFrame,
493 $rawFrame["file"] ?? null,
494 $rawFrame["line"] ?? 0
495 );
496 }
497
498 return $safeTrace;
499 }
500
505 public static function currentTrace(int $skipFrames = 0) : array{
506 ++$skipFrames; //omit this frame from trace, in addition to other skipped frames
507 if(function_exists("xdebug_get_function_stack") && count($trace = @xdebug_get_function_stack()) !== 0){
508 $trace = array_reverse($trace);
509 }else{
510 $e = new \Exception();
511 $trace = $e->getTrace();
512 }
513 for($i = 0; $i < $skipFrames; ++$i){
514 unset($trace[$i]);
515 }
516 return array_values($trace);
517 }
518
522 public static function printableCurrentTrace(int $skipFrames = 0) : array{
523 return self::printableTrace(self::currentTrace(++$skipFrames));
524 }
525
531 public static function parseDocComment(string $docComment) : array{
532 $rawDocComment = substr($docComment, 3, -2); //remove the opening and closing markers
533 preg_match_all('/(*ANYCRLF)^[\t ]*(?:\* )?@([a-zA-Z\-]+)(?:[\t ]+(.+?))?[\t ]*$/m', $rawDocComment, $matches);
534
535 return array_combine($matches[1], $matches[2]);
536 }
537
542 public static function testValidInstance(string $className, string $baseName) : void{
543 $baseInterface = false;
544 if(!class_exists($baseName)){
545 if(!interface_exists($baseName)){
546 throw new \InvalidArgumentException("Base class $baseName does not exist");
547 }
548 $baseInterface = true;
549 }
550 if(!class_exists($className)){
551 throw new \InvalidArgumentException("Class $className does not exist or is not a class");
552 }
553 if(!is_a($className, $baseName, true)){
554 throw new \InvalidArgumentException("Class $className does not " . ($baseInterface ? "implement" : "extend") . " $baseName");
555 }
556 $class = new \ReflectionClass($className);
557 if(!$class->isInstantiable()){
558 throw new \InvalidArgumentException("Class $className cannot be constructed");
559 }
560 }
561
574 public static function validateCallableSignature(callable|CallbackType $signature, callable $subject) : void{
575 if(!($signature instanceof CallbackType)){
576 $signature = CallbackType::createFromCallable($signature);
577 }
578 if(!$signature->isSatisfiedBy($subject)){
579 throw new \TypeError("Declaration of callable `" . CallbackType::createFromCallable($subject) . "` must be compatible with `" . $signature . "`");
580 }
581 }
582
588 public static function validateArrayValueType(array $array, \Closure $validator) : void{
589 foreach($array as $k => $v){
590 try{
591 $validator($v);
592 }catch(\TypeError $e){
593 throw new \TypeError("Incorrect type of element at \"$k\": " . $e->getMessage(), 0, $e);
594 }
595 }
596 }
597
608 public static function stringifyKeys(array $array) : \Generator{
609 foreach($array as $key => $value){ // @phpstan-ignore-line - this is where we fix the stupid bullshit with array keys :)
610 yield (string) $key => $value;
611 }
612 }
613
622 public static function promoteKeys(array $array) : array{
623 return $array;
624 }
625
626 public static function checkUTF8(string $string) : void{
627 if(!mb_check_encoding($string, 'UTF-8')){
628 throw new \InvalidArgumentException("Text must be valid UTF-8");
629 }
630 }
631
638 public static function assumeNotFalse(mixed $value, \Closure|string $context = "This should never be false") : mixed{
639 if($value === false){
640 throw new AssumptionFailedError("Assumption failure: " . (is_string($context) ? $context : $context()) . " (THIS IS A BUG)");
641 }
642 return $value;
643 }
644
645 public static function checkFloatNotInfOrNaN(string $name, float $float) : void{
646 if(is_nan($float)){
647 throw new \InvalidArgumentException("$name cannot be NaN");
648 }
649 if(is_infinite($float)){
650 throw new \InvalidArgumentException("$name cannot be infinite");
651 }
652 }
653
654 public static function checkVector3NotInfOrNaN(Vector3 $vector3) : void{
655 if($vector3 instanceof Location){ //location could be masquerading as vector3
656 self::checkFloatNotInfOrNaN("yaw", $vector3->yaw);
657 self::checkFloatNotInfOrNaN("pitch", $vector3->pitch);
658 }
659 self::checkFloatNotInfOrNaN("x", $vector3->x);
660 self::checkFloatNotInfOrNaN("y", $vector3->y);
661 self::checkFloatNotInfOrNaN("z", $vector3->z);
662 }
663
664 public static function checkLocationNotInfOrNaN(Location $location) : void{
665 self::checkVector3NotInfOrNaN($location);
666 }
667
672 public static function getOpcacheJitMode() : ?int{
673 if(
674 function_exists('opcache_get_status') &&
675 ($opcacheStatus = opcache_get_status(false)) !== false &&
676 isset($opcacheStatus["jit"]["on"])
677 ){
678 $jit = $opcacheStatus["jit"];
679 if($jit["on"] === true){
680 return (($jit["opt_flags"] >> 2) * 1000) +
681 (($jit["opt_flags"] & 0x03) * 100) +
682 ($jit["kind"] * 10) +
683 $jit["opt_level"];
684 }
685
686 //jit available, but disabled
687 return 0;
688 }
689
690 //jit not available
691 return null;
692 }
693
698 public static function getRandomFloat() : float{
699 return mt_rand() / mt_getrandmax();
700 }
701}
static printableExceptionInfo(\Throwable $e, $trace=null)
Definition Utils.php:411
static parseDocComment(string $docComment)
Definition Utils.php:531
static assumeNotFalse(mixed $value, \Closure|string $context="This should never be false")
Definition Utils.php:638
static validateArrayValueType(array $array, \Closure $validator)
Definition Utils.php:588
static validateCallableSignature(callable|CallbackType $signature, callable $subject)
Definition Utils.php:574
static getMachineUniqueId(string $extra="")
Definition Utils.php:201
static stringifyKeys(array $array)
Definition Utils.php:608
static hexdump(string $bin)
Definition Utils.php:339
static getNiceClosureName(\Closure $closure)
Definition Utils.php:124
static getOS(bool $recalculate=false)
Definition Utils.php:277
static currentTrace(int $skipFrames=0)
Definition Utils.php:505
static printable(mixed $str)
Definition Utils.php:354
static printableTraceWithMetadata(array $rawTrace, int $maxStringLength=80)
Definition Utils.php:486
static testValidInstance(string $className, string $baseName)
Definition Utils.php:542
static getOpcacheJitMode()
Definition Utils.php:672
static getNiceClassName(object $obj)
Definition Utils.php:154
static cloneCallback()
Definition Utils.php:171
static cloneObjectArray(array $array)
Definition Utils.php:187
static getRandomFloat()
Definition Utils.php:698
static printableTrace(array $trace, int $maxStringLength=80)
Definition Utils.php:452
static printableCurrentTrace(int $skipFrames=0)
Definition Utils.php:522
static promoteKeys(array $array)
Definition Utils.php:622