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, php_uint_t index, zend_string *key, int level TSRMLS_DC) /* {{{ */
58{
59    if (key == NULL) { /* numeric key */
60        php_printf("%*c[" ZEND_INT_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, php_uint_t 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_INT_FMT "]=>\n", level + 1, ' ', index);
76    } else { /* string key */
77        int unmangle = zend_unmangle_property_name(key->val, key->len, &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    php_uint_t 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_INT:
123            php_printf("%sint(" ZEND_INT_FMT ")\n", COMMON, Z_IVAL_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_STRSIZE_P(struc));
130            PHPWRITE(Z_STRVAL_P(struc), Z_STRSIZE_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                STR_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                php_uint_t 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(%ld) 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, php_uint_t index, zend_string *key, int level TSRMLS_DC) /* {{{ */
231{
232    if (key == NULL) { /* numeric key */
233        php_printf("%*c[" ZEND_INT_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, php_uint_t 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_INT_FMT "]=>\n", level + 1, ' ', index);
249    } else { /* string key */
250        zend_unmangle_property_name(key->val, key->len, &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    php_uint_t 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_INT:
294        php_printf("%slong(" ZEND_INT_FMT ")\n", COMMON, Z_IVAL_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_STRSIZE_P(struc));
301        PHPWRITE(Z_STRVAL_P(struc), Z_STRSIZE_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        STR_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_INT_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, php_uint_t 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_int(buf, (php_int_t) 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        STR_FREE(ckey);
420        STR_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, php_uint_t 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; /* ignored, but must be passed to unmangle */
434        const char *pname;
435        zend_string *pname_esc;
436
437        zend_unmangle_property_name(key->val, key->len,
438                &class_name, &pname);
439        pname_esc = php_addcslashes(pname, strlen(pname), 0, "'\\", 2 TSRMLS_CC);
440
441        smart_str_appendc(buf, '\'');
442        smart_str_appendl(buf, pname_esc->val, pname_esc->len);
443        smart_str_appendc(buf, '\'');
444        STR_RELEASE(pname_esc);
445    } else {
446        smart_str_append_int(buf, (php_int_t) index);
447    }
448    smart_str_appendl(buf, " => ", 4);
449    php_var_export_ex(zv, level + 2, buf TSRMLS_CC);
450    smart_str_appendc(buf, ',');
451    smart_str_appendc(buf, '\n');
452}
453/* }}} */
454
455PHPAPI void php_var_export_ex(zval *struc, int level, smart_str *buf TSRMLS_DC) /* {{{ */
456{
457    HashTable *myht;
458    char *tmp_str;
459    php_size_t tmp_len;
460    zend_string *class_name;
461    zend_string *ztmp, *ztmp2;
462    php_uint_t index;
463    zend_string *key;
464    zval *val;
465
466again:
467    switch (Z_TYPE_P(struc)) {
468        case IS_FALSE:
469            smart_str_appendl(buf, "false", 5);
470            break;
471        case IS_TRUE:
472            smart_str_appendl(buf, "true", 4);
473            break;
474        case IS_NULL:
475            smart_str_appendl(buf, "NULL", 4);
476            break;
477        case IS_INT:
478            smart_str_append_int(buf, Z_IVAL_P(struc));
479            break;
480        case IS_DOUBLE:
481            tmp_len = spprintf(&tmp_str, 0,"%.*H", PG(serialize_precision), Z_DVAL_P(struc));
482            smart_str_appendl(buf, tmp_str, tmp_len);
483            efree(tmp_str);
484            break;
485        case IS_STRING:
486            ztmp = php_addcslashes(Z_STRVAL_P(struc), Z_STRSIZE_P(struc), 0, "'\\", 2 TSRMLS_CC);
487            ztmp2 = php_str_to_str_ex(ztmp->val, ztmp->len, "\0", 1, "' . \"\\0\" . '", 12, 0, NULL);
488
489            smart_str_appendc(buf, '\'');
490            smart_str_appendl(buf, ztmp2->val, ztmp2->len);
491            smart_str_appendc(buf, '\'');
492
493            STR_FREE(ztmp);
494            STR_FREE(ztmp2);
495            break;
496        case IS_ARRAY:
497            myht = Z_ARRVAL_P(struc);
498            if (ZEND_HASH_APPLY_PROTECTION(myht) && myht->u.v.nApplyCount++ > 0) {
499                myht->u.v.nApplyCount--;
500                smart_str_appendl(buf, "NULL", 4);
501                zend_error(E_WARNING, "var_export does not handle circular references");
502                return;
503            }
504            if (level > 1) {
505                smart_str_appendc(buf, '\n');
506                buffer_append_spaces(buf, level - 1);
507            }
508            smart_str_appendl(buf, "array (\n", 8);
509            ZEND_HASH_FOREACH_KEY_VAL_IND(myht, index, key, val) {
510                php_array_element_export(val, index, key, level, buf TSRMLS_CC);
511            } ZEND_HASH_FOREACH_END();
512            if (ZEND_HASH_APPLY_PROTECTION(myht)) {
513                myht->u.v.nApplyCount--;
514            }
515            if (level > 1) {
516                buffer_append_spaces(buf, level - 1);
517            }
518            smart_str_appendc(buf, ')');
519
520            break;
521
522        case IS_OBJECT:
523            myht = Z_OBJPROP_P(struc);
524            if (myht) {
525                if (myht->u.v.nApplyCount > 0) {
526                    smart_str_appendl(buf, "NULL", 4);
527                    zend_error(E_WARNING, "var_export does not handle circular references");
528                    return;
529                } else {
530                    myht->u.v.nApplyCount++;
531                }
532            }
533            if (level > 1) {
534                smart_str_appendc(buf, '\n');
535                buffer_append_spaces(buf, level - 1);
536            }
537            class_name = Z_OBJ_HANDLER_P(struc, get_class_name)(Z_OBJ_P(struc), 0 TSRMLS_CC);
538
539            smart_str_appendl(buf, class_name->val, class_name->len);
540            smart_str_appendl(buf, "::__set_state(array(\n", 21);
541
542            STR_RELEASE(class_name);
543            if (myht) {
544                ZEND_HASH_FOREACH_KEY_VAL_IND(myht, index, key, val) {
545                    php_object_element_export(val, index, key, level, buf TSRMLS_CC);
546                } ZEND_HASH_FOREACH_END();
547                myht->u.v.nApplyCount--;
548            }
549            if (level > 1) {
550                buffer_append_spaces(buf, level - 1);
551            }
552            smart_str_appendl(buf, "))", 2);
553
554            break;
555        case IS_REFERENCE:
556            struc = Z_REFVAL_P(struc);
557            goto again;
558            break;
559        default:
560            smart_str_appendl(buf, "NULL", 4);
561            break;
562    }
563}
564/* }}} */
565
566/* FOR BC reasons, this will always perform and then print */
567PHPAPI void php_var_export(zval *struc, int level TSRMLS_DC) /* {{{ */
568{
569    smart_str buf = {0};
570    php_var_export_ex(struc, level, &buf TSRMLS_CC);
571    smart_str_0(&buf);
572    PHPWRITE(buf.s->val, buf.s->len);
573    smart_str_free(&buf);
574}
575/* }}} */
576
577
578/* {{{ proto mixed var_export(mixed var [, bool return])
579   Outputs or returns a string representation of a variable */
580PHP_FUNCTION(var_export)
581{
582    zval *var;
583    zend_bool return_output = 0;
584    smart_str buf = {0};
585
586    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|b", &var, &return_output) == FAILURE) {
587        return;
588    }
589
590    php_var_export_ex(var, 1, &buf TSRMLS_CC);
591    smart_str_0 (&buf);
592
593    if (return_output) {
594        RETURN_STR(buf.s);
595    } else {
596        PHPWRITE(buf.s->val, buf.s->len);
597        smart_str_free(&buf);
598    }
599}
600/* }}} */
601
602static void php_var_serialize_intern(smart_str *buf, zval *struc, HashTable *var_hash TSRMLS_DC);
603
604static inline int php_add_var_hash(HashTable *var_hash, zval *var_ptr, zval *var_old TSRMLS_DC) /* {{{ */
605{
606    zval var_no, *zv;
607    char id[32], *p;
608    register int len;
609    zval *var = var_ptr;
610
611    if (Z_ISREF_P(var)) {
612        var = Z_REFVAL_P(var);
613    }
614    if ((Z_TYPE_P(var) == IS_OBJECT) && Z_OBJ_HT_P(var)->get_class_entry) {
615        p = smart_str_print_long(id + sizeof(id) - 1,
616                (php_int_t) Z_OBJ_P(var));
617        *(--p) = 'O';
618        len = id + sizeof(id) - 1 - p;
619    } else if (var_ptr != var) {
620        p = smart_str_print_long(id + sizeof(id) - 1,
621                (php_int_t) Z_REF_P(var_ptr));
622        *(--p) = 'R';
623        len = id + sizeof(id) - 1 - p;
624    } else {
625        p = smart_str_print_long(id + sizeof(id) - 1, (php_int_t) var);
626        len = id + sizeof(id) - 1 - p;
627    }
628
629    if ((zv = zend_hash_str_find(var_hash, p, len)) != NULL) {
630        ZVAL_COPY_VALUE(var_old, zv);
631        if (var == var_ptr) {
632            /* we still need to bump up the counter, since non-refs will
633             * be counted separately by unserializer */
634            ZVAL_INT(&var_no, -1);
635            zend_hash_next_index_insert(var_hash, &var_no);
636        }
637#if 0
638        fprintf(stderr, "- had var (%d): %lu\n", Z_TYPE_P(var), **(php_uint_t**)var_old);
639#endif
640        return FAILURE;
641    }
642
643    /* +1 because otherwise hash will think we are trying to store NULL pointer */
644    ZVAL_INT(&var_no, zend_hash_num_elements(var_hash) + 1);
645    zend_hash_str_add(var_hash, p, len, &var_no);
646#if 0
647    fprintf(stderr, "+ add var (%d): %lu\n", Z_TYPE_P(var), Z_IVAL(var_no));
648#endif
649    return SUCCESS;
650}
651/* }}} */
652
653static inline void php_var_serialize_long(smart_str *buf, php_int_t val) /* {{{ */
654{
655    smart_str_appendl(buf, "i:", 2);
656    smart_str_append_int(buf, val);
657    smart_str_appendc(buf, ';');
658}
659/* }}} */
660
661static inline void php_var_serialize_string(smart_str *buf, char *str, int len) /* {{{ */
662{
663    smart_str_appendl(buf, "s:", 2);
664    smart_str_append_int(buf, len);
665    smart_str_appendl(buf, ":\"", 2);
666    smart_str_appendl(buf, str, len);
667    smart_str_appendl(buf, "\";", 2);
668}
669/* }}} */
670
671static inline zend_bool php_var_serialize_class_name(smart_str *buf, zval *struc TSRMLS_DC) /* {{{ */
672{
673    PHP_CLASS_ATTRIBUTES;
674
675    PHP_SET_CLASS_ATTRIBUTES(struc);
676    smart_str_appendl(buf, "O:", 2);
677    smart_str_append_int(buf, (int)class_name->len);
678    smart_str_appendl(buf, ":\"", 2);
679    smart_str_appendl(buf, class_name->val, class_name->len);
680    smart_str_appendl(buf, "\":", 2);
681    PHP_CLEANUP_CLASS_ATTRIBUTES();
682    return incomplete_class;
683}
684/* }}} */
685
686static void php_var_serialize_class(smart_str *buf, zval *struc, zval *retval_ptr, HashTable *var_hash TSRMLS_DC) /* {{{ */
687{
688    int count;
689    zend_bool incomplete_class;
690
691    incomplete_class = php_var_serialize_class_name(buf, struc TSRMLS_CC);
692    /* count after serializing name, since php_var_serialize_class_name
693     * changes the count if the variable is incomplete class */
694    count = zend_hash_num_elements(HASH_OF(retval_ptr));
695    if (incomplete_class) {
696        --count;
697    }
698    smart_str_append_int(buf, count);
699    smart_str_appendl(buf, ":{", 2);
700
701    if (count > 0) {
702        zend_string *key;
703        zval *d, *name;
704        zval nval, *nvalp;
705        HashTable *propers, *ht;
706
707        ZVAL_NULL(&nval);
708        nvalp = &nval;
709
710        ht = HASH_OF(retval_ptr);
711        ZEND_HASH_FOREACH_STR_KEY_VAL(ht, key, name) {
712            if (incomplete_class && strcmp(key->val, MAGIC_MEMBER) == 0) {
713                continue;
714            }
715
716            if (Z_TYPE_P(name) != IS_STRING) {
717                php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize.");
718                /* we should still add element even if it's not OK,
719                 * since we already wrote the length of the array before */
720                smart_str_appendl(buf,"N;", 2);
721                continue;
722            }
723            propers = Z_OBJPROP_P(struc);
724            if ((d = zend_hash_find(propers, Z_STR_P(name))) != NULL) {
725                if (Z_TYPE_P(d) == IS_INDIRECT) {
726                    d = Z_INDIRECT_P(d);
727                    if (Z_TYPE_P(d) == IS_UNDEF) {
728                        continue;
729                    }
730                }
731                php_var_serialize_string(buf, Z_STRVAL_P(name), Z_STRSIZE_P(name));
732                php_var_serialize_intern(buf, d, var_hash TSRMLS_CC);
733            } else {
734                zend_class_entry *ce;
735                ce = zend_get_class_entry(Z_OBJ_P(struc) TSRMLS_CC);
736                if (ce) {
737                    zend_string *prot_name, *priv_name;
738
739                    do {
740                        priv_name = zend_mangle_property_name(ce->name->val, ce->name->len, Z_STRVAL_P(name), Z_STRSIZE_P(name), ce->type & ZEND_INTERNAL_CLASS);
741                        if ((d = zend_hash_find(propers, priv_name)) != NULL) {
742                            if (Z_TYPE_P(d) == IS_INDIRECT) {
743                                d = Z_INDIRECT_P(d);
744                                if (Z_ISUNDEF_P(d)) {
745                                    break;
746                                }
747                            }
748                            php_var_serialize_string(buf, priv_name->val, priv_name->len);
749                            STR_FREE(priv_name);
750                            php_var_serialize_intern(buf, d, var_hash TSRMLS_CC);
751                            break;
752                        }
753                        STR_FREE(priv_name);
754                        prot_name = zend_mangle_property_name("*", 1, Z_STRVAL_P(name), Z_STRSIZE_P(name), ce->type & ZEND_INTERNAL_CLASS);
755                        if ((d = zend_hash_find(propers, prot_name)) != NULL) {
756                            if (Z_TYPE_P(d) == IS_INDIRECT) {
757                                d = Z_INDIRECT_P(d);
758                                if (Z_TYPE_P(d) == IS_UNDEF) {
759                                    STR_FREE(prot_name);
760                                    break;
761                                }
762                            }
763                            php_var_serialize_string(buf, prot_name->val, prot_name->len);
764                            STR_FREE(prot_name);
765                            php_var_serialize_intern(buf, d, var_hash TSRMLS_CC);
766                            break;
767                        }
768                        STR_FREE(prot_name);
769                        php_var_serialize_string(buf, Z_STRVAL_P(name), Z_STRSIZE_P(name));
770                        php_var_serialize_intern(buf, nvalp, var_hash TSRMLS_CC);
771                        php_error_docref(NULL TSRMLS_CC, E_NOTICE, "\"%s\" returned as member variable from __sleep() but does not exist", Z_STRVAL_P(name));
772                    } while (0);
773                } else {
774                    php_var_serialize_string(buf, Z_STRVAL_P(name), Z_STRSIZE_P(name));
775                    php_var_serialize_intern(buf, nvalp, var_hash TSRMLS_CC);
776                }
777            }
778        } ZEND_HASH_FOREACH_END();
779    }
780    smart_str_appendc(buf, '}');
781}
782/* }}} */
783
784static void php_var_serialize_intern(smart_str *buf, zval *struc, HashTable *var_hash TSRMLS_DC) /* {{{ */
785{
786    int i;
787    zval var_already;
788    HashTable *myht;
789
790    if (EG(exception)) {
791        return;
792    }
793
794    ZVAL_UNDEF(&var_already);
795
796    if (var_hash &&
797        php_add_var_hash(var_hash, struc, &var_already TSRMLS_CC) == FAILURE) {
798        if (Z_ISREF_P(struc)) {
799            smart_str_appendl(buf, "R:", 2);
800            smart_str_append_int(buf, Z_IVAL(var_already));
801            smart_str_appendc(buf, ';');
802            return;
803        } else if (Z_TYPE_P(struc) == IS_OBJECT) {
804            smart_str_appendl(buf, "r:", 2);
805            smart_str_append_int(buf, Z_IVAL(var_already));
806            smart_str_appendc(buf, ';');
807            return;
808        }
809    }
810
811again:
812    switch (Z_TYPE_P(struc)) {
813        case IS_FALSE:
814            smart_str_appendl(buf, "b:0;", 4);
815            return;
816
817        case IS_TRUE:
818            smart_str_appendl(buf, "b:1;", 4);
819            return;
820
821        case IS_NULL:
822            smart_str_appendl(buf, "N;", 2);
823            return;
824
825        case IS_INT:
826            php_var_serialize_long(buf, Z_IVAL_P(struc));
827            return;
828
829        case IS_DOUBLE: {
830                char *s;
831
832                smart_str_appendl(buf, "d:", 2);
833                s = (char *) safe_emalloc(PG(serialize_precision), 1, MAX_LENGTH_OF_DOUBLE + 1);
834                php_gcvt(Z_DVAL_P(struc), PG(serialize_precision), '.', 'E', s);
835                smart_str_appends(buf, s);
836                smart_str_appendc(buf, ';');
837                efree(s);
838                return;
839            }
840
841        case IS_STRING:
842            php_var_serialize_string(buf, Z_STRVAL_P(struc), Z_STRSIZE_P(struc));
843            return;
844
845        case IS_OBJECT: {
846                zval retval;
847                zval fname;
848                int res;
849                zend_class_entry *ce = NULL;
850
851                if (Z_OBJ_HT_P(struc)->get_class_entry) {
852                    ce = Z_OBJCE_P(struc);
853                }
854
855                if (ce && ce->serialize != NULL) {
856                    /* has custom handler */
857                    unsigned char *serialized_data = NULL;
858                    zend_uint serialized_length;
859
860                    if (ce->serialize(struc, &serialized_data, &serialized_length, (zend_serialize_data *)var_hash TSRMLS_CC) == SUCCESS) {
861                        smart_str_appendl(buf, "C:", 2);
862                        smart_str_append_int(buf, (int)Z_OBJCE_P(struc)->name->len);
863                        smart_str_appendl(buf, ":\"", 2);
864                        smart_str_appendl(buf, Z_OBJCE_P(struc)->name->val, Z_OBJCE_P(struc)->name->len);
865                        smart_str_appendl(buf, "\":", 2);
866
867                        smart_str_append_int(buf, (int)serialized_length);
868                        smart_str_appendl(buf, ":{", 2);
869                        smart_str_appendl(buf, serialized_data, serialized_length);
870                        smart_str_appendc(buf, '}');
871                    } else {
872                        smart_str_appendl(buf, "N;", 2);
873                    }
874                    if (serialized_data) {
875                        efree(serialized_data);
876                    }
877                    return;
878                }
879
880                if (ce && ce != PHP_IC_ENTRY && zend_hash_str_exists(&ce->function_table, "__sleep", sizeof("__sleep")-1)) {
881                    ZVAL_STRINGL(&fname, "__sleep", sizeof("__sleep") - 1);
882                    BG(serialize_lock)++;
883                    res = call_user_function_ex(CG(function_table), struc, &fname, &retval, 0, 0, 1, NULL TSRMLS_CC);
884                    BG(serialize_lock)--;
885                    zval_dtor(&fname);
886
887                    if (EG(exception)) {
888                        zval_ptr_dtor(&retval);
889                        return;
890                    }
891
892                    if (res == SUCCESS) {
893                        if (Z_TYPE(retval) != IS_UNDEF) {
894                            if (HASH_OF(&retval)) {
895                                php_var_serialize_class(buf, struc, &retval, var_hash TSRMLS_CC);
896                            } else {
897                                php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize");
898                                /* we should still add element even if it's not OK,
899                                 * since we already wrote the length of the array before */
900                                smart_str_appendl(buf,"N;", 2);
901                            }
902                            zval_ptr_dtor(&retval);
903                        }
904                        return;
905                    }
906                    zval_ptr_dtor(&retval);
907                }
908
909                /* fall-through */
910            }
911        case IS_ARRAY: {
912            zend_bool incomplete_class = 0;
913            if (Z_TYPE_P(struc) == IS_ARRAY) {
914                smart_str_appendl(buf, "a:", 2);
915                myht = HASH_OF(struc);
916            } else {
917                incomplete_class = php_var_serialize_class_name(buf, struc TSRMLS_CC);
918                myht = Z_OBJPROP_P(struc);
919            }
920            /* count after serializing name, since php_var_serialize_class_name
921             * changes the count if the variable is incomplete class */
922            i = myht ? zend_hash_num_elements(myht) : 0;
923            if (i > 0 && incomplete_class) {
924                --i;
925            }
926            smart_str_append_int(buf, i);
927            smart_str_appendl(buf, ":{", 2);
928            if (i > 0) {
929                zend_string *key;
930                zval *data;
931                php_uint_t index;
932
933                ZEND_HASH_FOREACH_KEY_VAL_IND(myht, index, key, data) {
934
935                    if (incomplete_class && strcmp(key->val, MAGIC_MEMBER) == 0) {
936                        continue;
937                    }
938
939                    if (!key) {
940                        php_var_serialize_long(buf, index);
941                    } else {
942                        php_var_serialize_string(buf, key->val, key->len);
943                    }
944
945                    /* we should still add element even if it's not OK,
946                     * since we already wrote the length of the array before */
947                    if ((Z_TYPE_P(data) == IS_ARRAY && Z_TYPE_P(struc) == IS_ARRAY && Z_ARR_P(data) == Z_ARR_P(struc))
948                        || (Z_TYPE_P(data) == IS_ARRAY && Z_ARRVAL_P(data)->u.v.nApplyCount > 1)
949                    ) {
950                        smart_str_appendl(buf, "N;", 2);
951                    } else {
952                        if (Z_TYPE_P(data) == IS_ARRAY && ZEND_HASH_APPLY_PROTECTION(Z_ARRVAL_P(data))) {
953                            Z_ARRVAL_P(data)->u.v.nApplyCount++;
954                        }
955                        php_var_serialize_intern(buf, data, var_hash TSRMLS_CC);
956                        if (Z_TYPE_P(data) == IS_ARRAY && ZEND_HASH_APPLY_PROTECTION(Z_ARRVAL_P(data))) {
957                            Z_ARRVAL_P(data)->u.v.nApplyCount--;
958                        }
959                    }
960                } ZEND_HASH_FOREACH_END();
961            }
962            smart_str_appendc(buf, '}');
963            return;
964        }
965        case IS_REFERENCE:
966            struc = Z_REFVAL_P(struc);
967            goto again;
968        default:
969            smart_str_appendl(buf, "i:0;", 4);
970            return;
971    }
972}
973/* }}} */
974
975PHPAPI void php_var_serialize(smart_str *buf, zval *struc, php_serialize_data_t *var_hash TSRMLS_DC) /* {{{ */
976{
977    php_var_serialize_intern(buf, struc, *var_hash TSRMLS_CC);
978    smart_str_0(buf);
979}
980/* }}} */
981
982/* {{{ proto string serialize(mixed variable)
983   Returns a string representation of variable (which can later be unserialized) */
984PHP_FUNCTION(serialize)
985{
986    zval *struc;
987    php_serialize_data_t var_hash;
988    smart_str buf = {0};
989
990    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &struc) == FAILURE) {
991        return;
992    }
993
994    PHP_VAR_SERIALIZE_INIT(var_hash);
995    php_var_serialize(&buf, struc, &var_hash TSRMLS_CC);
996    PHP_VAR_SERIALIZE_DESTROY(var_hash);
997
998    if (EG(exception)) {
999        smart_str_free(&buf);
1000        RETURN_FALSE;
1001    }
1002
1003    if (buf.s) {
1004        RETURN_STR(buf.s);
1005    } else {
1006        RETURN_NULL();
1007    }
1008}
1009/* }}} */
1010
1011/* {{{ proto mixed unserialize(string variable_representation)
1012   Takes a string representation of variable and recreates it */
1013PHP_FUNCTION(unserialize)
1014{
1015    char *buf = NULL;
1016    int buf_len;
1017    const unsigned char *p;
1018    php_unserialize_data_t var_hash;
1019
1020    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) {
1021        RETURN_FALSE;
1022    }
1023
1024    if (buf_len == 0) {
1025        RETURN_FALSE;
1026    }
1027
1028    p = (const unsigned char*) buf;
1029    PHP_VAR_UNSERIALIZE_INIT(var_hash);
1030    if (!php_var_unserialize(return_value, &p, p + buf_len, &var_hash TSRMLS_CC)) {
1031        PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
1032        zval_dtor(return_value);
1033        if (!EG(exception)) {
1034            php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Error at offset " ZEND_INT_FMT " of %d bytes", (php_int_t)((char*)p - buf), buf_len);
1035        }
1036        RETURN_FALSE;
1037    }
1038    PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
1039}
1040/* }}} */
1041
1042/* {{{ proto int memory_get_usage([real_usage])
1043   Returns the allocated by PHP memory */
1044PHP_FUNCTION(memory_get_usage) {
1045    zend_bool real_usage = 0;
1046
1047    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &real_usage) == FAILURE) {
1048        RETURN_FALSE;
1049    }
1050
1051    RETURN_INT(zend_memory_usage(real_usage TSRMLS_CC));
1052}
1053/* }}} */
1054
1055/* {{{ proto int memory_get_peak_usage([real_usage])
1056   Returns the peak allocated by PHP memory */
1057PHP_FUNCTION(memory_get_peak_usage) {
1058    zend_bool real_usage = 0;
1059
1060    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &real_usage) == FAILURE) {
1061        RETURN_FALSE;
1062    }
1063
1064    RETURN_INT(zend_memory_peak_usage(real_usage TSRMLS_CC));
1065}
1066/* }}} */
1067
1068/*
1069 * Local variables:
1070 * tab-width: 4
1071 * c-basic-offset: 4
1072 * End:
1073 * vim600: sw=4 ts=4 fdm=marker
1074 * vim<600: sw=4 ts=4
1075 */
1076