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    zend_class_entry *called_scope;
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    zend_object *newobj;
84
85    if (zend_parse_parameters(ZEND_NUM_ARGS(), "o*", &newthis, &my_params, &my_param_count) == FAILURE) {
86        return;
87    }
88
89    zclosure = getThis();
90    closure = (zend_closure *)Z_OBJ_P(zclosure);
91
92    if (closure->func.common.fn_flags & ZEND_ACC_STATIC) {
93        zend_error(E_WARNING, "Cannot bind an instance to a static closure");
94        return;
95    }
96
97    if (closure->func.type == ZEND_INTERNAL_FUNCTION) {
98        /* verify that we aren't binding internal function to a wrong object */
99        if ((closure->func.common.fn_flags & ZEND_ACC_STATIC) == 0 &&
100                !instanceof_function(Z_OBJCE_P(newthis), closure->func.common.scope)) {
101            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);
102            return;
103        }
104    }
105
106    newobj = Z_OBJ_P(newthis);
107
108    if (newobj->ce != closure->func.common.scope && newobj->ce->type == ZEND_INTERNAL_CLASS) {
109        /* rebinding to internal class is not allowed */
110        zend_error(E_WARNING, "Cannot bind closure to object of internal class %s", newobj->ce->name->val);
111        return;
112    }
113
114    /* This should never happen as closures will always be callable */
115    if (zend_fcall_info_init(zclosure, 0, &fci, &fci_cache, NULL, NULL) != SUCCESS) {
116        ZEND_ASSERT(0);
117    }
118
119    fci.retval = &closure_result;
120    fci.params = my_params;
121    fci.param_count = my_param_count;
122    fci.object = fci_cache.object = newobj;
123    fci_cache.initialized = 1;
124
125    my_function = *fci_cache.function_handler;
126    /* use scope of passed object */
127    my_function.common.scope = Z_OBJCE_P(newthis);
128    fci_cache.function_handler = &my_function;
129
130    if (zend_call_function(&fci, &fci_cache) == SUCCESS && Z_TYPE(closure_result) != IS_UNDEF) {
131        ZVAL_COPY_VALUE(return_value, &closure_result);
132    }
133}
134/* }}} */
135
136/* {{{ proto Closure Closure::bind(Closure $old, object $to [, mixed $scope = "static" ] )
137   Create a closure from another one and bind to another object and scope */
138ZEND_METHOD(Closure, bind)
139{
140    zval *newthis, *zclosure, *scope_arg = NULL;
141    zend_closure *closure;
142    zend_class_entry *ce, *called_scope;
143
144    if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Oo!|z", &zclosure, zend_ce_closure, &newthis, &scope_arg) == FAILURE) {
145        RETURN_NULL();
146    }
147
148    closure = (zend_closure *)Z_OBJ_P(zclosure);
149
150    if ((newthis != NULL) && (closure->func.common.fn_flags & ZEND_ACC_STATIC)) {
151        zend_error(E_WARNING, "Cannot bind an instance to a static closure");
152    }
153
154    if (scope_arg != NULL) { /* scope argument was given */
155        if (Z_TYPE_P(scope_arg) == IS_OBJECT) {
156            ce = Z_OBJCE_P(scope_arg);
157        } else if (Z_TYPE_P(scope_arg) == IS_NULL) {
158            ce = NULL;
159        } else {
160            zend_string *class_name = zval_get_string(scope_arg);
161            if (zend_string_equals_literal(class_name, "static")) {
162                ce = closure->func.common.scope;
163            } else if ((ce = zend_lookup_class_ex(class_name, NULL, 1)) == NULL) {
164                zend_error(E_WARNING, "Class '%s' not found", class_name->val);
165                zend_string_release(class_name);
166                RETURN_NULL();
167            }
168            zend_string_release(class_name);
169        }
170        if(ce && ce != closure->func.common.scope && ce->type == ZEND_INTERNAL_CLASS) {
171            /* rebinding to internal class is not allowed */
172            zend_error(E_WARNING, "Cannot bind closure to scope of internal class %s", ce->name->val);
173            return;
174        }
175    } else { /* scope argument not given; do not change the scope by default */
176        ce = closure->func.common.scope;
177    }
178
179    if (newthis) {
180        called_scope = Z_OBJCE_P(newthis);
181    } else {
182        called_scope = ce;
183    }
184
185    zend_create_closure(return_value, &closure->func, ce, called_scope, newthis);
186}
187/* }}} */
188
189static zend_function *zend_closure_get_constructor(zend_object *object) /* {{{ */
190{
191    zend_error(E_EXCEPTION | E_ERROR, "Instantiation of 'Closure' is not allowed");
192    return NULL;
193}
194/* }}} */
195
196static int zend_closure_compare_objects(zval *o1, zval *o2) /* {{{ */
197{
198    return (Z_OBJ_P(o1) != Z_OBJ_P(o2));
199}
200/* }}} */
201
202ZEND_API zend_function *zend_get_closure_invoke_method(zend_object *object) /* {{{ */
203{
204    zend_closure *closure = (zend_closure *)object;
205    zend_function *invoke = (zend_function*)emalloc(sizeof(zend_function));
206
207    invoke->common = closure->func.common;
208    /* We return ZEND_INTERNAL_FUNCTION, but arg_info representation is the
209     * same as for ZEND_USER_FUNCTION (uses zend_string* instead of char*).
210     * This is not a problem, because ZEND_ACC_HAS_TYPE_HINTS is never set,
211     * and we won't check arguments on internal function */
212    invoke->type = ZEND_INTERNAL_FUNCTION;
213    invoke->internal_function.fn_flags = ZEND_ACC_PUBLIC | ZEND_ACC_CALL_VIA_HANDLER | (closure->func.common.fn_flags & ZEND_ACC_RETURN_REFERENCE);
214    invoke->internal_function.handler = ZEND_MN(Closure___invoke);
215    invoke->internal_function.module = 0;
216    invoke->internal_function.scope = zend_ce_closure;
217    invoke->internal_function.function_name = zend_string_init(ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1, 0);
218    return invoke;
219}
220/* }}} */
221
222ZEND_API const zend_function *zend_get_closure_method_def(zval *obj) /* {{{ */
223{
224    zend_closure *closure = (zend_closure *)Z_OBJ_P(obj);
225    return &closure->func;
226}
227/* }}} */
228
229ZEND_API zval* zend_get_closure_this_ptr(zval *obj) /* {{{ */
230{
231    zend_closure *closure = (zend_closure *)Z_OBJ_P(obj);
232    return &closure->this_ptr;
233}
234/* }}} */
235
236static zend_function *zend_closure_get_method(zend_object **object, zend_string *method, const zval *key) /* {{{ */
237{
238    zend_string *lc_name;
239
240    lc_name = zend_string_tolower(method);
241    if (zend_string_equals_literal(method, ZEND_INVOKE_FUNC_NAME)) {
242        zend_string_release(lc_name);
243        return zend_get_closure_invoke_method(*object);
244    }
245    zend_string_release(lc_name);
246    return std_object_handlers.get_method(object, method, key);
247}
248/* }}} */
249
250static zval *zend_closure_read_property(zval *object, zval *member, int type, void **cache_slot, zval *rv) /* {{{ */
251{
252    ZEND_CLOSURE_PROPERTY_ERROR();
253    return &EG(uninitialized_zval);
254}
255/* }}} */
256
257static void zend_closure_write_property(zval *object, zval *member, zval *value, void **cache_slot) /* {{{ */
258{
259    ZEND_CLOSURE_PROPERTY_ERROR();
260}
261/* }}} */
262
263static zval *zend_closure_get_property_ptr_ptr(zval *object, zval *member, int type, void **cache_slot) /* {{{ */
264{
265    ZEND_CLOSURE_PROPERTY_ERROR();
266    return NULL;
267}
268/* }}} */
269
270static int zend_closure_has_property(zval *object, zval *member, int has_set_exists, void **cache_slot) /* {{{ */
271{
272    if (has_set_exists != 2) {
273        ZEND_CLOSURE_PROPERTY_ERROR();
274    }
275    return 0;
276}
277/* }}} */
278
279static void zend_closure_unset_property(zval *object, zval *member, void **cache_slot) /* {{{ */
280{
281    ZEND_CLOSURE_PROPERTY_ERROR();
282}
283/* }}} */
284
285static void zend_closure_free_storage(zend_object *object) /* {{{ */
286{
287    zend_closure *closure = (zend_closure *)object;
288
289    zend_object_std_dtor(&closure->std);
290
291    if (closure->func.type == ZEND_USER_FUNCTION) {
292        destroy_op_array(&closure->func.op_array);
293    }
294
295    if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
296        zval_ptr_dtor(&closure->this_ptr);
297    }
298}
299/* }}} */
300
301static zend_object *zend_closure_new(zend_class_entry *class_type) /* {{{ */
302{
303    zend_closure *closure;
304
305    closure = emalloc(sizeof(zend_closure));
306    memset(closure, 0, sizeof(zend_closure));
307
308    zend_object_std_init(&closure->std, class_type);
309    closure->std.handlers = &closure_handlers;
310
311    return (zend_object*)closure;
312}
313/* }}} */
314
315static zend_object *zend_closure_clone(zval *zobject) /* {{{ */
316{
317    zend_closure *closure = (zend_closure *)Z_OBJ_P(zobject);
318    zval result;
319
320    zend_create_closure(&result, &closure->func,
321        closure->func.common.scope, closure->called_scope, &closure->this_ptr);
322    return Z_OBJ(result);
323}
324/* }}} */
325
326int zend_closure_get_closure(zval *obj, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zend_object **obj_ptr) /* {{{ */
327{
328    zend_closure *closure;
329
330    if (Z_TYPE_P(obj) != IS_OBJECT) {
331        return FAILURE;
332    }
333
334    closure = (zend_closure *)Z_OBJ_P(obj);
335    *fptr_ptr = &closure->func;
336    *ce_ptr = closure->called_scope;
337
338    if (obj_ptr) {
339        if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
340            *obj_ptr = Z_OBJ(closure->this_ptr);
341        } else {
342            *obj_ptr = NULL;
343        }
344    }
345    return SUCCESS;
346}
347/* }}} */
348
349static HashTable *zend_closure_get_debug_info(zval *object, int *is_temp) /* {{{ */
350{
351    zend_closure *closure = (zend_closure *)Z_OBJ_P(object);
352    zval val;
353    struct _zend_arg_info *arg_info = closure->func.common.arg_info;
354    HashTable *debug_info;
355
356    *is_temp = 1;
357
358    ALLOC_HASHTABLE(debug_info);
359    zend_hash_init(debug_info, 8, NULL, ZVAL_PTR_DTOR, 0);
360
361    if (closure->func.type == ZEND_USER_FUNCTION && closure->func.op_array.static_variables) {
362        HashTable *static_variables = closure->func.op_array.static_variables;
363        ZVAL_ARR(&val, zend_array_dup(static_variables));
364        zend_hash_str_update(debug_info, "static", sizeof("static")-1, &val);
365    }
366
367    if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
368        Z_ADDREF(closure->this_ptr);
369        zend_hash_str_update(debug_info, "this", sizeof("this")-1, &closure->this_ptr);
370    }
371
372    if (arg_info &&
373        (closure->func.common.num_args ||
374         (closure->func.common.fn_flags & ZEND_ACC_VARIADIC))) {
375        uint32_t i, num_args, required = closure->func.common.required_num_args;
376
377        array_init(&val);
378
379        num_args = closure->func.common.num_args;
380        if (closure->func.common.fn_flags & ZEND_ACC_VARIADIC) {
381            num_args++;
382        }
383        for (i = 0; i < num_args; i++) {
384            zend_string *name;
385            zval info;
386            if (arg_info->name) {
387                name = zend_strpprintf(0, "%s$%s",
388                        arg_info->pass_by_reference ? "&" : "",
389                        arg_info->name->val);
390            } else {
391                name = zend_strpprintf(0, "%s$param%d",
392                        arg_info->pass_by_reference ? "&" : "",
393                        i + 1);
394            }
395            ZVAL_NEW_STR(&info, zend_strpprintf(0, "%s", i >= required ? "<optional>" : "<required>"));
396            zend_hash_update(Z_ARRVAL(val), name, &info);
397            zend_string_release(name);
398            arg_info++;
399        }
400        zend_hash_str_update(debug_info, "parameter", sizeof("parameter")-1, &val);
401    }
402
403    return debug_info;
404}
405/* }}} */
406
407static HashTable *zend_closure_get_gc(zval *obj, zval **table, int *n) /* {{{ */
408{
409    zend_closure *closure = (zend_closure *)Z_OBJ_P(obj);
410
411    *table = Z_TYPE(closure->this_ptr) != IS_NULL ? &closure->this_ptr : NULL;
412    *n = Z_TYPE(closure->this_ptr) != IS_NULL ? 1 : 0;
413    return (closure->func.type == ZEND_USER_FUNCTION) ?
414        closure->func.op_array.static_variables : NULL;
415}
416/* }}} */
417
418/* {{{ proto Closure::__construct()
419   Private constructor preventing instantiation */
420ZEND_METHOD(Closure, __construct)
421{
422    zend_error(E_EXCEPTION | E_ERROR, "Instantiation of 'Closure' is not allowed");
423}
424/* }}} */
425
426ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_bindto, 0, 0, 1)
427    ZEND_ARG_INFO(0, newthis)
428    ZEND_ARG_INFO(0, newscope)
429ZEND_END_ARG_INFO()
430
431ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_bind, 0, 0, 2)
432    ZEND_ARG_INFO(0, closure)
433    ZEND_ARG_INFO(0, newthis)
434    ZEND_ARG_INFO(0, newscope)
435ZEND_END_ARG_INFO()
436
437ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_call, 0, 0, 1)
438    ZEND_ARG_INFO(0, newthis)
439    ZEND_ARG_VARIADIC_INFO(0, parameters)
440ZEND_END_ARG_INFO()
441
442static const zend_function_entry closure_functions[] = {
443    ZEND_ME(Closure, __construct, NULL, ZEND_ACC_PRIVATE)
444    ZEND_ME(Closure, bind, arginfo_closure_bind, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
445    ZEND_MALIAS(Closure, bindTo, bind, arginfo_closure_bindto, ZEND_ACC_PUBLIC)
446    ZEND_ME(Closure, call, arginfo_closure_call, ZEND_ACC_PUBLIC)
447    ZEND_FE_END
448};
449
450void zend_register_closure_ce(void) /* {{{ */
451{
452    zend_class_entry ce;
453
454    INIT_CLASS_ENTRY(ce, "Closure", closure_functions);
455    zend_ce_closure = zend_register_internal_class(&ce);
456    zend_ce_closure->ce_flags |= ZEND_ACC_FINAL;
457    zend_ce_closure->create_object = zend_closure_new;
458    zend_ce_closure->serialize = zend_class_serialize_deny;
459    zend_ce_closure->unserialize = zend_class_unserialize_deny;
460
461    memcpy(&closure_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
462    closure_handlers.free_obj = zend_closure_free_storage;
463    closure_handlers.clone_obj = NULL;
464    closure_handlers.get_constructor = zend_closure_get_constructor;
465    closure_handlers.get_method = zend_closure_get_method;
466    closure_handlers.write_property = zend_closure_write_property;
467    closure_handlers.read_property = zend_closure_read_property;
468    closure_handlers.get_property_ptr_ptr = zend_closure_get_property_ptr_ptr;
469    closure_handlers.has_property = zend_closure_has_property;
470    closure_handlers.unset_property = zend_closure_unset_property;
471    closure_handlers.compare_objects = zend_closure_compare_objects;
472    closure_handlers.clone_obj = zend_closure_clone;
473    closure_handlers.get_debug_info = zend_closure_get_debug_info;
474    closure_handlers.get_closure = zend_closure_get_closure;
475    closure_handlers.get_gc = zend_closure_get_gc;
476}
477/* }}} */
478
479ZEND_API void zend_create_closure(zval *res, zend_function *func, zend_class_entry *scope, zend_class_entry *called_scope, zval *this_ptr) /* {{{ */
480{
481    zend_closure *closure;
482
483    object_init_ex(res, zend_ce_closure);
484
485    closure = (zend_closure *)Z_OBJ_P(res);
486
487    closure->func = *func;
488    closure->func.common.prototype = (zend_function*)closure;
489    closure->func.common.fn_flags |= ZEND_ACC_CLOSURE;
490
491    if ((scope == NULL) && this_ptr && (Z_TYPE_P(this_ptr) != IS_UNDEF)) {
492        /* use dummy scope if we're binding an object without specifying a scope */
493        /* maybe it would be better to create one for this purpose */
494        scope = zend_ce_closure;
495    }
496
497    if (closure->func.type == ZEND_USER_FUNCTION) {
498        if (closure->func.op_array.static_variables) {
499            HashTable *static_variables = closure->func.op_array.static_variables;
500
501            ALLOC_HASHTABLE(closure->func.op_array.static_variables);
502            zend_hash_init(closure->func.op_array.static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0);
503            zend_hash_apply_with_arguments(static_variables, zval_copy_static_var, 1, closure->func.op_array.static_variables);
504        }
505        closure->func.op_array.run_time_cache = NULL;
506        if (closure->func.op_array.refcount) {
507            (*closure->func.op_array.refcount)++;
508        }
509    } else {
510        /* verify that we aren't binding internal function to a wrong scope */
511        if(func->common.scope != NULL) {
512            if(scope && !instanceof_function(scope, func->common.scope)) {
513                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);
514                scope = NULL;
515            }
516            if(scope && this_ptr && (func->common.fn_flags & ZEND_ACC_STATIC) == 0 &&
517                    !instanceof_function(Z_OBJCE_P(this_ptr), closure->func.common.scope)) {
518                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);
519                scope = NULL;
520                this_ptr = NULL;
521            }
522        } else {
523            /* if it's a free function, we won't set scope & this since they're meaningless */
524            this_ptr = NULL;
525            scope = NULL;
526        }
527    }
528
529    ZVAL_UNDEF(&closure->this_ptr);
530    /* Invariant:
531     * If the closure is unscoped or static, it has no bound object. */
532    closure->func.common.scope = scope;
533    closure->called_scope = called_scope;
534    if (scope) {
535        closure->func.common.fn_flags |= ZEND_ACC_PUBLIC;
536        if (this_ptr && Z_TYPE_P(this_ptr) == IS_OBJECT && (closure->func.common.fn_flags & ZEND_ACC_STATIC) == 0) {
537            ZVAL_COPY(&closure->this_ptr, this_ptr);
538        }
539    }
540}
541/* }}} */
542
543/*
544 * Local variables:
545 * tab-width: 4
546 * c-basic-offset: 4
547 * indent-tabs-mode: t
548 * End:
549 */
550