PocketMine-MP 5.32.2 git-1ebd7d3960d713d56f77f610fe0c15cdee201069
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
178 public static function cloneObjectArray(array $array) : array{
179 return array_map(fn(object $o) => clone $o, $array);
180 }
181
190 public static function getMachineUniqueId(string $extra = "") : UuidInterface{
191 if(self::$serverUniqueId !== null && $extra === ""){
192 return self::$serverUniqueId;
193 }
194
195 $machine = php_uname("a");
196 $cpuinfo = @file("/proc/cpuinfo");
197 if($cpuinfo !== false){
198 $cpuinfoLines = preg_grep("/(model name|Processor|Serial)/", $cpuinfo);
199 if($cpuinfoLines === false){
200 throw new AssumptionFailedError("Pattern is valid, so this shouldn't fail ...");
201 }
202 $machine .= implode("", $cpuinfoLines);
203 }
204 $machine .= sys_get_temp_dir();
205 $machine .= $extra;
206 $os = Utils::getOS();
207 if($os === Utils::OS_WINDOWS){
208 @exec("ipconfig /ALL", $mac);
209 $mac = implode("\n", $mac);
210 if(preg_match_all("#Physical Address[. ]{1,}: ([0-9A-F\\-]{17})#", $mac, $matches) > 0){
211 foreach($matches[1] as $i => $v){
212 if($v === "00-00-00-00-00-00"){
213 unset($matches[1][$i]);
214 }
215 }
216 $machine .= implode(" ", $matches[1]); //Mac Addresses
217 }
218 }elseif($os === Utils::OS_LINUX){
219 if(file_exists("/etc/machine-id")){
220 $machine .= file_get_contents("/etc/machine-id");
221 }else{
222 @exec("ifconfig 2>/dev/null", $mac);
223 $mac = implode("\n", $mac);
224 if(preg_match_all("#HWaddr[ \t]{1,}([0-9a-f:]{17})#", $mac, $matches) > 0){
225 foreach($matches[1] as $i => $v){
226 if($v === "00:00:00:00:00:00"){
227 unset($matches[1][$i]);
228 }
229 }
230 $machine .= implode(" ", $matches[1]); //Mac Addresses
231 }
232 }
233 }elseif($os === Utils::OS_ANDROID){
234 $machine .= @file_get_contents("/system/build.prop");
235 }elseif($os === Utils::OS_MACOS){
236 $machine .= shell_exec("system_profiler SPHardwareDataType | grep UUID");
237 }
238 $data = $machine . PHP_MAXPATHLEN;
239 $data .= PHP_INT_MAX;
240 $data .= PHP_INT_SIZE;
241 $data .= get_current_user();
242 foreach(get_loaded_extensions() as $ext){
243 $data .= $ext . ":" . phpversion($ext);
244 }
245
246 //TODO: use of NIL as namespace is a hack; it works for now, but we should have a proper namespace UUID
247 $uuid = Uuid::uuid3(Uuid::NIL, $data);
248
249 if($extra === ""){
250 self::$serverUniqueId = $uuid;
251 }
252
253 return $uuid;
254 }
255
259 public static function getOS(bool $recalculate = false) : string{
260 if(self::$os === null || $recalculate){
261 $uname = php_uname("s");
262 if(stripos($uname, "Darwin") !== false){
263 if(str_starts_with(php_uname("m"), "iP")){
264 self::$os = self::OS_IOS;
265 }else{
266 self::$os = self::OS_MACOS;
267 }
268 }elseif(stripos($uname, "Win") !== false || $uname === "Msys"){
269 self::$os = self::OS_WINDOWS;
270 }elseif(stripos($uname, "Linux") !== false){
271 if(@file_exists("/system/build.prop")){
272 self::$os = self::OS_ANDROID;
273 }else{
274 self::$os = self::OS_LINUX;
275 }
276 }elseif(stripos($uname, "BSD") !== false || $uname === "DragonFly"){
277 self::$os = self::OS_BSD;
278 }else{
279 self::$os = self::OS_UNKNOWN;
280 }
281 }
282
283 return self::$os;
284 }
285
286 public static function getCoreCount(bool $recalculate = false) : int{
287 if(self::$cpuCores !== null && !$recalculate){
288 return self::$cpuCores;
289 }
290
291 $processors = 0;
292 switch(Utils::getOS()){
293 case Utils::OS_LINUX:
294 case Utils::OS_ANDROID:
295 if(($cpuinfo = @file('/proc/cpuinfo')) !== false){
296 foreach($cpuinfo as $l){
297 if(preg_match('/^processor[ \t]*:[ \t]*[0-9]+$/m', $l) > 0){
298 ++$processors;
299 }
300 }
301 }elseif(($cpuPresent = @file_get_contents("/sys/devices/system/cpu/present")) !== false){
302 if(preg_match("/^([0-9]+)\\-([0-9]+)$/", trim($cpuPresent), $matches) > 0){
303 $processors = ((int) $matches[2]) - ((int) $matches[1]);
304 }
305 }
306 break;
307 case Utils::OS_BSD:
308 case Utils::OS_MACOS:
309 $processors = (int) shell_exec("sysctl -n hw.ncpu");
310 break;
311 case Utils::OS_WINDOWS:
312 $processors = (int) getenv("NUMBER_OF_PROCESSORS");
313 break;
314 }
315 return self::$cpuCores = $processors;
316 }
317
321 public static function hexdump(string $bin) : string{
322 $output = "";
323 $bin = str_split($bin, 16);
324 foreach($bin as $counter => $line){
325 $hex = chunk_split(chunk_split(str_pad(bin2hex($line), 32, " ", STR_PAD_RIGHT), 2, " "), 24, " ");
326 $ascii = preg_replace('#([^\x20-\x7E])#', ".", $line);
327 $output .= str_pad(dechex($counter << 4), 4, "0", STR_PAD_LEFT) . " " . $hex . " " . $ascii . PHP_EOL;
328 }
329
330 return $output;
331 }
332
336 public static function printable(mixed $str) : string{
337 if(!is_string($str)){
338 return gettype($str);
339 }
340
341 return preg_replace('#([^\x20-\x7E])#', '.', $str);
342 }
343
344 public static function javaStringHash(string $string) : int{
345 $hash = 0;
346 for($i = 0, $len = strlen($string); $i < $len; $i++){
347 $ord = ord($string[$i]);
348 if(($ord & 0x80) !== 0){
349 $ord -= 0x100;
350 }
351 $hash = 31 * $hash + $ord;
352 $hash &= 0xFFFFFFFF;
353 }
354 return $hash;
355 }
356
357 public static function getReferenceCount(object $value, bool $includeCurrent = true) : int{
358 ob_start();
359 debug_zval_dump($value);
360 $contents = ob_get_contents();
361 if($contents === false) throw new AssumptionFailedError("ob_get_contents() should never return false here");
362 $ret = explode("\n", $contents, limit: 2);
363 ob_end_clean();
364
365 if(preg_match('/^.* refcount\\(([0-9]+)\\)\\{$/', trim($ret[0]), $m) > 0){
366 return ((int) $m[1]) - ($includeCurrent ? 3 : 4); //$value + zval call + extra call
367 }
368 return -1;
369 }
370
371 private static function printableExceptionMessage(\Throwable $e) : string{
372 $errstr = preg_replace('/\s+/', ' ', trim($e->getMessage()));
373
374 $errno = $e->getCode();
375 if(is_int($errno)){
376 try{
377 $errno = ErrorTypeToStringMap::get($errno);
378 }catch(\InvalidArgumentException $ex){
379 //pass
380 }
381 }
382
383 $errfile = Filesystem::cleanPath($e->getFile());
384 $errline = $e->getLine();
385
386 return get_class($e) . ": \"$errstr\" ($errno) in \"$errfile\" at line $errline";
387 }
388
394 public static function printableExceptionInfo(\Throwable $e, $trace = null) : array{
395 if($trace === null){
396 $trace = $e->getTrace();
397 }
398
399 $lines = [self::printableExceptionMessage($e)];
400 $lines[] = "--- Stack trace ---";
401 foreach(Utils::printableTrace($trace) as $line){
402 $lines[] = " " . $line;
403 }
404 for($prev = $e->getPrevious(); $prev !== null; $prev = $prev->getPrevious()){
405 $lines[] = "--- Previous ---";
406 $lines[] = self::printableExceptionMessage($prev);
407 foreach(Utils::printableTrace($prev->getTrace()) as $line){
408 $lines[] = " " . $line;
409 }
410 }
411 $lines[] = "--- End of exception information ---";
412 return $lines;
413 }
414
415 private static function stringifyValueForTrace(mixed $value, int $maxStringLength) : string{
416 return match(true){
417 is_object($value) => "object " . self::getNiceClassName($value) . "#" . spl_object_id($value),
418 is_array($value) => "array[" . count($value) . "]",
419 is_string($value) => "string[" . strlen($value) . "] " . substr(Utils::printable($value), 0, $maxStringLength),
420 is_bool($value) => $value ? "true" : "false",
421 is_int($value) => "int " . $value,
422 is_float($value) => "float " . $value,
423 $value === null => "null",
424 default => gettype($value) . " " . Utils::printable((string) $value)
425 };
426 }
427
435 public static function printableTrace(array $trace, int $maxStringLength = 80) : array{
436 $messages = [];
437 for($i = 0; isset($trace[$i]); ++$i){
438 $params = "";
439 if(isset($trace[$i]["args"]) || isset($trace[$i]["params"])){
440 if(isset($trace[$i]["args"])){
441 $args = $trace[$i]["args"];
442 }else{
443 $args = $trace[$i]["params"];
444 }
447 $paramsList = [];
448 $offset = 0;
449 foreach($args as $argId => $value){
450 $paramsList[] = ($argId === $offset ? "" : "$argId: ") . self::stringifyValueForTrace($value, $maxStringLength);
451 $offset++;
452 }
453 $params = implode(", ", $paramsList);
454 }
455 $messages[] = "#$i " .
456 (isset($trace[$i]["file"]) ? Filesystem::cleanPath($trace[$i]["file"]) : "") .
457 "(" . (isset($trace[$i]["line"]) ? $trace[$i]["line"] : "") . "): " .
458 (isset($trace[$i]["class"]) ?
459 $trace[$i]["class"] . (($trace[$i]["type"] === "dynamic" || $trace[$i]["type"] === "->") ? "->" : "::") :
460 ""
461 ) .
462 $trace[$i]["function"] .
463 "(" . Utils::printable($params) . ")";
464 }
465 return $messages;
466 }
467
477 public static function printableTraceWithMetadata(array $rawTrace, int $maxStringLength = 80) : array{
478 $printableTrace = self::printableTrace($rawTrace, $maxStringLength);
479 $safeTrace = [];
480 foreach($printableTrace as $frameId => $printableFrame){
481 $rawFrame = $rawTrace[$frameId];
482 $safeTrace[$frameId] = new ThreadCrashInfoFrame(
483 $printableFrame,
484 $rawFrame["file"] ?? null,
485 $rawFrame["line"] ?? 0
486 );
487 }
488
489 return $safeTrace;
490 }
491
496 public static function currentTrace(int $skipFrames = 0) : array{
497 ++$skipFrames; //omit this frame from trace, in addition to other skipped frames
498 if(function_exists("xdebug_get_function_stack") && count($trace = @xdebug_get_function_stack()) !== 0){
499 $trace = array_reverse($trace);
500 }else{
501 $e = new \Exception();
502 $trace = $e->getTrace();
503 }
504 for($i = 0; $i < $skipFrames; ++$i){
505 unset($trace[$i]);
506 }
507 return array_values($trace);
508 }
509
513 public static function printableCurrentTrace(int $skipFrames = 0) : array{
514 return self::printableTrace(self::currentTrace(++$skipFrames));
515 }
516
522 public static function parseDocComment(string $docComment) : array{
523 $rawDocComment = substr($docComment, 3, -2); //remove the opening and closing markers
524 preg_match_all('/(*ANYCRLF)^[\t ]*(?:\* )?@([a-zA-Z\-]+)(?:[\t ]+(.+?))?[\t ]*$/m', $rawDocComment, $matches);
525
526 return array_combine($matches[1], $matches[2]);
527 }
528
533 public static function testValidInstance(string $className, string $baseName) : void{
534 $baseInterface = false;
535 if(!class_exists($baseName)){
536 if(!interface_exists($baseName)){
537 throw new \InvalidArgumentException("Base class $baseName does not exist");
538 }
539 $baseInterface = true;
540 }
541 if(!class_exists($className)){
542 throw new \InvalidArgumentException("Class $className does not exist or is not a class");
543 }
544 if(!is_a($className, $baseName, true)){
545 throw new \InvalidArgumentException("Class $className does not " . ($baseInterface ? "implement" : "extend") . " $baseName");
546 }
547 $class = new \ReflectionClass($className);
548 if(!$class->isInstantiable()){
549 throw new \InvalidArgumentException("Class $className cannot be constructed");
550 }
551 }
552
565 public static function validateCallableSignature(callable|CallbackType $signature, callable $subject) : void{
566 if(!($signature instanceof CallbackType)){
567 $signature = CallbackType::createFromCallable($signature);
568 }
569 if(!$signature->isSatisfiedBy($subject)){
570 throw new \TypeError("Declaration of callable `" . CallbackType::createFromCallable($subject) . "` must be compatible with `" . $signature . "`");
571 }
572 }
573
579 public static function validateArrayValueType(array $array, \Closure $validator) : void{
580 foreach(Utils::promoteKeys($array) as $k => $v){
581 try{
582 $validator($v);
583 }catch(\TypeError $e){
584 throw new \TypeError("Incorrect type of element at \"$k\": " . $e->getMessage(), 0, $e);
585 }
586 }
587 }
588
599 public static function stringifyKeys(array $array) : \Generator{
600 foreach($array as $key => $value){ // @phpstan-ignore-line - this is where we fix the stupid bullshit with array keys :)
601 yield (string) $key => $value;
602 }
603 }
604
613 public static function promoteKeys(array $array) : array{
614 return $array;
615 }
616
617 public static function checkUTF8(string $string) : void{
618 if(!mb_check_encoding($string, 'UTF-8')){
619 throw new \InvalidArgumentException("Text must be valid UTF-8");
620 }
621 }
622
629 public static function assumeNotFalse(mixed $value, \Closure|string $context = "This should never be false") : mixed{
630 if($value === false){
631 throw new AssumptionFailedError("Assumption failure: " . (is_string($context) ? $context : $context()) . " (THIS IS A BUG)");
632 }
633 return $value;
634 }
635
636 public static function checkFloatNotInfOrNaN(string $name, float $float) : void{
637 if(is_nan($float)){
638 throw new \InvalidArgumentException("$name cannot be NaN");
639 }
640 if(is_infinite($float)){
641 throw new \InvalidArgumentException("$name cannot be infinite");
642 }
643 }
644
645 public static function checkVector3NotInfOrNaN(Vector3 $vector3) : void{
646 if($vector3 instanceof Location){ //location could be masquerading as vector3
647 self::checkFloatNotInfOrNaN("yaw", $vector3->yaw);
648 self::checkFloatNotInfOrNaN("pitch", $vector3->pitch);
649 }
650 self::checkFloatNotInfOrNaN("x", $vector3->x);
651 self::checkFloatNotInfOrNaN("y", $vector3->y);
652 self::checkFloatNotInfOrNaN("z", $vector3->z);
653 }
654
655 public static function checkLocationNotInfOrNaN(Location $location) : void{
656 self::checkVector3NotInfOrNaN($location);
657 }
658
663 public static function getOpcacheJitMode() : ?int{
664 if(
665 function_exists('opcache_get_status') &&
666 ($opcacheStatus = opcache_get_status(false)) !== false &&
667 isset($opcacheStatus["jit"]["on"])
668 ){
669 $jit = $opcacheStatus["jit"];
670 if($jit["on"] === true){
671 return (($jit["opt_flags"] >> 2) * 1000) +
672 (($jit["opt_flags"] & 0x03) * 100) +
673 ($jit["kind"] * 10) +
674 $jit["opt_level"];
675 }
676
677 //jit available, but disabled
678 return 0;
679 }
680
681 //jit not available
682 return null;
683 }
684
689 public static function getRandomFloat() : float{
690 return mt_rand() / mt_getrandmax();
691 }
692}
static printableExceptionInfo(\Throwable $e, $trace=null)
Definition Utils.php:394
static parseDocComment(string $docComment)
Definition Utils.php:522
static assumeNotFalse(mixed $value, \Closure|string $context="This should never be false")
Definition Utils.php:629
static validateArrayValueType(array $array, \Closure $validator)
Definition Utils.php:579
static validateCallableSignature(callable|CallbackType $signature, callable $subject)
Definition Utils.php:565
static getMachineUniqueId(string $extra="")
Definition Utils.php:190
static stringifyKeys(array $array)
Definition Utils.php:599
static hexdump(string $bin)
Definition Utils.php:321
static getNiceClosureName(\Closure $closure)
Definition Utils.php:124
static getOS(bool $recalculate=false)
Definition Utils.php:259
static currentTrace(int $skipFrames=0)
Definition Utils.php:496
static printable(mixed $str)
Definition Utils.php:336
static printableTraceWithMetadata(array $rawTrace, int $maxStringLength=80)
Definition Utils.php:477
static testValidInstance(string $className, string $baseName)
Definition Utils.php:533
static getOpcacheJitMode()
Definition Utils.php:663
static getNiceClassName(object $obj)
Definition Utils.php:154
static cloneObjectArray(array $array)
Definition Utils.php:178
static getRandomFloat()
Definition Utils.php:689
static printableTrace(array $trace, int $maxStringLength=80)
Definition Utils.php:435
static printableCurrentTrace(int $skipFrames=0)
Definition Utils.php:513
static promoteKeys(array $array)
Definition Utils.php:613