VarCloner.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\VarDumper\Cloner;
  11. /**
  12. * @author Nicolas Grekas <p@tchwork.com>
  13. */
  14. class VarCloner extends AbstractCloner
  15. {
  16. private static $gid;
  17. private static $hashMask = 0;
  18. private static $hashOffset = 0;
  19. private static $arrayCache = [];
  20. /**
  21. * {@inheritdoc}
  22. */
  23. protected function doClone($var)
  24. {
  25. $len = 1; // Length of $queue
  26. $pos = 0; // Number of cloned items past the minimum depth
  27. $refsCounter = 0; // Hard references counter
  28. $queue = [[$var]]; // This breadth-first queue is the return value
  29. $indexedArrays = []; // Map of queue indexes that hold numerically indexed arrays
  30. $hardRefs = []; // Map of original zval hashes to stub objects
  31. $objRefs = []; // Map of original object handles to their stub object counterpart
  32. $objects = []; // Keep a ref to objects to ensure their handle cannot be reused while cloning
  33. $resRefs = []; // Map of original resource handles to their stub object counterpart
  34. $values = []; // Map of stub objects' hashes to original values
  35. $maxItems = $this->maxItems;
  36. $maxString = $this->maxString;
  37. $minDepth = $this->minDepth;
  38. $currentDepth = 0; // Current tree depth
  39. $currentDepthFinalIndex = 0; // Final $queue index for current tree depth
  40. $minimumDepthReached = 0 === $minDepth; // Becomes true when minimum tree depth has been reached
  41. $cookie = (object) []; // Unique object used to detect hard references
  42. $a = null; // Array cast for nested structures
  43. $stub = null; // Stub capturing the main properties of an original item value
  44. // or null if the original value is used directly
  45. if (!self::$hashMask) {
  46. self::$gid = uniqid(mt_rand(), true); // Unique string used to detect the special $GLOBALS variable
  47. self::initHashMask();
  48. }
  49. $gid = self::$gid;
  50. $hashMask = self::$hashMask;
  51. $hashOffset = self::$hashOffset;
  52. $arrayStub = new Stub();
  53. $arrayStub->type = Stub::TYPE_ARRAY;
  54. $fromObjCast = false;
  55. for ($i = 0; $i < $len; ++$i) {
  56. // Detect when we move on to the next tree depth
  57. if ($i > $currentDepthFinalIndex) {
  58. ++$currentDepth;
  59. $currentDepthFinalIndex = $len - 1;
  60. if ($currentDepth >= $minDepth) {
  61. $minimumDepthReached = true;
  62. }
  63. }
  64. $refs = $vals = $queue[$i];
  65. if (\PHP_VERSION_ID < 70200 && empty($indexedArrays[$i])) {
  66. // see https://wiki.php.net/rfc/convert_numeric_keys_in_object_array_casts
  67. foreach ($vals as $k => $v) {
  68. if (\is_int($k)) {
  69. continue;
  70. }
  71. foreach ([$k => true] as $gk => $gv) {
  72. }
  73. if ($gk !== $k) {
  74. $fromObjCast = true;
  75. $refs = $vals = array_values($queue[$i]);
  76. break;
  77. }
  78. }
  79. }
  80. foreach ($vals as $k => $v) {
  81. // $v is the original value or a stub object in case of hard references
  82. if (\PHP_VERSION_ID >= 70400) {
  83. $zvalIsRef = null !== \ReflectionReference::fromArrayElement($vals, $k);
  84. } else {
  85. $refs[$k] = $cookie;
  86. $zvalIsRef = $vals[$k] === $cookie;
  87. }
  88. if ($zvalIsRef) {
  89. $vals[$k] = &$stub; // Break hard references to make $queue completely
  90. unset($stub); // independent from the original structure
  91. if ($v instanceof Stub && isset($hardRefs[spl_object_hash($v)])) {
  92. $vals[$k] = $refs[$k] = $v;
  93. if ($v->value instanceof Stub && (Stub::TYPE_OBJECT === $v->value->type || Stub::TYPE_RESOURCE === $v->value->type)) {
  94. ++$v->value->refCount;
  95. }
  96. ++$v->refCount;
  97. continue;
  98. }
  99. $refs[$k] = $vals[$k] = new Stub();
  100. $refs[$k]->value = $v;
  101. $h = spl_object_hash($refs[$k]);
  102. $hardRefs[$h] = &$refs[$k];
  103. $values[$h] = $v;
  104. $vals[$k]->handle = ++$refsCounter;
  105. }
  106. // Create $stub when the original value $v can not be used directly
  107. // If $v is a nested structure, put that structure in array $a
  108. switch (true) {
  109. case null === $v:
  110. case \is_bool($v):
  111. case \is_int($v):
  112. case \is_float($v):
  113. continue 2;
  114. case \is_string($v):
  115. if ('' === $v) {
  116. continue 2;
  117. }
  118. if (!preg_match('//u', $v)) {
  119. $stub = new Stub();
  120. $stub->type = Stub::TYPE_STRING;
  121. $stub->class = Stub::STRING_BINARY;
  122. if (0 <= $maxString && 0 < $cut = \strlen($v) - $maxString) {
  123. $stub->cut = $cut;
  124. $stub->value = substr($v, 0, -$cut);
  125. } else {
  126. $stub->value = $v;
  127. }
  128. } elseif (0 <= $maxString && isset($v[1 + ($maxString >> 2)]) && 0 < $cut = mb_strlen($v, 'UTF-8') - $maxString) {
  129. $stub = new Stub();
  130. $stub->type = Stub::TYPE_STRING;
  131. $stub->class = Stub::STRING_UTF8;
  132. $stub->cut = $cut;
  133. $stub->value = mb_substr($v, 0, $maxString, 'UTF-8');
  134. } else {
  135. continue 2;
  136. }
  137. $a = null;
  138. break;
  139. case \is_array($v):
  140. if (!$v) {
  141. continue 2;
  142. }
  143. $stub = $arrayStub;
  144. $stub->class = Stub::ARRAY_INDEXED;
  145. $j = -1;
  146. foreach ($v as $gk => $gv) {
  147. if ($gk !== ++$j) {
  148. $stub->class = Stub::ARRAY_ASSOC;
  149. break;
  150. }
  151. }
  152. $a = $v;
  153. if (Stub::ARRAY_ASSOC === $stub->class) {
  154. // Copies of $GLOBALS have very strange behavior,
  155. // let's detect them with some black magic
  156. $a[$gid] = true;
  157. // Happens with copies of $GLOBALS
  158. if (isset($v[$gid])) {
  159. unset($v[$gid]);
  160. $a = [];
  161. foreach ($v as $gk => &$gv) {
  162. $a[$gk] = &$gv;
  163. }
  164. unset($gv);
  165. } else {
  166. $a = $v;
  167. }
  168. } elseif (\PHP_VERSION_ID < 70200) {
  169. $indexedArrays[$len] = true;
  170. }
  171. break;
  172. case \is_object($v):
  173. case $v instanceof \__PHP_Incomplete_Class:
  174. if (empty($objRefs[$h = $hashMask ^ hexdec(substr(spl_object_hash($v), $hashOffset, \PHP_INT_SIZE))])) {
  175. $stub = new Stub();
  176. $stub->type = Stub::TYPE_OBJECT;
  177. $stub->class = \get_class($v);
  178. $stub->value = $v;
  179. $stub->handle = $h;
  180. $a = $this->castObject($stub, 0 < $i);
  181. if ($v !== $stub->value) {
  182. if (Stub::TYPE_OBJECT !== $stub->type || null === $stub->value) {
  183. break;
  184. }
  185. $h = $hashMask ^ hexdec(substr(spl_object_hash($stub->value), $hashOffset, \PHP_INT_SIZE));
  186. $stub->handle = $h;
  187. }
  188. $stub->value = null;
  189. if (0 <= $maxItems && $maxItems <= $pos && $minimumDepthReached) {
  190. $stub->cut = \count($a);
  191. $a = null;
  192. }
  193. }
  194. if (empty($objRefs[$h])) {
  195. $objRefs[$h] = $stub;
  196. $objects[] = $v;
  197. } else {
  198. $stub = $objRefs[$h];
  199. ++$stub->refCount;
  200. $a = null;
  201. }
  202. break;
  203. default: // resource
  204. if (empty($resRefs[$h = (int) $v])) {
  205. $stub = new Stub();
  206. $stub->type = Stub::TYPE_RESOURCE;
  207. if ('Unknown' === $stub->class = @get_resource_type($v)) {
  208. $stub->class = 'Closed';
  209. }
  210. $stub->value = $v;
  211. $stub->handle = $h;
  212. $a = $this->castResource($stub, 0 < $i);
  213. $stub->value = null;
  214. if (0 <= $maxItems && $maxItems <= $pos && $minimumDepthReached) {
  215. $stub->cut = \count($a);
  216. $a = null;
  217. }
  218. }
  219. if (empty($resRefs[$h])) {
  220. $resRefs[$h] = $stub;
  221. } else {
  222. $stub = $resRefs[$h];
  223. ++$stub->refCount;
  224. $a = null;
  225. }
  226. break;
  227. }
  228. if ($a) {
  229. if (!$minimumDepthReached || 0 > $maxItems) {
  230. $queue[$len] = $a;
  231. $stub->position = $len++;
  232. } elseif ($pos < $maxItems) {
  233. if ($maxItems < $pos += \count($a)) {
  234. $a = \array_slice($a, 0, $maxItems - $pos);
  235. if ($stub->cut >= 0) {
  236. $stub->cut += $pos - $maxItems;
  237. }
  238. }
  239. $queue[$len] = $a;
  240. $stub->position = $len++;
  241. } elseif ($stub->cut >= 0) {
  242. $stub->cut += \count($a);
  243. $stub->position = 0;
  244. }
  245. }
  246. if ($arrayStub === $stub) {
  247. if ($arrayStub->cut) {
  248. $stub = [$arrayStub->cut, $arrayStub->class => $arrayStub->position];
  249. $arrayStub->cut = 0;
  250. } elseif (isset(self::$arrayCache[$arrayStub->class][$arrayStub->position])) {
  251. $stub = self::$arrayCache[$arrayStub->class][$arrayStub->position];
  252. } else {
  253. self::$arrayCache[$arrayStub->class][$arrayStub->position] = $stub = [$arrayStub->class => $arrayStub->position];
  254. }
  255. }
  256. if ($zvalIsRef) {
  257. $refs[$k]->value = $stub;
  258. } else {
  259. $vals[$k] = $stub;
  260. }
  261. }
  262. if ($fromObjCast) {
  263. $fromObjCast = false;
  264. $refs = $vals;
  265. $vals = [];
  266. $j = -1;
  267. foreach ($queue[$i] as $k => $v) {
  268. foreach ([$k => true] as $gk => $gv) {
  269. }
  270. if ($gk !== $k) {
  271. $vals = (object) $vals;
  272. $vals->{$k} = $refs[++$j];
  273. $vals = (array) $vals;
  274. } else {
  275. $vals[$k] = $refs[++$j];
  276. }
  277. }
  278. }
  279. $queue[$i] = $vals;
  280. }
  281. foreach ($values as $h => $v) {
  282. $hardRefs[$h] = $v;
  283. }
  284. return $queue;
  285. }
  286. private static function initHashMask()
  287. {
  288. $obj = (object) [];
  289. self::$hashOffset = 16 - PHP_INT_SIZE;
  290. self::$hashMask = -1;
  291. if (\defined('HHVM_VERSION')) {
  292. self::$hashOffset += 16;
  293. } else {
  294. // check if we are nested in an output buffering handler to prevent a fatal error with ob_start() below
  295. $obFuncs = ['ob_clean', 'ob_end_clean', 'ob_flush', 'ob_end_flush', 'ob_get_contents', 'ob_get_flush'];
  296. foreach (debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) as $frame) {
  297. if (isset($frame['function'][0]) && !isset($frame['class']) && 'o' === $frame['function'][0] && \in_array($frame['function'], $obFuncs)) {
  298. $frame['line'] = 0;
  299. break;
  300. }
  301. }
  302. if (!empty($frame['line'])) {
  303. ob_start();
  304. debug_zval_dump($obj);
  305. self::$hashMask = (int) substr(ob_get_clean(), 17);
  306. }
  307. }
  308. self::$hashMask ^= hexdec(substr(spl_object_hash($obj), self::$hashOffset, PHP_INT_SIZE));
  309. }
  310. }