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