1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 5                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2014 The PHP Group                                |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 3.01 of the PHP license,      |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available through the world-wide-web at the following url:           |
10   | http://www.php.net/license/3_01.txt                                  |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Authors: Jani Lehtimäki <jkl@njet.net>                               |
16   |          Thies C. Arntzen <thies@thieso.net>                         |
17   |          Sascha Schumann <sascha@schumann.cx>                        |
18   +----------------------------------------------------------------------+
19*/
20
21/* $Id$ */
22
23/* {{{ includes
24*/
25#include <stdio.h>
26#include <stdlib.h>
27#include <errno.h>
28#include "php.h"
29#include "php_string.h"
30#include "php_var.h"
31#include "php_smart_str.h"
32#include "basic_functions.h"
33#include "php_incomplete_class.h"
34
35#define COMMON (is_ref ? "&" : "")
36/* }}} */
37
38static uint zend_obj_num_elements(HashTable *ht)
39{
40    Bucket *p;
41    uint idx;
42    uint num;
43
44    num = ht->nNumOfElements;
45    for (idx = 0; idx < ht->nNumUsed; idx++) {
46        p = ht->arData + idx;
47        if (Z_TYPE(p->val) == IS_UNDEF) continue;
48        if (Z_TYPE(p->val) == IS_INDIRECT) {
49            if (Z_TYPE_P(Z_INDIRECT(p->val)) == IS_UNDEF) {
50                num--;
51            }
52        }
53    }
54    return num;
55}
56
57static void php_array_element_dump(zval *zv, zend_ulong index, zend_string *key, int level TSRMLS_DC) /* {{{ */
58{
59    if (key == NULL) { /* numeric key */
60        php_printf("%*c[" ZEND_LONG_FMT "]=>\n", level + 1, ' ', index);
61    } else { /* string key */
62        php_printf("%*c[\"", level + 1, ' ');
63        PHPWRITE(key->val, key->len);
64        php_printf("\"]=>\n");
65        }
66    php_var_dump(zv, level + 2 TSRMLS_CC);
67}
68/* }}} */
69
70static void php_object_property_dump(zval *zv, zend_ulong index, zend_string *key, int level TSRMLS_DC) /* {{{ */
71{
72    const char *prop_name, *class_name;
73
74    if (key == NULL) { /* numeric key */
75        php_printf("%*c[" ZEND_LONG_FMT "]=>\n", level + 1, ' ', index);
76    } else { /* string key */
77        int unmangle = zend_unmangle_property_name(key, &class_name, &prop_name);
78        php_printf("%*c[", level + 1, ' ');
79
80        if (class_name && unmangle == SUCCESS) {
81            if (class_name[0] == '*') {
82                php_printf("\"%s\":protected", prop_name);
83            } else {
84                php_printf("\"%s\":\"%s\":private", prop_name, class_name);
85            }
86        } else {
87            php_printf("\"");
88            PHPWRITE(key->val, key->len);
89            php_printf("\"");
90        }
91        ZEND_PUTS("]=>\n");
92    }
93    php_var_dump(zv, level + 2 TSRMLS_CC);
94}
95/* }}} */
96
97PHPAPI void php_var_dump(zval *struc, int level TSRMLS_DC) /* {{{ */
98{
99    HashTable *myht;
100    zend_string *class_name;
101    int is_temp;
102    int is_ref = 0;
103    zend_ulong num;
104    zend_string *key;
105    zval *val;
106
107    if (level > 1) {
108        php_printf("%*c", level - 1, ' ');
109    }
110
111again:
112    switch (Z_TYPE_P(struc)) {
113        case IS_FALSE:
114            php_printf("%sbool(false)\n", COMMON);
115            break;
116        case IS_TRUE:
117            php_printf("%sbool(true)\n", COMMON);
118            break;
119        case IS_NULL:
120            php_printf("%sNULL\n", COMMON);
121            break;
122        case IS_LONG:
123            php_printf("%sint(" ZEND_LONG_FMT ")\n", COMMON, Z_LVAL_P(struc));
124            break;
125        case IS_DOUBLE:
126            php_printf("%sfloat(%.*G)\n", COMMON, (int) EG(precision), Z_DVAL_P(struc));
127            break;
128        case IS_STRING:
129            php_printf("%sstring(%d) \"", COMMON, Z_STRLEN_P(struc));
130            PHPWRITE(Z_STRVAL_P(struc), Z_STRLEN_P(struc));
131            PUTS("\"\n");
132            break;
133        case IS_ARRAY:
134            myht = Z_ARRVAL_P(struc);
135            if (level > 1 && ZEND_HASH_APPLY_PROTECTION(myht) && ++myht->u.v.nApplyCount > 1) {
136                PUTS("*RECURSION*\n");
137                --myht->u.v.nApplyCount;
138                return;
139            }
140            php_printf("%sarray(%d) {\n", COMMON, zend_hash_num_elements(myht));
141            is_temp = 0;
142
143            ZEND_HASH_FOREACH_KEY_VAL_IND(myht, num, key, val) {
144                php_array_element_dump(val, num, key, level TSRMLS_CC);
145            } ZEND_HASH_FOREACH_END();
146            if (level > 1 && ZEND_HASH_APPLY_PROTECTION(myht)) {
147                --myht->u.v.nApplyCount;
148            }
149            if (is_temp) {
150                zend_hash_destroy(myht);
151                efree(myht);
152            }
153            if (level > 1) {
154                php_printf("%*c", level-1, ' ');
155            }
156            PUTS("}\n");
157            break;
158        case IS_OBJECT:
159            myht = Z_OBJDEBUG_P(struc, is_temp);
160            if (myht && ++myht->u.v.nApplyCount > 1) {
161                PUTS("*RECURSION*\n");
162                --myht->u.v.nApplyCount;
163                return;
164            }
165
166            if (Z_OBJ_HANDLER_P(struc, get_class_name)) {
167                class_name = Z_OBJ_HANDLER_P(struc, get_class_name)(Z_OBJ_P(struc), 0 TSRMLS_CC);
168                php_printf("%sobject(%s)#%d (%d) {\n", COMMON, class_name->val, Z_OBJ_HANDLE_P(struc), myht ? zend_obj_num_elements(myht) : 0);
169                zend_string_release(class_name);
170            } else {
171                php_printf("%sobject(unknown class)#%d (%d) {\n", COMMON, Z_OBJ_HANDLE_P(struc), myht ? zend_obj_num_elements(myht) : 0);
172            }
173            if (myht) {
174                zend_ulong num;
175                zend_string *key;
176                zval *val;
177
178                ZEND_HASH_FOREACH_KEY_VAL_IND(myht, num, key, val) {
179                    php_object_property_dump(val, num, key, level TSRMLS_CC);
180                } ZEND_HASH_FOREACH_END();
181                --myht->u.v.nApplyCount;
182                if (is_temp) {
183                    zend_hash_destroy(myht);
184                    efree(myht);
185                }
186            }
187            if (level > 1) {
188                php_printf("%*c", level-1, ' ');
189            }
190            PUTS("}\n");
191            break;
192        case IS_RESOURCE: {
193            const char *type_name = zend_rsrc_list_get_rsrc_type(Z_RES_P(struc) TSRMLS_CC);
194            php_printf("%sresource(%pd) of type (%s)\n", COMMON, Z_RES_P(struc)->handle, type_name ? type_name : "Unknown");
195            break;
196        }
197        case IS_REFERENCE:
198            //??? hide references with refcount==1 (for compatibility)
199            if (Z_REFCOUNT_P(struc) > 1) {
200                is_ref = 1;
201            }
202            struc = Z_REFVAL_P(struc);
203            goto again;
204            break;
205        default:
206            php_printf("%sUNKNOWN:0\n", COMMON);
207            break;
208    }
209}
210/* }}} */
211
212/* {{{ proto void var_dump(mixed var)
213   Dumps a string representation of variable to output */
214PHP_FUNCTION(var_dump)
215{
216    zval *args;
217    int argc;
218    int i;
219
220    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) {
221        return;
222    }
223
224    for (i = 0; i < argc; i++) {
225        php_var_dump(&args[i], 1 TSRMLS_CC);
226    }
227}
228/* }}} */
229
230static void zval_array_element_dump(zval *zv, zend_ulong index, zend_string *key, int level TSRMLS_DC) /* {{{ */
231{
232    if (key == NULL) { /* numeric key */
233        php_printf("%*c[" ZEND_LONG_FMT "]=>\n", level + 1, ' ', index);
234    } else { /* string key */
235        php_printf("%*c[\"", level + 1, ' ');
236        PHPWRITE(key->val, key->len);
237        php_printf("\"]=>\n");
238    }
239    php_debug_zval_dump(zv, level + 2 TSRMLS_CC);
240}
241/* }}} */
242
243static void zval_object_property_dump(zval *zv, zend_ulong index, zend_string *key, int level TSRMLS_DC) /* {{{ */
244{
245    const char *prop_name, *class_name;
246
247    if (key == NULL) { /* numeric key */
248        php_printf("%*c[" ZEND_LONG_FMT "]=>\n", level + 1, ' ', index);
249    } else { /* string key */
250        zend_unmangle_property_name(key, &class_name, &prop_name);
251        php_printf("%*c[", level + 1, ' ');
252
253        if (class_name) {
254            if (class_name[0] == '*') {
255                php_printf("\"%s\":protected", prop_name);
256            } else {
257                php_printf("\"%s\":\"%s\":private", prop_name, class_name);
258            }
259        } else {
260            php_printf("\"%s\"", prop_name);
261        }
262        ZEND_PUTS("]=>\n");
263    }
264    php_debug_zval_dump(zv, level + 2 TSRMLS_CC);
265}
266/* }}} */
267
268PHPAPI void php_debug_zval_dump(zval *struc, int level TSRMLS_DC) /* {{{ */
269{
270    HashTable *myht = NULL;
271    zend_string *class_name;
272    int is_temp = 0;
273    int is_ref = 0;
274    zend_ulong index;
275    zend_string *key;
276    zval *val;
277
278    if (level > 1) {
279        php_printf("%*c", level - 1, ' ');
280    }
281
282again:
283    switch (Z_TYPE_P(struc)) {
284    case IS_FALSE:
285        php_printf("%sbool(false)\n", COMMON);
286        break;
287    case IS_TRUE:
288        php_printf("%sbool(true)\n", COMMON);
289        break;
290    case IS_NULL:
291        php_printf("%sNULL\n", COMMON);
292        break;
293    case IS_LONG:
294        php_printf("%slong(" ZEND_LONG_FMT ")\n", COMMON, Z_LVAL_P(struc));
295        break;
296    case IS_DOUBLE:
297        php_printf("%sdouble(%.*G)\n", COMMON, (int) EG(precision), Z_DVAL_P(struc));
298        break;
299    case IS_STRING:
300        php_printf("%sstring(%d) \"", COMMON, Z_STRLEN_P(struc));
301        PHPWRITE(Z_STRVAL_P(struc), Z_STRLEN_P(struc));
302        php_printf("\" refcount(%u)\n", IS_INTERNED(Z_STR_P(struc)) ? 1 : Z_REFCOUNT_P(struc));
303        break;
304    case IS_ARRAY:
305        myht = Z_ARRVAL_P(struc);
306        if (level > 1 && ZEND_HASH_APPLY_PROTECTION(myht) && myht->u.v.nApplyCount++ > 1) {
307            myht->u.v.nApplyCount--;
308            PUTS("*RECURSION*\n");
309            return;
310        }
311        php_printf("%sarray(%d) refcount(%u){\n", COMMON, zend_hash_num_elements(myht), Z_REFCOUNTED_P(struc) ? Z_REFCOUNT_P(struc) : 1);
312        ZEND_HASH_FOREACH_KEY_VAL_IND(myht, index, key, val) {
313            zval_array_element_dump(val, index, key, level TSRMLS_CC);
314        } ZEND_HASH_FOREACH_END();
315        if (level > 1 && ZEND_HASH_APPLY_PROTECTION(myht)) {
316            myht->u.v.nApplyCount--;
317        }
318        if (is_temp) {
319            zend_hash_destroy(myht);
320            efree(myht);
321        }
322        if (level > 1) {
323            php_printf("%*c", level - 1, ' ');
324        }
325        PUTS("}\n");
326        break;
327    case IS_OBJECT:
328        myht = Z_OBJDEBUG_P(struc, is_temp);
329        if (myht) {
330            if (myht->u.v.nApplyCount > 1) {
331                PUTS("*RECURSION*\n");
332                return;
333            } else {
334                myht->u.v.nApplyCount++;
335            }
336        }
337        class_name = Z_OBJ_HANDLER_P(struc, get_class_name)(Z_OBJ_P(struc), 0 TSRMLS_CC);
338        php_printf("%sobject(%s)#%d (%d) refcount(%u){\n", COMMON, class_name->val, Z_OBJ_HANDLE_P(struc), myht ? zend_obj_num_elements(myht) : 0, Z_REFCOUNT_P(struc));
339        zend_string_release(class_name);
340        if (myht) {
341            ZEND_HASH_FOREACH_KEY_VAL_IND(myht, index, key, val) {
342                zval_object_property_dump(val, index, key, level TSRMLS_CC);
343            } ZEND_HASH_FOREACH_END();
344            myht->u.v.nApplyCount--;
345            if (is_temp) {
346                zend_hash_destroy(myht);
347                efree(myht);
348            }
349        }
350        if (level > 1) {
351            php_printf("%*c", level - 1, ' ');
352        }
353        PUTS("}\n");
354        break;
355    case IS_RESOURCE: {
356        const char *type_name = zend_rsrc_list_get_rsrc_type(Z_RES_P(struc) TSRMLS_CC);
357        php_printf("%sresource(" ZEND_LONG_FMT ") of type (%s) refcount(%u)\n", COMMON, Z_RES_P(struc)->handle, type_name ? type_name : "Unknown", Z_REFCOUNT_P(struc));
358        break;
359    }
360    case IS_REFERENCE:
361        //??? hide references with refcount==1 (for compatibility)
362        if (Z_REFCOUNT_P(struc) > 1) {
363            is_ref = 1;
364        }
365        struc = Z_REFVAL_P(struc);
366        goto again;
367    default:
368        php_printf("%sUNKNOWN:0\n", COMMON);
369        break;
370    }
371}
372/* }}} */
373
374/* {{{ proto void debug_zval_dump(mixed var)
375   Dumps a string representation of an internal zend value to output. */
376PHP_FUNCTION(debug_zval_dump)
377{
378    zval *args;
379    int argc;
380    int i;
381
382    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) {
383        return;
384    }
385
386    for (i = 0; i < argc; i++) {
387        php_debug_zval_dump(&args[i], 1 TSRMLS_CC);
388    }
389}
390/* }}} */
391
392#define buffer_append_spaces(buf, num_spaces) \
393    do { \
394        char *tmp_spaces; \
395        int tmp_spaces_len; \
396        tmp_spaces_len = spprintf(&tmp_spaces, 0,"%*c", num_spaces, ' '); \
397        smart_str_appendl(buf, tmp_spaces, tmp_spaces_len); \
398        efree(tmp_spaces); \
399    } while(0);
400
401static void php_array_element_export(zval *zv, zend_ulong index, zend_string *key, int level, smart_str *buf TSRMLS_DC) /* {{{ */
402{
403    if (key == NULL) { /* numeric key */
404        buffer_append_spaces(buf, level+1);
405        smart_str_append_long(buf, (zend_long) index);
406        smart_str_appendl(buf, " => ", 4);
407
408    } else { /* string key */
409        zend_string *tmp_str;
410        zend_string *ckey = php_addcslashes(key->val, key->len, 0, "'\\", 2 TSRMLS_CC);
411        tmp_str = php_str_to_str_ex(ckey->val, ckey->len, "\0", 1, "' . \"\\0\" . '", 12, 0, NULL);
412
413        buffer_append_spaces(buf, level + 1);
414
415        smart_str_appendc(buf, '\'');
416        smart_str_appendl(buf, tmp_str->val, tmp_str->len);
417        smart_str_appendl(buf, "' => ", 5);
418
419        zend_string_free(ckey);
420        zend_string_free(tmp_str);
421    }
422    php_var_export_ex(zv, level + 2, buf TSRMLS_CC);
423
424    smart_str_appendc(buf, ',');
425    smart_str_appendc(buf, '\n');
426}
427/* }}} */
428
429static void php_object_element_export(zval *zv, zend_ulong index, zend_string *key, int level, smart_str *buf TSRMLS_DC) /* {{{ */
430{
431    buffer_append_spaces(buf, level + 2);
432    if (key != NULL) {
433        const char *class_name, *prop_name;
434        size_t prop_name_len;
435        zend_string *pname_esc;
436
437        zend_unmangle_property_name_ex(key, &class_name, &prop_name, &prop_name_len);
438        pname_esc = php_addcslashes(prop_name, prop_name_len, 0, "'\\", 2 TSRMLS_CC);
439
440        smart_str_appendc(buf, '\'');
441        smart_str_appendl(buf, pname_esc->val, pname_esc->len);
442        smart_str_appendc(buf, '\'');
443        zend_string_release(pname_esc);
444    } else {
445        smart_str_append_long(buf, (zend_long) index);
446    }
447    smart_str_appendl(buf, " => ", 4);
448    php_var_export_ex(zv, level + 2, buf TSRMLS_CC);
449    smart_str_appendc(buf, ',');
450    smart_str_appendc(buf, '\n');
451}
452/* }}} */
453
454PHPAPI void php_var_export_ex(zval *struc, int level, smart_str *buf TSRMLS_DC) /* {{{ */
455{
456    HashTable *myht;
457    char *tmp_str;
458    size_t tmp_len;
459    zend_string *class_name;
460    zend_string *ztmp, *ztmp2;
461    zend_ulong index;
462    zend_string *key;
463    zval *val;
464
465again:
466    switch (Z_TYPE_P(struc)) {
467        case IS_FALSE:
468            smart_str_appendl(buf, "false", 5);
469            break;
470        case IS_TRUE:
471            smart_str_appendl(buf, "true", 4);
472            break;
473        case IS_NULL:
474            smart_str_appendl(buf, "NULL", 4);
475            break;
476        case IS_LONG:
477            smart_str_append_long(buf, Z_LVAL_P(struc));
478            break;
479        case IS_DOUBLE:
480            tmp_len = spprintf(&tmp_str, 0,"%.*H", PG(serialize_precision), Z_DVAL_P(struc));
481            smart_str_appendl(buf, tmp_str, tmp_len);
482            efree(tmp_str);
483            break;
484        case IS_STRING:
485            ztmp = php_addcslashes(Z_STRVAL_P(struc), Z_STRLEN_P(struc), 0, "'\\", 2 TSRMLS_CC);
486            ztmp2 = php_str_to_str_ex(ztmp->val, ztmp->len, "\0", 1, "' . \"\\0\" . '", 12, 0, NULL);
487
488            smart_str_appendc(buf, '\'');
489            smart_str_appendl(buf, ztmp2->val, ztmp2->len);
490            smart_str_appendc(buf, '\'');
491
492            zend_string_free(ztmp);
493            zend_string_free(ztmp2);
494            break;
495        case IS_ARRAY:
496            myht = Z_ARRVAL_P(struc);
497            if (ZEND_HASH_APPLY_PROTECTION(myht) && myht->u.v.nApplyCount++ > 0) {
498                myht->u.v.nApplyCount--;
499                smart_str_appendl(buf, "NULL", 4);
500                zend_error(E_WARNING, "var_export does not handle circular references");
501                return;
502            }
503            if (level > 1) {
504                smart_str_appendc(buf, '\n');
505                buffer_append_spaces(buf, level - 1);
506            }
507            smart_str_appendl(buf, "array (\n", 8);
508            ZEND_HASH_FOREACH_KEY_VAL_IND(myht, index, key, val) {
509                php_array_element_export(val, index, key, level, buf TSRMLS_CC);
510            } ZEND_HASH_FOREACH_END();
511            if (ZEND_HASH_APPLY_PROTECTION(myht)) {
512                myht->u.v.nApplyCount--;
513            }
514            if (level > 1) {
515                buffer_append_spaces(buf, level - 1);
516            }
517            smart_str_appendc(buf, ')');
518
519            break;
520
521        case IS_OBJECT:
522            myht = Z_OBJPROP_P(struc);
523            if (myht) {
524                if (myht->u.v.nApplyCount > 0) {
525                    smart_str_appendl(buf, "NULL", 4);
526                    zend_error(E_WARNING, "var_export does not handle circular references");
527                    return;
528                } else {
529                    myht->u.v.nApplyCount++;
530                }
531            }
532            if (level > 1) {
533                smart_str_appendc(buf, '\n');
534                buffer_append_spaces(buf, level - 1);
535            }
536            class_name = Z_OBJ_HANDLER_P(struc, get_class_name)(Z_OBJ_P(struc), 0 TSRMLS_CC);
537
538            smart_str_appendl(buf, class_name->val, class_name->len);
539            smart_str_appendl(buf, "::__set_state(array(\n", 21);
540
541            zend_string_release(class_name);
542            if (myht) {
543                ZEND_HASH_FOREACH_KEY_VAL_IND(myht, index, key, val) {
544                    php_object_element_export(val, index, key, level, buf TSRMLS_CC);
545                } ZEND_HASH_FOREACH_END();
546                myht->u.v.nApplyCount--;
547            }
548            if (level > 1) {
549                buffer_append_spaces(buf, level - 1);
550            }
551            smart_str_appendl(buf, "))", 2);
552
553            break;
554        case IS_REFERENCE:
555            struc = Z_REFVAL_P(struc);
556            goto again;
557            break;
558        default:
559            smart_str_appendl(buf, "NULL", 4);
560            break;
561    }
562}
563/* }}} */
564
565/* FOR BC reasons, this will always perform and then print */
566PHPAPI void php_var_export(zval *struc, int level TSRMLS_DC) /* {{{ */
567{
568    smart_str buf = {0};
569    php_var_export_ex(struc, level, &buf TSRMLS_CC);
570    smart_str_0(&buf);
571    PHPWRITE(buf.s->val, buf.s->len);
572    smart_str_free(&buf);
573}
574/* }}} */
575
576
577/* {{{ proto mixed var_export(mixed var [, bool return])
578   Outputs or returns a string representation of a variable */
579PHP_FUNCTION(var_export)
580{
581    zval *var;
582    zend_bool return_output = 0;
583    smart_str buf = {0};
584
585    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|b", &var, &return_output) == FAILURE) {
586        return;
587    }
588
589    php_var_export_ex(var, 1, &buf TSRMLS_CC);
590    smart_str_0 (&buf);
591
592    if (return_output) {
593        RETURN_STR(buf.s);
594    } else {
595        PHPWRITE(buf.s->val, buf.s->len);
596        smart_str_free(&buf);
597    }
598}
599/* }}} */
600
601static void php_var_serialize_intern(smart_str *buf, zval *struc, HashTable *var_hash TSRMLS_DC);
602
603static inline int php_add_var_hash(HashTable *var_hash, zval *var_ptr, zval *var_old TSRMLS_DC) /* {{{ */
604{
605    zval var_no, *zv;
606    char id[32], *p;
607    register int len;
608    zval *var = var_ptr;
609
610    if (Z_ISREF_P(var)) {
611        var = Z_REFVAL_P(var);
612    }
613    if ((Z_TYPE_P(var) == IS_OBJECT) && Z_OBJ_HT_P(var)->get_class_entry) {
614        p = smart_str_print_long(id + sizeof(id) - 1,
615                (zend_long) Z_OBJ_P(var));
616        *(--p) = 'O';
617        len = id + sizeof(id) - 1 - p;
618    } else if (var_ptr != var) {
619        p = smart_str_print_long(id + sizeof(id) - 1,
620                (zend_long) Z_REF_P(var_ptr));
621        *(--p) = 'R';
622        len = id + sizeof(id) - 1 - p;
623    } else {
624        p = smart_str_print_long(id + sizeof(id) - 1, (zend_long) var);
625        len = id + sizeof(id) - 1 - p;
626    }
627
628    if ((zv = zend_hash_str_find(var_hash, p, len)) != NULL) {
629        ZVAL_COPY_VALUE(var_old, zv);
630        if (var == var_ptr) {
631            /* we still need to bump up the counter, since non-refs will
632             * be counted separately by unserializer */
633            ZVAL_LONG(&var_no, -1);
634            zend_hash_next_index_insert(var_hash, &var_no);
635        }
636#if 0
637        fprintf(stderr, "- had var (%d): %lu\n", Z_TYPE_P(var), **(zend_ulong**)var_old);
638#endif
639        return FAILURE;
640    }
641
642    /* +1 because otherwise hash will think we are trying to store NULL pointer */
643    ZVAL_LONG(&var_no, zend_hash_num_elements(var_hash) + 1);
644    zend_hash_str_add(var_hash, p, len, &var_no);
645#if 0
646    fprintf(stderr, "+ add var (%d): %lu\n", Z_TYPE_P(var), Z_LVAL(var_no));
647#endif
648    return SUCCESS;
649}
650/* }}} */
651
652static inline void php_var_serialize_long(smart_str *buf, zend_long val) /* {{{ */
653{
654    smart_str_appendl(buf, "i:", 2);
655    smart_str_append_long(buf, val);
656    smart_str_appendc(buf, ';');
657}
658/* }}} */
659
660static inline void php_var_serialize_string(smart_str *buf, char *str, int len) /* {{{ */
661{
662    smart_str_appendl(buf, "s:", 2);
663    smart_str_append_long(buf, len);
664    smart_str_appendl(buf, ":\"", 2);
665    smart_str_appendl(buf, str, len);
666    smart_str_appendl(buf, "\";", 2);
667}
668/* }}} */
669
670static inline zend_bool php_var_serialize_class_name(smart_str *buf, zval *struc TSRMLS_DC) /* {{{ */
671{
672    PHP_CLASS_ATTRIBUTES;
673
674    PHP_SET_CLASS_ATTRIBUTES(struc);
675    smart_str_appendl(buf, "O:", 2);
676    smart_str_append_long(buf, (int)class_name->len);
677    smart_str_appendl(buf, ":\"", 2);
678    smart_str_appendl(buf, class_name->val, class_name->len);
679    smart_str_appendl(buf, "\":", 2);
680    PHP_CLEANUP_CLASS_ATTRIBUTES();
681    return incomplete_class;
682}
683/* }}} */
684
685static void php_var_serialize_class(smart_str *buf, zval *struc, zval *retval_ptr, HashTable *var_hash TSRMLS_DC) /* {{{ */
686{
687    int count;
688    zend_bool incomplete_class;
689
690    incomplete_class = php_var_serialize_class_name(buf, struc TSRMLS_CC);
691    /* count after serializing name, since php_var_serialize_class_name
692     * changes the count if the variable is incomplete class */
693    count = zend_hash_num_elements(HASH_OF(retval_ptr));
694    if (incomplete_class) {
695        --count;
696    }
697    smart_str_append_long(buf, count);
698    smart_str_appendl(buf, ":{", 2);
699
700    if (count > 0) {
701        zend_string *key;
702        zval *d, *name;
703        zval nval, *nvalp;
704        HashTable *propers, *ht;
705
706        ZVAL_NULL(&nval);
707        nvalp = &nval;
708
709        ht = HASH_OF(retval_ptr);
710        ZEND_HASH_FOREACH_STR_KEY_VAL(ht, key, name) {
711            if (incomplete_class && strcmp(key->val, MAGIC_MEMBER) == 0) {
712                continue;
713            }
714
715            if (Z_TYPE_P(name) != IS_STRING) {
716                php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize.");
717                /* we should still add element even if it's not OK,
718                 * since we already wrote the length of the array before */
719                smart_str_appendl(buf,"N;", 2);
720                continue;
721            }
722            propers = Z_OBJPROP_P(struc);
723            if ((d = zend_hash_find(propers, Z_STR_P(name))) != NULL) {
724                if (Z_TYPE_P(d) == IS_INDIRECT) {
725                    d = Z_INDIRECT_P(d);
726                    if (Z_TYPE_P(d) == IS_UNDEF) {
727                        continue;
728                    }
729                }
730                php_var_serialize_string(buf, Z_STRVAL_P(name), Z_STRLEN_P(name));
731                php_var_serialize_intern(buf, d, var_hash TSRMLS_CC);
732            } else {
733                zend_class_entry *ce;
734                ce = zend_get_class_entry(Z_OBJ_P(struc) TSRMLS_CC);
735                if (ce) {
736                    zend_string *prot_name, *priv_name;
737
738                    do {
739                        priv_name = zend_mangle_property_name(ce->name->val, ce->name->len, Z_STRVAL_P(name), Z_STRLEN_P(name), ce->type & ZEND_INTERNAL_CLASS);
740                        if ((d = zend_hash_find(propers, priv_name)) != NULL) {
741                            if (Z_TYPE_P(d) == IS_INDIRECT) {
742                                d = Z_INDIRECT_P(d);
743                                if (Z_ISUNDEF_P(d)) {
744                                    break;
745                                }
746                            }
747                            php_var_serialize_string(buf, priv_name->val, priv_name->len);
748                            zend_string_free(priv_name);
749                            php_var_serialize_intern(buf, d, var_hash TSRMLS_CC);
750                            break;
751                        }
752                        zend_string_free(priv_name);
753                        prot_name = zend_mangle_property_name("*", 1, Z_STRVAL_P(name), Z_STRLEN_P(name), ce->type & ZEND_INTERNAL_CLASS);
754                        if ((d = zend_hash_find(propers, prot_name)) != NULL) {
755                            if (Z_TYPE_P(d) == IS_INDIRECT) {
756                                d = Z_INDIRECT_P(d);
757                                if (Z_TYPE_P(d) == IS_UNDEF) {
758                                    zend_string_free(prot_name);
759                                    break;
760                                }
761                            }
762                            php_var_serialize_string(buf, prot_name->val, prot_name->len);
763                            zend_string_free(prot_name);
764                            php_var_serialize_intern(buf, d, var_hash TSRMLS_CC);
765                            break;
766                        }
767                        zend_string_free(prot_name);
768                        php_var_serialize_string(buf, Z_STRVAL_P(name), Z_STRLEN_P(name));
769                        php_var_serialize_intern(buf, nvalp, var_hash TSRMLS_CC);
770                        php_error_docref(NULL TSRMLS_CC, E_NOTICE, "\"%s\" returned as member variable from __sleep() but does not exist", Z_STRVAL_P(name));
771                    } while (0);
772                } else {
773                    php_var_serialize_string(buf, Z_STRVAL_P(name), Z_STRLEN_P(name));
774                    php_var_serialize_intern(buf, nvalp, var_hash TSRMLS_CC);
775                }
776            }
777        } ZEND_HASH_FOREACH_END();
778    }
779    smart_str_appendc(buf, '}');
780}
781/* }}} */
782
783static void php_var_serialize_intern(smart_str *buf, zval *struc, HashTable *var_hash TSRMLS_DC) /* {{{ */
784{
785    int i;
786    zval var_already;
787    HashTable *myht;
788
789    if (EG(exception)) {
790        return;
791    }
792
793    ZVAL_UNDEF(&var_already);
794
795    if (var_hash &&
796        php_add_var_hash(var_hash, struc, &var_already TSRMLS_CC) == FAILURE) {
797        if (Z_ISREF_P(struc)) {
798            smart_str_appendl(buf, "R:", 2);
799            smart_str_append_long(buf, Z_LVAL(var_already));
800            smart_str_appendc(buf, ';');
801            return;
802        } else if (Z_TYPE_P(struc) == IS_OBJECT) {
803            smart_str_appendl(buf, "r:", 2);
804            smart_str_append_long(buf, Z_LVAL(var_already));
805            smart_str_appendc(buf, ';');
806            return;
807        }
808    }
809
810again:
811    switch (Z_TYPE_P(struc)) {
812        case IS_FALSE:
813            smart_str_appendl(buf, "b:0;", 4);
814            return;
815
816        case IS_TRUE:
817            smart_str_appendl(buf, "b:1;", 4);
818            return;
819
820        case IS_NULL:
821            smart_str_appendl(buf, "N;", 2);
822            return;
823
824        case IS_LONG:
825            php_var_serialize_long(buf, Z_LVAL_P(struc));
826            return;
827
828        case IS_DOUBLE: {
829                char *s;
830
831                smart_str_appendl(buf, "d:", 2);
832                s = (char *) safe_emalloc(PG(serialize_precision), 1, MAX_LENGTH_OF_DOUBLE + 1);
833                php_gcvt(Z_DVAL_P(struc), PG(serialize_precision), '.', 'E', s);
834                smart_str_appends(buf, s);
835                smart_str_appendc(buf, ';');
836                efree(s);
837                return;
838            }
839
840        case IS_STRING:
841            php_var_serialize_string(buf, Z_STRVAL_P(struc), Z_STRLEN_P(struc));
842            return;
843
844        case IS_OBJECT: {
845                zval retval;
846                zval fname;
847                int res;
848                zend_class_entry *ce = NULL;
849
850                if (Z_OBJ_HT_P(struc)->get_class_entry) {
851                    ce = Z_OBJCE_P(struc);
852                }
853
854                if (ce && ce->serialize != NULL) {
855                    /* has custom handler */
856                    unsigned char *serialized_data = NULL;
857                    size_t serialized_length;
858
859                    if (ce->serialize(struc, &serialized_data, &serialized_length, (zend_serialize_data *)var_hash TSRMLS_CC) == SUCCESS) {
860                        smart_str_appendl(buf, "C:", 2);
861                        smart_str_append_long(buf, (int)Z_OBJCE_P(struc)->name->len);
862                        smart_str_appendl(buf, ":\"", 2);
863                        smart_str_appendl(buf, Z_OBJCE_P(struc)->name->val, Z_OBJCE_P(struc)->name->len);
864                        smart_str_appendl(buf, "\":", 2);
865
866                        smart_str_append_long(buf, (int)serialized_length);
867                        smart_str_appendl(buf, ":{", 2);
868                        smart_str_appendl(buf, serialized_data, serialized_length);
869                        smart_str_appendc(buf, '}');
870                    } else {
871                        smart_str_appendl(buf, "N;", 2);
872                    }
873                    if (serialized_data) {
874                        efree(serialized_data);
875                    }
876                    return;
877                }
878
879                if (ce && ce != PHP_IC_ENTRY && zend_hash_str_exists(&ce->function_table, "__sleep", sizeof("__sleep")-1)) {
880                    ZVAL_STRINGL(&fname, "__sleep", sizeof("__sleep") - 1);
881                    BG(serialize_lock)++;
882                    res = call_user_function_ex(CG(function_table), struc, &fname, &retval, 0, 0, 1, NULL TSRMLS_CC);
883                    BG(serialize_lock)--;
884                    zval_dtor(&fname);
885
886                    if (EG(exception)) {
887                        zval_ptr_dtor(&retval);
888                        return;
889                    }
890
891                    if (res == SUCCESS) {
892                        if (Z_TYPE(retval) != IS_UNDEF) {
893                            if (HASH_OF(&retval)) {
894                                php_var_serialize_class(buf, struc, &retval, var_hash TSRMLS_CC);
895                            } else {
896                                php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize");
897                                /* we should still add element even if it's not OK,
898                                 * since we already wrote the length of the array before */
899                                smart_str_appendl(buf,"N;", 2);
900                            }
901                            zval_ptr_dtor(&retval);
902                        }
903                        return;
904                    }
905                    zval_ptr_dtor(&retval);
906                }
907
908                /* fall-through */
909            }
910        case IS_ARRAY: {
911            zend_bool incomplete_class = 0;
912            if (Z_TYPE_P(struc) == IS_ARRAY) {
913                smart_str_appendl(buf, "a:", 2);
914                myht = HASH_OF(struc);
915            } else {
916                incomplete_class = php_var_serialize_class_name(buf, struc TSRMLS_CC);
917                myht = Z_OBJPROP_P(struc);
918            }
919            /* count after serializing name, since php_var_serialize_class_name
920             * changes the count if the variable is incomplete class */
921            i = myht ? zend_hash_num_elements(myht) : 0;
922            if (i > 0 && incomplete_class) {
923                --i;
924            }
925            smart_str_append_long(buf, i);
926            smart_str_appendl(buf, ":{", 2);
927            if (i > 0) {
928                zend_string *key;
929                zval *data;
930                zend_ulong index;
931
932                ZEND_HASH_FOREACH_KEY_VAL_IND(myht, index, key, data) {
933
934                    if (incomplete_class && strcmp(key->val, MAGIC_MEMBER) == 0) {
935                        continue;
936                    }
937
938                    if (!key) {
939                        php_var_serialize_long(buf, index);
940                    } else {
941                        php_var_serialize_string(buf, key->val, key->len);
942                    }
943
944                    /* we should still add element even if it's not OK,
945                     * since we already wrote the length of the array before */
946                    if ((Z_TYPE_P(data) == IS_ARRAY && Z_TYPE_P(struc) == IS_ARRAY && Z_ARR_P(data) == Z_ARR_P(struc))
947                        || (Z_TYPE_P(data) == IS_ARRAY && Z_ARRVAL_P(data)->u.v.nApplyCount > 1)
948                    ) {
949                        smart_str_appendl(buf, "N;", 2);
950                    } else {
951                        if (Z_TYPE_P(data) == IS_ARRAY && ZEND_HASH_APPLY_PROTECTION(Z_ARRVAL_P(data))) {
952                            Z_ARRVAL_P(data)->u.v.nApplyCount++;
953                        }
954                        php_var_serialize_intern(buf, data, var_hash TSRMLS_CC);
955                        if (Z_TYPE_P(data) == IS_ARRAY && ZEND_HASH_APPLY_PROTECTION(Z_ARRVAL_P(data))) {
956                            Z_ARRVAL_P(data)->u.v.nApplyCount--;
957                        }
958                    }
959                } ZEND_HASH_FOREACH_END();
960            }
961            smart_str_appendc(buf, '}');
962            return;
963        }
964        case IS_REFERENCE:
965            struc = Z_REFVAL_P(struc);
966            goto again;
967        default:
968            smart_str_appendl(buf, "i:0;", 4);
969            return;
970    }
971}
972/* }}} */
973
974PHPAPI void php_var_serialize(smart_str *buf, zval *struc, php_serialize_data_t *var_hash TSRMLS_DC) /* {{{ */
975{
976    php_var_serialize_intern(buf, struc, *var_hash TSRMLS_CC);
977    smart_str_0(buf);
978}
979/* }}} */
980
981/* {{{ proto string serialize(mixed variable)
982   Returns a string representation of variable (which can later be unserialized) */
983PHP_FUNCTION(serialize)
984{
985    zval *struc;
986    php_serialize_data_t var_hash;
987    smart_str buf = {0};
988
989    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &struc) == FAILURE) {
990        return;
991    }
992
993    PHP_VAR_SERIALIZE_INIT(var_hash);
994    php_var_serialize(&buf, struc, &var_hash TSRMLS_CC);
995    PHP_VAR_SERIALIZE_DESTROY(var_hash);
996
997    if (EG(exception)) {
998        smart_str_free(&buf);
999        RETURN_FALSE;
1000    }
1001
1002    if (buf.s) {
1003        RETURN_STR(buf.s);
1004    } else {
1005        RETURN_NULL();
1006    }
1007}
1008/* }}} */
1009
1010/* {{{ proto mixed unserialize(string variable_representation)
1011   Takes a string representation of variable and recreates it */
1012PHP_FUNCTION(unserialize)
1013{
1014    char *buf = NULL;
1015    size_t buf_len;
1016    const unsigned char *p;
1017    php_unserialize_data_t var_hash;
1018
1019    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) {
1020        RETURN_FALSE;
1021    }
1022
1023    if (buf_len == 0) {
1024        RETURN_FALSE;
1025    }
1026
1027    p = (const unsigned char*) buf;
1028    PHP_VAR_UNSERIALIZE_INIT(var_hash);
1029    if (!php_var_unserialize(return_value, &p, p + buf_len, &var_hash TSRMLS_CC)) {
1030        PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
1031        zval_dtor(return_value);
1032        if (!EG(exception)) {
1033            php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Error at offset " ZEND_LONG_FMT " of %d bytes", (zend_long)((char*)p - buf), buf_len);
1034        }
1035        RETURN_FALSE;
1036    }
1037    PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
1038}
1039/* }}} */
1040
1041/* {{{ proto int memory_get_usage([real_usage])
1042   Returns the allocated by PHP memory */
1043PHP_FUNCTION(memory_get_usage) {
1044    zend_bool real_usage = 0;
1045
1046    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &real_usage) == FAILURE) {
1047        RETURN_FALSE;
1048    }
1049
1050    RETURN_LONG(zend_memory_usage(real_usage TSRMLS_CC));
1051}
1052/* }}} */
1053
1054/* {{{ proto int memory_get_peak_usage([real_usage])
1055   Returns the peak allocated by PHP memory */
1056PHP_FUNCTION(memory_get_peak_usage) {
1057    zend_bool real_usage = 0;
1058
1059    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &real_usage) == FAILURE) {
1060        RETURN_FALSE;
1061    }
1062
1063    RETURN_LONG(zend_memory_peak_usage(real_usage TSRMLS_CC));
1064}
1065/* }}} */
1066
1067/*
1068 * Local variables:
1069 * tab-width: 4
1070 * c-basic-offset: 4
1071 * End:
1072 * vim600: sw=4 ts=4 fdm=marker
1073 * vim<600: sw=4 ts=4
1074 */
1075