1/*
2   +----------------------------------------------------------------------+
3   | Zend Engine                                                          |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1998-2015 Zend Technologies Ltd. (http://www.zend.com) |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt.                                |
11   | If you did not receive a copy of the Zend license and are unable to  |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@zend.com so we can mail you a copy immediately.              |
14   +----------------------------------------------------------------------+
15   | Authors: Christian Seiler <chris_se@gmx.net>                         |
16   |          Dmitry Stogov <dmitry@zend.com>                             |
17   |          Marcus Boerger <helly@php.net>                              |
18   +----------------------------------------------------------------------+
19*/
20
21/* $Id$ */
22
23#include "zend.h"
24#include "zend_API.h"
25#include "zend_closures.h"
26#include "zend_exceptions.h"
27#include "zend_interfaces.h"
28#include "zend_objects.h"
29#include "zend_objects_API.h"
30#include "zend_globals.h"
31
32#define ZEND_CLOSURE_PRINT_NAME "Closure object"
33
34#define ZEND_CLOSURE_PROPERTY_ERROR() \
35    zend_error(E_EXCEPTION | E_ERROR, "Closure object cannot have properties")
36
37typedef struct _zend_closure {
38    zend_object    std;
39    zend_function  func;
40    zval           this_ptr;
41    HashTable     *debug_info;
42} zend_closure;
43
44/* non-static since it needs to be referenced */
45ZEND_API zend_class_entry *zend_ce_closure;
46static zend_object_handlers closure_handlers;
47
48ZEND_METHOD(Closure, __invoke) /* {{{ */
49{
50    zend_function *func = EX(func);
51    zval *arguments;
52
53    arguments = emalloc(sizeof(zval) * ZEND_NUM_ARGS());
54    if (zend_get_parameters_array_ex(ZEND_NUM_ARGS(), arguments) == FAILURE) {
55        efree(arguments);
56        zend_error(E_EXCEPTION | E_ERROR, "Cannot get arguments for calling closure");
57        RETVAL_FALSE;
58    } else if (call_user_function_ex(CG(function_table), NULL, getThis(), return_value, ZEND_NUM_ARGS(), arguments, 1, NULL) == FAILURE) {
59        RETVAL_FALSE;
60    }
61    efree(arguments);
62
63    /* destruct the function also, then - we have allocated it in get_method */
64    zend_string_release(func->internal_function.function_name);
65    efree(func);
66#if ZEND_DEBUG
67    execute_data->func = NULL;
68#endif
69}
70/* }}} */
71
72/* {{{ proto mixed Closure::call(object $to [, mixed $parameter] [, mixed $...] )
73   Call closure, binding to a given object with its class as the scope */
74ZEND_METHOD(Closure, call)
75{
76    zval *zclosure, *newthis, closure_result;
77    zend_closure *closure;
78    zend_fcall_info fci;
79    zend_fcall_info_cache fci_cache;
80    zval *my_params;
81    int my_param_count = 0;
82    zend_function my_function;
83
84    if (zend_parse_parameters(ZEND_NUM_ARGS(), "o*", &newthis, &my_params, &my_param_count) == FAILURE) {
85        return;
86    }
87
88    zclosure = getThis();
89    closure = (zend_closure *)Z_OBJ_P(zclosure);
90
91    if (closure->func.common.fn_flags & ZEND_ACC_STATIC) {
92        zend_error(E_WARNING, "Cannot bind an instance to a static closure");
93        return;
94    }
95
96    if (closure->func.type == ZEND_INTERNAL_FUNCTION) {
97        /* verify that we aren't binding internal function to a wrong object */
98        if ((closure->func.common.fn_flags & ZEND_ACC_STATIC) == 0 &&
99                !instanceof_function(Z_OBJCE_P(newthis), closure->func.common.scope)) {
100            zend_error(E_WARNING, "Cannot bind function %s::%s to object of class %s", closure->func.common.scope->name->val, closure->func.common.function_name->val, Z_OBJCE_P(newthis)->name->val);
101            return;
102        }
103    }
104
105    /* This should never happen as closures will always be callable */
106    if (zend_fcall_info_init(zclosure, 0, &fci, &fci_cache, NULL, NULL) != SUCCESS) {
107        ZEND_ASSERT(0);
108    }
109
110    fci.retval = &closure_result;
111    fci.params = my_params;
112    fci.param_count = my_param_count;
113    fci.object = fci_cache.object = Z_OBJ_P(newthis);
114    fci_cache.initialized = 1;
115
116    my_function = *fci_cache.function_handler;
117    /* use scope of passed object */
118    my_function.common.scope = Z_OBJCE_P(newthis);
119    fci_cache.function_handler = &my_function;
120
121    if (zend_call_function(&fci, &fci_cache) == SUCCESS && Z_TYPE(closure_result) != IS_UNDEF) {
122        ZVAL_COPY_VALUE(return_value, &closure_result);
123    }
124}
125/* }}} */
126
127/* {{{ proto Closure Closure::bind(Closure $old, object $to [, mixed $scope = "static" ] )
128   Create a closure from another one and bind to another object and scope */
129ZEND_METHOD(Closure, bind)
130{
131    zval *newthis, *zclosure, *scope_arg = NULL;
132    zend_closure *closure;
133    zend_class_entry *ce;
134
135    if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Oo!|z", &zclosure, zend_ce_closure, &newthis, &scope_arg) == FAILURE) {
136        RETURN_NULL();
137    }
138
139    closure = (zend_closure *)Z_OBJ_P(zclosure);
140
141    if ((newthis != NULL) && (closure->func.common.fn_flags & ZEND_ACC_STATIC)) {
142        zend_error(E_WARNING, "Cannot bind an instance to a static closure");
143    }
144
145    if (scope_arg != NULL) { /* scope argument was given */
146        if (Z_TYPE_P(scope_arg) == IS_OBJECT) {
147            ce = Z_OBJCE_P(scope_arg);
148        } else if (Z_TYPE_P(scope_arg) == IS_NULL) {
149            ce = NULL;
150        } else {
151            zend_string *class_name = zval_get_string(scope_arg);
152            if (zend_string_equals_literal(class_name, "static")) {
153                ce = closure->func.common.scope;
154            } else if ((ce = zend_lookup_class_ex(class_name, NULL, 1)) == NULL) {
155                zend_error(E_WARNING, "Class '%s' not found", class_name->val);
156                zend_string_release(class_name);
157                RETURN_NULL();
158            }
159            zend_string_release(class_name);
160        }
161    } else { /* scope argument not given; do not change the scope by default */
162        ce = closure->func.common.scope;
163    }
164
165    zend_create_closure(return_value, &closure->func, ce, newthis);
166}
167/* }}} */
168
169static zend_function *zend_closure_get_constructor(zend_object *object) /* {{{ */
170{
171    zend_error(E_EXCEPTION | E_ERROR, "Instantiation of 'Closure' is not allowed");
172    return NULL;
173}
174/* }}} */
175
176static int zend_closure_compare_objects(zval *o1, zval *o2) /* {{{ */
177{
178    return (Z_OBJ_P(o1) != Z_OBJ_P(o2));
179}
180/* }}} */
181
182ZEND_API zend_function *zend_get_closure_invoke_method(zend_object *object) /* {{{ */
183{
184    zend_closure *closure = (zend_closure *)object;
185    zend_function *invoke = (zend_function*)emalloc(sizeof(zend_function));
186
187    invoke->common = closure->func.common;
188    /* TODO: return ZEND_INTERNAL_FUNCTION, but arg_info representation is suitable for ZEND_USER_FUNCTION ??? */
189    invoke->type = ZEND_INTERNAL_FUNCTION;
190    invoke->internal_function.fn_flags = ZEND_ACC_PUBLIC | ZEND_ACC_CALL_VIA_HANDLER | (closure->func.common.fn_flags & ZEND_ACC_RETURN_REFERENCE);
191    invoke->internal_function.handler = ZEND_MN(Closure___invoke);
192    invoke->internal_function.module = 0;
193    invoke->internal_function.scope = zend_ce_closure;
194    invoke->internal_function.function_name = zend_string_init(ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1, 0);
195    return invoke;
196}
197/* }}} */
198
199ZEND_API const zend_function *zend_get_closure_method_def(zval *obj) /* {{{ */
200{
201    zend_closure *closure = (zend_closure *)Z_OBJ_P(obj);
202    return &closure->func;
203}
204/* }}} */
205
206ZEND_API zval* zend_get_closure_this_ptr(zval *obj) /* {{{ */
207{
208    zend_closure *closure = (zend_closure *)Z_OBJ_P(obj);
209    return &closure->this_ptr;
210}
211/* }}} */
212
213static zend_function *zend_closure_get_method(zend_object **object, zend_string *method, const zval *key) /* {{{ */
214{
215    zend_string *lc_name;
216
217    lc_name = zend_string_tolower(method);
218    if (zend_string_equals_literal(method, ZEND_INVOKE_FUNC_NAME)) {
219        zend_string_release(lc_name);
220        return zend_get_closure_invoke_method(*object);
221    }
222    zend_string_release(lc_name);
223    return std_object_handlers.get_method(object, method, key);
224}
225/* }}} */
226
227static zval *zend_closure_read_property(zval *object, zval *member, int type, void **cache_slot, zval *rv) /* {{{ */
228{
229    ZEND_CLOSURE_PROPERTY_ERROR();
230    return &EG(uninitialized_zval);
231}
232/* }}} */
233
234static void zend_closure_write_property(zval *object, zval *member, zval *value, void **cache_slot) /* {{{ */
235{
236    ZEND_CLOSURE_PROPERTY_ERROR();
237}
238/* }}} */
239
240static zval *zend_closure_get_property_ptr_ptr(zval *object, zval *member, int type, void **cache_slot) /* {{{ */
241{
242    ZEND_CLOSURE_PROPERTY_ERROR();
243    return NULL;
244}
245/* }}} */
246
247static int zend_closure_has_property(zval *object, zval *member, int has_set_exists, void **cache_slot) /* {{{ */
248{
249    if (has_set_exists != 2) {
250        ZEND_CLOSURE_PROPERTY_ERROR();
251    }
252    return 0;
253}
254/* }}} */
255
256static void zend_closure_unset_property(zval *object, zval *member, void **cache_slot) /* {{{ */
257{
258    ZEND_CLOSURE_PROPERTY_ERROR();
259}
260/* }}} */
261
262static void zend_closure_free_storage(zend_object *object) /* {{{ */
263{
264    zend_closure *closure = (zend_closure *)object;
265
266    zend_object_std_dtor(&closure->std);
267
268    if (closure->func.type == ZEND_USER_FUNCTION) {
269        zend_execute_data *ex = EG(current_execute_data);
270        while (ex) {
271            if (ex->func == &closure->func) {
272                zend_error(E_ERROR, "Cannot destroy active lambda function");
273            }
274            ex = ex->prev_execute_data;
275        }
276        destroy_op_array(&closure->func.op_array);
277    }
278
279    if (closure->debug_info != NULL) {
280        zend_hash_destroy(closure->debug_info);
281        efree(closure->debug_info);
282    }
283
284    if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
285        zval_ptr_dtor(&closure->this_ptr);
286    }
287}
288/* }}} */
289
290static zend_object *zend_closure_new(zend_class_entry *class_type) /* {{{ */
291{
292    zend_closure *closure;
293
294    closure = emalloc(sizeof(zend_closure));
295    memset(closure, 0, sizeof(zend_closure));
296
297    zend_object_std_init(&closure->std, class_type);
298    closure->std.handlers = &closure_handlers;
299
300    return (zend_object*)closure;
301}
302/* }}} */
303
304static zend_object *zend_closure_clone(zval *zobject) /* {{{ */
305{
306    zend_closure *closure = (zend_closure *)Z_OBJ_P(zobject);
307    zval result;
308
309    zend_create_closure(&result, &closure->func, closure->func.common.scope, &closure->this_ptr);
310    return Z_OBJ(result);
311}
312/* }}} */
313
314int zend_closure_get_closure(zval *obj, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zend_object **obj_ptr) /* {{{ */
315{
316    zend_closure *closure;
317
318    if (Z_TYPE_P(obj) != IS_OBJECT) {
319        return FAILURE;
320    }
321
322    closure = (zend_closure *)Z_OBJ_P(obj);
323    *fptr_ptr = &closure->func;
324
325    if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
326        if (obj_ptr) {
327            *obj_ptr = Z_OBJ(closure->this_ptr);
328        }
329        *ce_ptr = Z_OBJCE(closure->this_ptr);
330    } else {
331        if (obj_ptr) {
332            *obj_ptr = NULL;
333        }
334        *ce_ptr = closure->func.common.scope;
335    }
336    return SUCCESS;
337}
338/* }}} */
339
340static HashTable *zend_closure_get_debug_info(zval *object, int *is_temp) /* {{{ */
341{
342    zend_closure *closure = (zend_closure *)Z_OBJ_P(object);
343    zval val;
344    struct _zend_arg_info *arg_info = closure->func.common.arg_info;
345
346    *is_temp = 0;
347
348    if (closure->debug_info == NULL) {
349        ALLOC_HASHTABLE(closure->debug_info);
350        zend_hash_init(closure->debug_info, 8, NULL, ZVAL_PTR_DTOR, 0);
351    }
352    if (closure->debug_info->u.v.nApplyCount == 0) {
353        if (closure->func.type == ZEND_USER_FUNCTION && closure->func.op_array.static_variables) {
354            HashTable *static_variables = closure->func.op_array.static_variables;
355            ZVAL_ARR(&val, zend_array_dup(static_variables));
356            zend_hash_str_update(closure->debug_info, "static", sizeof("static")-1, &val);
357        }
358
359        if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
360            Z_ADDREF(closure->this_ptr);
361            zend_hash_str_update(closure->debug_info, "this", sizeof("this")-1, &closure->this_ptr);
362        }
363
364        if (arg_info &&
365            (closure->func.common.num_args ||
366             (closure->func.common.fn_flags & ZEND_ACC_VARIADIC))) {
367            uint32_t i, num_args, required = closure->func.common.required_num_args;
368
369            array_init(&val);
370
371            num_args = closure->func.common.num_args;
372            if (closure->func.common.fn_flags & ZEND_ACC_VARIADIC) {
373                num_args++;
374            }
375            for (i = 0; i < num_args; i++) {
376                zend_string *name;
377                zval info;
378                if (arg_info->name) {
379                    name = zend_strpprintf(0, "%s$%s",
380                            arg_info->pass_by_reference ? "&" : "",
381                            arg_info->name->val);
382                } else {
383                    name = zend_strpprintf(0, "%s$param%d",
384                            arg_info->pass_by_reference ? "&" : "",
385                            i + 1);
386                }
387                ZVAL_NEW_STR(&info, zend_strpprintf(0, "%s", i >= required ? "<optional>" : "<required>"));
388                zend_hash_update(Z_ARRVAL(val), name, &info);
389                zend_string_release(name);
390                arg_info++;
391            }
392            zend_hash_str_update(closure->debug_info, "parameter", sizeof("parameter")-1, &val);
393        }
394    }
395
396    return closure->debug_info;
397}
398/* }}} */
399
400static HashTable *zend_closure_get_gc(zval *obj, zval **table, int *n) /* {{{ */
401{
402    zend_closure *closure = (zend_closure *)Z_OBJ_P(obj);
403
404    if (closure->debug_info != NULL) {
405        zend_hash_destroy(closure->debug_info);
406        efree(closure->debug_info);
407        closure->debug_info = NULL;
408    }
409
410    *table = Z_TYPE(closure->this_ptr) != IS_NULL ? &closure->this_ptr : NULL;
411    *n = Z_TYPE(closure->this_ptr) != IS_NULL ? 1 : 0;
412    return (closure->func.type == ZEND_USER_FUNCTION) ?
413        closure->func.op_array.static_variables : NULL;
414}
415/* }}} */
416
417/* {{{ proto Closure::__construct()
418   Private constructor preventing instantiation */
419ZEND_METHOD(Closure, __construct)
420{
421    zend_error(E_EXCEPTION | E_ERROR, "Instantiation of 'Closure' is not allowed");
422}
423/* }}} */
424
425ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_bindto, 0, 0, 1)
426    ZEND_ARG_INFO(0, newthis)
427    ZEND_ARG_INFO(0, newscope)
428ZEND_END_ARG_INFO()
429
430ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_bind, 0, 0, 2)
431    ZEND_ARG_INFO(0, closure)
432    ZEND_ARG_INFO(0, newthis)
433    ZEND_ARG_INFO(0, newscope)
434ZEND_END_ARG_INFO()
435
436ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_call, 0, 0, 1)
437    ZEND_ARG_INFO(0, newthis)
438    ZEND_ARG_VARIADIC_INFO(0, parameters)
439ZEND_END_ARG_INFO()
440
441static const zend_function_entry closure_functions[] = {
442    ZEND_ME(Closure, __construct, NULL, ZEND_ACC_PRIVATE)
443    ZEND_ME(Closure, bind, arginfo_closure_bind, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
444    ZEND_MALIAS(Closure, bindTo, bind, arginfo_closure_bindto, ZEND_ACC_PUBLIC)
445    ZEND_ME(Closure, call, arginfo_closure_call, ZEND_ACC_PUBLIC)
446    ZEND_FE_END
447};
448
449void zend_register_closure_ce(void) /* {{{ */
450{
451    zend_class_entry ce;
452
453    INIT_CLASS_ENTRY(ce, "Closure", closure_functions);
454    zend_ce_closure = zend_register_internal_class(&ce);
455    zend_ce_closure->ce_flags |= ZEND_ACC_FINAL;
456    zend_ce_closure->create_object = zend_closure_new;
457    zend_ce_closure->serialize = zend_class_serialize_deny;
458    zend_ce_closure->unserialize = zend_class_unserialize_deny;
459
460    memcpy(&closure_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
461    closure_handlers.free_obj = zend_closure_free_storage;
462    closure_handlers.clone_obj = NULL;
463    closure_handlers.get_constructor = zend_closure_get_constructor;
464    closure_handlers.get_method = zend_closure_get_method;
465    closure_handlers.write_property = zend_closure_write_property;
466    closure_handlers.read_property = zend_closure_read_property;
467    closure_handlers.get_property_ptr_ptr = zend_closure_get_property_ptr_ptr;
468    closure_handlers.has_property = zend_closure_has_property;
469    closure_handlers.unset_property = zend_closure_unset_property;
470    closure_handlers.compare_objects = zend_closure_compare_objects;
471    closure_handlers.clone_obj = zend_closure_clone;
472    closure_handlers.get_debug_info = zend_closure_get_debug_info;
473    closure_handlers.get_closure = zend_closure_get_closure;
474    closure_handlers.get_gc = zend_closure_get_gc;
475}
476/* }}} */
477
478ZEND_API void zend_create_closure(zval *res, zend_function *func, zend_class_entry *scope, zval *this_ptr) /* {{{ */
479{
480    zend_closure *closure;
481
482    object_init_ex(res, zend_ce_closure);
483
484    closure = (zend_closure *)Z_OBJ_P(res);
485
486    closure->func = *func;
487    closure->func.common.prototype = (zend_function*)closure;
488    closure->func.common.fn_flags |= ZEND_ACC_CLOSURE;
489
490    if ((scope == NULL) && this_ptr && (Z_TYPE_P(this_ptr) != IS_UNDEF)) {
491        /* use dummy scope if we're binding an object without specifying a scope */
492        /* maybe it would be better to create one for this purpose */
493        scope = zend_ce_closure;
494    }
495
496    if (closure->func.type == ZEND_USER_FUNCTION) {
497        if (closure->func.op_array.static_variables) {
498            HashTable *static_variables = closure->func.op_array.static_variables;
499
500            ALLOC_HASHTABLE(closure->func.op_array.static_variables);
501            zend_hash_init(closure->func.op_array.static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0);
502            zend_hash_apply_with_arguments(static_variables, zval_copy_static_var, 1, closure->func.op_array.static_variables);
503        }
504        closure->func.op_array.run_time_cache = NULL;
505        if (closure->func.op_array.refcount) {
506            (*closure->func.op_array.refcount)++;
507        }
508    } else {
509        /* verify that we aren't binding internal function to a wrong scope */
510        if(func->common.scope != NULL) {
511            if(scope && !instanceof_function(scope, func->common.scope)) {
512                zend_error(E_WARNING, "Cannot bind function %s::%s to scope class %s", func->common.scope->name->val, func->common.function_name->val, scope->name->val);
513                scope = NULL;
514            }
515            if(scope && this_ptr && (func->common.fn_flags & ZEND_ACC_STATIC) == 0 &&
516                    !instanceof_function(Z_OBJCE_P(this_ptr), closure->func.common.scope)) {
517                zend_error(E_WARNING, "Cannot bind function %s::%s to object of class %s", func->common.scope->name->val, func->common.function_name->val, Z_OBJCE_P(this_ptr)->name->val);
518                scope = NULL;
519                this_ptr = NULL;
520            }
521        } else {
522            /* if it's a free function, we won't set scope & this since they're meaningless */
523            this_ptr = NULL;
524            scope = NULL;
525        }
526    }
527
528    ZVAL_UNDEF(&closure->this_ptr);
529    /* Invariants:
530     * If the closure is unscoped, it has no bound object.
531     * The the closure is scoped, it's either static or it's bound */
532    closure->func.common.scope = scope;
533    if (scope) {
534        closure->func.common.fn_flags |= ZEND_ACC_PUBLIC;
535        if (this_ptr && Z_TYPE_P(this_ptr) == IS_OBJECT && (closure->func.common.fn_flags & ZEND_ACC_STATIC) == 0) {
536            ZVAL_COPY(&closure->this_ptr, this_ptr);
537        } else {
538            closure->func.common.fn_flags |= ZEND_ACC_STATIC;
539        }
540    }
541}
542/* }}} */
543
544/*
545 * Local variables:
546 * tab-width: 4
547 * c-basic-offset: 4
548 * indent-tabs-mode: t
549 * End:
550 */
551