xref: /PHP-7.3/Zend/zend_closures.c (revision 773f980e)
1 /*
2    +----------------------------------------------------------------------+
3    | Zend Engine                                                          |
4    +----------------------------------------------------------------------+
5    | Copyright (c) 1998-2018 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@php.net>                              |
17    |          Marcus Boerger <helly@php.net>                              |
18    +----------------------------------------------------------------------+
19 */
20 
21 #include "zend.h"
22 #include "zend_API.h"
23 #include "zend_closures.h"
24 #include "zend_exceptions.h"
25 #include "zend_interfaces.h"
26 #include "zend_objects.h"
27 #include "zend_objects_API.h"
28 #include "zend_globals.h"
29 
30 #define ZEND_CLOSURE_PRINT_NAME "Closure object"
31 
32 #define ZEND_CLOSURE_PROPERTY_ERROR() \
33 	zend_throw_error(NULL, "Closure object cannot have properties")
34 
35 typedef struct _zend_closure {
36 	zend_object       std;
37 	zend_function     func;
38 	zval              this_ptr;
39 	zend_class_entry *called_scope;
40 	zif_handler       orig_internal_handler;
41 } zend_closure;
42 
43 /* non-static since it needs to be referenced */
44 ZEND_API zend_class_entry *zend_ce_closure;
45 static zend_object_handlers closure_handlers;
46 
ZEND_METHOD(Closure,__invoke)47 ZEND_METHOD(Closure, __invoke) /* {{{ */
48 {
49 	zend_function *func = EX(func);
50 	zval *arguments = ZEND_CALL_ARG(execute_data, 1);
51 
52 	if (call_user_function(CG(function_table), NULL, getThis(), return_value, ZEND_NUM_ARGS(), arguments) == FAILURE) {
53 		RETVAL_FALSE;
54 	}
55 
56 	/* destruct the function also, then - we have allocated it in get_method */
57 	zend_string_release_ex(func->internal_function.function_name, 0);
58 	efree(func);
59 #if ZEND_DEBUG
60 	execute_data->func = NULL;
61 #endif
62 }
63 /* }}} */
64 
zend_valid_closure_binding(zend_closure * closure,zval * newthis,zend_class_entry * scope)65 static zend_bool zend_valid_closure_binding(
66 		zend_closure *closure, zval *newthis, zend_class_entry *scope) /* {{{ */
67 {
68 	zend_function *func = &closure->func;
69 	zend_bool is_fake_closure = (func->common.fn_flags & ZEND_ACC_FAKE_CLOSURE) != 0;
70 	if (newthis) {
71 		if (func->common.fn_flags & ZEND_ACC_STATIC) {
72 			zend_error(E_WARNING, "Cannot bind an instance to a static closure");
73 			return 0;
74 		}
75 
76 		if (is_fake_closure && func->common.scope &&
77 				!instanceof_function(Z_OBJCE_P(newthis), func->common.scope)) {
78 			/* Binding incompatible $this to an internal method is not supported. */
79 			zend_error(E_WARNING, "Cannot bind method %s::%s() to object of class %s",
80 					ZSTR_VAL(func->common.scope->name),
81 					ZSTR_VAL(func->common.function_name),
82 					ZSTR_VAL(Z_OBJCE_P(newthis)->name));
83 			return 0;
84 		}
85 	} else if (!(func->common.fn_flags & ZEND_ACC_STATIC) && func->common.scope
86 			&& func->type == ZEND_INTERNAL_FUNCTION) {
87 		zend_error(E_WARNING, "Cannot unbind $this of internal method");
88 		return 0;
89 	}
90 
91 	if (scope && scope != func->common.scope && scope->type == ZEND_INTERNAL_CLASS) {
92 		/* rebinding to internal class is not allowed */
93 		zend_error(E_WARNING, "Cannot bind closure to scope of internal class %s",
94 				ZSTR_VAL(scope->name));
95 		return 0;
96 	}
97 
98 	if (is_fake_closure && scope != func->common.scope) {
99 		zend_error(E_WARNING, "Cannot rebind scope of closure created by ReflectionFunctionAbstract::getClosure()");
100 		return 0;
101 	}
102 
103 	return 1;
104 }
105 /* }}} */
106 
107 /* {{{ proto mixed Closure::call(object to [, mixed parameter] [, mixed ...] )
108    Call closure, binding to a given object with its class as the scope */
ZEND_METHOD(Closure,call)109 ZEND_METHOD(Closure, call)
110 {
111 	zval *zclosure, *newthis, closure_result;
112 	zend_closure *closure;
113 	zend_fcall_info fci;
114 	zend_fcall_info_cache fci_cache;
115 	zend_function my_function;
116 	zend_object *newobj;
117 
118 	fci.param_count = 0;
119 	fci.params = NULL;
120 
121 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "o*", &newthis, &fci.params, &fci.param_count) == FAILURE) {
122 		return;
123 	}
124 
125 	zclosure = getThis();
126 	closure = (zend_closure *) Z_OBJ_P(zclosure);
127 
128 	newobj = Z_OBJ_P(newthis);
129 
130 	if (!zend_valid_closure_binding(closure, newthis, Z_OBJCE_P(newthis))) {
131 		return;
132 	}
133 
134 	if (closure->func.common.fn_flags & ZEND_ACC_GENERATOR) {
135 		zval new_closure;
136 		zend_create_closure(&new_closure, &closure->func, Z_OBJCE_P(newthis), closure->called_scope, newthis);
137 		closure = (zend_closure *) Z_OBJ(new_closure);
138 		fci_cache.function_handler = &closure->func;
139 	} else {
140 		memcpy(&my_function, &closure->func, closure->func.type == ZEND_USER_FUNCTION ? sizeof(zend_op_array) : sizeof(zend_internal_function));
141 		my_function.common.fn_flags &= ~ZEND_ACC_CLOSURE;
142 		/* use scope of passed object */
143 		my_function.common.scope = Z_OBJCE_P(newthis);
144 		fci_cache.function_handler = &my_function;
145 
146 		/* Runtime cache relies on bound scope to be immutable, hence we need a separate rt cache in case scope changed */
147 		if (ZEND_USER_CODE(my_function.type) && closure->func.common.scope != Z_OBJCE_P(newthis)) {
148 			my_function.op_array.run_time_cache = emalloc(my_function.op_array.cache_size);
149 			memset(my_function.op_array.run_time_cache, 0, my_function.op_array.cache_size);
150 		}
151 	}
152 
153 	fci_cache.called_scope = newobj->ce;
154 	fci_cache.object = fci.object = newobj;
155 
156 	fci.size = sizeof(fci);
157 	ZVAL_COPY_VALUE(&fci.function_name, zclosure);
158 	fci.retval = &closure_result;
159 	fci.no_separation = 1;
160 
161 	if (zend_call_function(&fci, &fci_cache) == SUCCESS && Z_TYPE(closure_result) != IS_UNDEF) {
162 		if (Z_ISREF(closure_result)) {
163 			zend_unwrap_reference(&closure_result);
164 		}
165 		ZVAL_COPY_VALUE(return_value, &closure_result);
166 	}
167 
168 	if (fci_cache.function_handler->common.fn_flags & ZEND_ACC_GENERATOR) {
169 		/* copied upon generator creation */
170 		GC_DELREF(&closure->std);
171 	} else if (ZEND_USER_CODE(my_function.type) && closure->func.common.scope != Z_OBJCE_P(newthis)) {
172 		efree(my_function.op_array.run_time_cache);
173 	}
174 }
175 /* }}} */
176 
177 /* {{{ proto Closure Closure::bind(callable old, object to [, mixed scope])
178    Create a closure from another one and bind to another object and scope */
ZEND_METHOD(Closure,bind)179 ZEND_METHOD(Closure, bind)
180 {
181 	zval *newthis, *zclosure, *scope_arg = NULL;
182 	zend_closure *closure;
183 	zend_class_entry *ce, *called_scope;
184 
185 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Oo!|z", &zclosure, zend_ce_closure, &newthis, &scope_arg) == FAILURE) {
186 		return;
187 	}
188 
189 	closure = (zend_closure *)Z_OBJ_P(zclosure);
190 
191 	if (scope_arg != NULL) { /* scope argument was given */
192 		if (Z_TYPE_P(scope_arg) == IS_OBJECT) {
193 			ce = Z_OBJCE_P(scope_arg);
194 		} else if (Z_TYPE_P(scope_arg) == IS_NULL) {
195 			ce = NULL;
196 		} else {
197 			zend_string *tmp_class_name;
198 			zend_string *class_name = zval_get_tmp_string(scope_arg, &tmp_class_name);
199 			if (zend_string_equals_literal(class_name, "static")) {
200 				ce = closure->func.common.scope;
201 			} else if ((ce = zend_lookup_class_ex(class_name, NULL, 1)) == NULL) {
202 				zend_error(E_WARNING, "Class '%s' not found", ZSTR_VAL(class_name));
203 				zend_tmp_string_release(tmp_class_name);
204 				RETURN_NULL();
205 			}
206 			zend_tmp_string_release(tmp_class_name);
207 		}
208 	} else { /* scope argument not given; do not change the scope by default */
209 		ce = closure->func.common.scope;
210 	}
211 
212 	if (!zend_valid_closure_binding(closure, newthis, ce)) {
213 		return;
214 	}
215 
216 	if (newthis) {
217 		called_scope = Z_OBJCE_P(newthis);
218 	} else {
219 		called_scope = ce;
220 	}
221 
222 	zend_create_closure(return_value, &closure->func, ce, called_scope, newthis);
223 }
224 /* }}} */
225 
ZEND_NAMED_FUNCTION(zend_closure_call_magic)226 static ZEND_NAMED_FUNCTION(zend_closure_call_magic) /* {{{ */ {
227 	zend_fcall_info fci;
228 	zend_fcall_info_cache fcc;
229 	zval params[2];
230 
231 	memset(&fci, 0, sizeof(zend_fcall_info));
232 	memset(&fcc, 0, sizeof(zend_fcall_info_cache));
233 
234 	fci.size = sizeof(zend_fcall_info);
235 	fci.retval = return_value;
236 
237 	fcc.function_handler = (EX(func)->internal_function.fn_flags & ZEND_ACC_STATIC) ?
238 		EX(func)->internal_function.scope->__callstatic : EX(func)->internal_function.scope->__call;
239 	fci.params = params;
240 	fci.param_count = 2;
241 	ZVAL_STR(&fci.params[0], EX(func)->common.function_name);
242 	if (ZEND_NUM_ARGS()) {
243 		array_init_size(&fci.params[1], ZEND_NUM_ARGS());
244 		zend_copy_parameters_array(ZEND_NUM_ARGS(), &fci.params[1]);
245 	} else {
246 		ZVAL_EMPTY_ARRAY(&fci.params[1]);
247 	}
248 
249 	fci.object = Z_OBJ(EX(This));
250 	fcc.object = Z_OBJ(EX(This));
251 
252 	zend_call_function(&fci, &fcc);
253 
254 	zval_ptr_dtor(&fci.params[0]);
255 	zval_ptr_dtor(&fci.params[1]);
256 }
257 /* }}} */
258 
zend_create_closure_from_callable(zval * return_value,zval * callable,char ** error)259 static int zend_create_closure_from_callable(zval *return_value, zval *callable, char **error) /* {{{ */ {
260 	zend_fcall_info_cache fcc;
261 	zend_function *mptr;
262 	zval instance;
263 	zend_internal_function call;
264 
265 	if (!zend_is_callable_ex(callable, NULL, 0, NULL, &fcc, error)) {
266 		return FAILURE;
267 	}
268 
269 	mptr = fcc.function_handler;
270 	if (mptr->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) {
271 		/* For Closure::fromCallable([$closure, "__invoke"]) return $closure. */
272 		if (fcc.object && fcc.object->ce == zend_ce_closure
273 				&& zend_string_equals_literal(mptr->common.function_name, "__invoke")) {
274 			ZVAL_OBJ(return_value, fcc.object);
275 			GC_ADDREF(fcc.object);
276 			zend_free_trampoline(mptr);
277 			return SUCCESS;
278 		}
279 
280 		memset(&call, 0, sizeof(zend_internal_function));
281 		call.type = ZEND_INTERNAL_FUNCTION;
282 		call.fn_flags = mptr->common.fn_flags & ZEND_ACC_STATIC;
283 		call.handler = zend_closure_call_magic;
284 		call.function_name = mptr->common.function_name;
285 		call.scope = mptr->common.scope;
286 
287 		zend_free_trampoline(mptr);
288 		mptr = (zend_function *) &call;
289 	}
290 
291 	if (fcc.object) {
292 		ZVAL_OBJ(&instance, fcc.object);
293 		zend_create_fake_closure(return_value, mptr, mptr->common.scope, fcc.called_scope, &instance);
294 	} else {
295 		zend_create_fake_closure(return_value, mptr, mptr->common.scope, fcc.called_scope, NULL);
296 	}
297 
298 	return SUCCESS;
299 }
300 /* }}} */
301 
302 /* {{{ proto Closure Closure::fromCallable(callable callable)
303    Create a closure from a callable using the current scope. */
ZEND_METHOD(Closure,fromCallable)304 ZEND_METHOD(Closure, fromCallable)
305 {
306 	zval *callable;
307 	int success;
308 	char *error = NULL;
309 
310 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &callable) == FAILURE) {
311 		return;
312 	}
313 
314 	if (Z_TYPE_P(callable) == IS_OBJECT && instanceof_function(Z_OBJCE_P(callable), zend_ce_closure)) {
315 		/* It's already a closure */
316 		RETURN_ZVAL(callable, 1, 0);
317 	}
318 
319 	/* create closure as if it were called from parent scope */
320 	EG(current_execute_data) = EX(prev_execute_data);
321 	success = zend_create_closure_from_callable(return_value, callable, &error);
322 	EG(current_execute_data) = execute_data;
323 
324 	if (success == FAILURE || error) {
325 		if (error) {
326 			zend_throw_exception_ex(zend_ce_type_error, 0, "Failed to create closure from callable: %s", error);
327 			efree(error);
328 		} else {
329 			zend_throw_exception_ex(zend_ce_type_error, 0, "Failed to create closure from callable");
330 		}
331 	}
332 }
333 /* }}} */
334 
zend_closure_get_constructor(zend_object * object)335 static ZEND_COLD zend_function *zend_closure_get_constructor(zend_object *object) /* {{{ */
336 {
337 	zend_throw_error(NULL, "Instantiation of 'Closure' is not allowed");
338 	return NULL;
339 }
340 /* }}} */
341 
zend_closure_compare_objects(zval * o1,zval * o2)342 static int zend_closure_compare_objects(zval *o1, zval *o2) /* {{{ */
343 {
344 	return (Z_OBJ_P(o1) != Z_OBJ_P(o2));
345 }
346 /* }}} */
347 
zend_get_closure_invoke_method(zend_object * object)348 ZEND_API zend_function *zend_get_closure_invoke_method(zend_object *object) /* {{{ */
349 {
350 	zend_closure *closure = (zend_closure *)object;
351 	zend_function *invoke = (zend_function*)emalloc(sizeof(zend_function));
352 	const uint32_t keep_flags =
353 		ZEND_ACC_RETURN_REFERENCE | ZEND_ACC_VARIADIC | ZEND_ACC_HAS_RETURN_TYPE;
354 
355 	invoke->common = closure->func.common;
356 	/* We return ZEND_INTERNAL_FUNCTION, but arg_info representation is the
357 	 * same as for ZEND_USER_FUNCTION (uses zend_string* instead of char*).
358 	 * This is not a problem, because ZEND_ACC_HAS_TYPE_HINTS is never set,
359 	 * and we won't check arguments on internal function. We also set
360 	 * ZEND_ACC_USER_ARG_INFO flag to prevent invalid usage by Reflection */
361 	invoke->type = ZEND_INTERNAL_FUNCTION;
362 	invoke->internal_function.fn_flags =
363 		ZEND_ACC_PUBLIC | ZEND_ACC_CALL_VIA_HANDLER | (closure->func.common.fn_flags & keep_flags);
364 	if (closure->func.type != ZEND_INTERNAL_FUNCTION || (closure->func.common.fn_flags & ZEND_ACC_USER_ARG_INFO)) {
365 		invoke->internal_function.fn_flags |=
366 			ZEND_ACC_USER_ARG_INFO;
367 	}
368 	invoke->internal_function.handler = ZEND_MN(Closure___invoke);
369 	invoke->internal_function.module = 0;
370 	invoke->internal_function.scope = zend_ce_closure;
371 	invoke->internal_function.function_name = ZSTR_KNOWN(ZEND_STR_MAGIC_INVOKE);
372 	return invoke;
373 }
374 /* }}} */
375 
zend_get_closure_method_def(zval * obj)376 ZEND_API const zend_function *zend_get_closure_method_def(zval *obj) /* {{{ */
377 {
378 	zend_closure *closure = (zend_closure *)Z_OBJ_P(obj);
379 	return &closure->func;
380 }
381 /* }}} */
382 
zend_get_closure_this_ptr(zval * obj)383 ZEND_API zval* zend_get_closure_this_ptr(zval *obj) /* {{{ */
384 {
385 	zend_closure *closure = (zend_closure *)Z_OBJ_P(obj);
386 	return &closure->this_ptr;
387 }
388 /* }}} */
389 
zend_closure_get_method(zend_object ** object,zend_string * method,const zval * key)390 static zend_function *zend_closure_get_method(zend_object **object, zend_string *method, const zval *key) /* {{{ */
391 {
392 	if (zend_string_equals_literal_ci(method, ZEND_INVOKE_FUNC_NAME)) {
393 		return zend_get_closure_invoke_method(*object);
394 	}
395 
396 	return zend_std_get_method(object, method, key);
397 }
398 /* }}} */
399 
zend_closure_read_property(zval * object,zval * member,int type,void ** cache_slot,zval * rv)400 static zval *zend_closure_read_property(zval *object, zval *member, int type, void **cache_slot, zval *rv) /* {{{ */
401 {
402 	ZEND_CLOSURE_PROPERTY_ERROR();
403 	return &EG(uninitialized_zval);
404 }
405 /* }}} */
406 
zend_closure_write_property(zval * object,zval * member,zval * value,void ** cache_slot)407 static void zend_closure_write_property(zval *object, zval *member, zval *value, void **cache_slot) /* {{{ */
408 {
409 	ZEND_CLOSURE_PROPERTY_ERROR();
410 }
411 /* }}} */
412 
zend_closure_get_property_ptr_ptr(zval * object,zval * member,int type,void ** cache_slot)413 static zval *zend_closure_get_property_ptr_ptr(zval *object, zval *member, int type, void **cache_slot) /* {{{ */
414 {
415 	ZEND_CLOSURE_PROPERTY_ERROR();
416 	return NULL;
417 }
418 /* }}} */
419 
zend_closure_has_property(zval * object,zval * member,int has_set_exists,void ** cache_slot)420 static int zend_closure_has_property(zval *object, zval *member, int has_set_exists, void **cache_slot) /* {{{ */
421 {
422 	if (has_set_exists != ZEND_PROPERTY_EXISTS) {
423 		ZEND_CLOSURE_PROPERTY_ERROR();
424 	}
425 	return 0;
426 }
427 /* }}} */
428 
zend_closure_unset_property(zval * object,zval * member,void ** cache_slot)429 static void zend_closure_unset_property(zval *object, zval *member, void **cache_slot) /* {{{ */
430 {
431 	ZEND_CLOSURE_PROPERTY_ERROR();
432 }
433 /* }}} */
434 
zend_closure_free_storage(zend_object * object)435 static void zend_closure_free_storage(zend_object *object) /* {{{ */
436 {
437 	zend_closure *closure = (zend_closure *)object;
438 
439 	zend_object_std_dtor(&closure->std);
440 
441 	if (closure->func.type == ZEND_USER_FUNCTION) {
442 		if (closure->func.op_array.fn_flags & ZEND_ACC_NO_RT_ARENA) {
443 			efree(closure->func.op_array.run_time_cache);
444 			closure->func.op_array.run_time_cache = NULL;
445 		}
446 		destroy_op_array(&closure->func.op_array);
447 	}
448 
449 	if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
450 		zval_ptr_dtor(&closure->this_ptr);
451 	}
452 }
453 /* }}} */
454 
zend_closure_new(zend_class_entry * class_type)455 static zend_object *zend_closure_new(zend_class_entry *class_type) /* {{{ */
456 {
457 	zend_closure *closure;
458 
459 	closure = emalloc(sizeof(zend_closure));
460 	memset(closure, 0, sizeof(zend_closure));
461 
462 	zend_object_std_init(&closure->std, class_type);
463 	closure->std.handlers = &closure_handlers;
464 
465 	return (zend_object*)closure;
466 }
467 /* }}} */
468 
zend_closure_clone(zval * zobject)469 static zend_object *zend_closure_clone(zval *zobject) /* {{{ */
470 {
471 	zend_closure *closure = (zend_closure *)Z_OBJ_P(zobject);
472 	zval result;
473 
474 	zend_create_closure(&result, &closure->func,
475 		closure->func.common.scope, closure->called_scope, &closure->this_ptr);
476 	return Z_OBJ(result);
477 }
478 /* }}} */
479 
zend_closure_get_closure(zval * obj,zend_class_entry ** ce_ptr,zend_function ** fptr_ptr,zend_object ** obj_ptr)480 int zend_closure_get_closure(zval *obj, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zend_object **obj_ptr) /* {{{ */
481 {
482 	zend_closure *closure = (zend_closure *)Z_OBJ_P(obj);
483 	*fptr_ptr = &closure->func;
484 	*ce_ptr = closure->called_scope;
485 
486 	if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
487 		*obj_ptr = Z_OBJ(closure->this_ptr);
488 	} else {
489 		*obj_ptr = NULL;
490 	}
491 
492 	return SUCCESS;
493 }
494 /* }}} */
495 
zend_closure_get_debug_info(zval * object,int * is_temp)496 static HashTable *zend_closure_get_debug_info(zval *object, int *is_temp) /* {{{ */
497 {
498 	zend_closure *closure = (zend_closure *)Z_OBJ_P(object);
499 	zval val;
500 	struct _zend_arg_info *arg_info = closure->func.common.arg_info;
501 	HashTable *debug_info;
502 	zend_bool zstr_args = (closure->func.type == ZEND_USER_FUNCTION) || (closure->func.common.fn_flags & ZEND_ACC_USER_ARG_INFO);
503 
504 	*is_temp = 1;
505 
506 	debug_info = zend_new_array(8);
507 
508 	if (closure->func.type == ZEND_USER_FUNCTION && closure->func.op_array.static_variables) {
509 		zval *var;
510 		HashTable *static_variables = closure->func.op_array.static_variables;
511 		ZVAL_ARR(&val, zend_array_dup(static_variables));
512 		zend_hash_update(debug_info, ZSTR_KNOWN(ZEND_STR_STATIC), &val);
513 		ZEND_HASH_FOREACH_VAL(Z_ARRVAL(val), var) {
514 			if (Z_TYPE_P(var) == IS_CONSTANT_AST) {
515 				zval_ptr_dtor(var);
516 				ZVAL_STRING(var, "<constant ast>");
517 			}
518 		} ZEND_HASH_FOREACH_END();
519 	}
520 
521 	if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
522 		Z_ADDREF(closure->this_ptr);
523 		zend_hash_update(debug_info, ZSTR_KNOWN(ZEND_STR_THIS), &closure->this_ptr);
524 	}
525 
526 	if (arg_info &&
527 		(closure->func.common.num_args ||
528 		 (closure->func.common.fn_flags & ZEND_ACC_VARIADIC))) {
529 		uint32_t i, num_args, required = closure->func.common.required_num_args;
530 
531 		array_init(&val);
532 
533 		num_args = closure->func.common.num_args;
534 		if (closure->func.common.fn_flags & ZEND_ACC_VARIADIC) {
535 			num_args++;
536 		}
537 		for (i = 0; i < num_args; i++) {
538 			zend_string *name;
539 			zval info;
540 			if (arg_info->name) {
541 				if (zstr_args) {
542 					name = zend_strpprintf(0, "%s$%s",
543 							arg_info->pass_by_reference ? "&" : "",
544 							ZSTR_VAL(arg_info->name));
545 				} else {
546 					name = zend_strpprintf(0, "%s$%s",
547 							arg_info->pass_by_reference ? "&" : "",
548 							((zend_internal_arg_info*)arg_info)->name);
549 				}
550 			} else {
551 				name = zend_strpprintf(0, "%s$param%d",
552 						arg_info->pass_by_reference ? "&" : "",
553 						i + 1);
554 			}
555 			ZVAL_NEW_STR(&info, zend_strpprintf(0, "%s", i >= required ? "<optional>" : "<required>"));
556 			zend_hash_update(Z_ARRVAL(val), name, &info);
557 			zend_string_release_ex(name, 0);
558 			arg_info++;
559 		}
560 		zend_hash_str_update(debug_info, "parameter", sizeof("parameter")-1, &val);
561 	}
562 
563 	return debug_info;
564 }
565 /* }}} */
566 
zend_closure_get_gc(zval * obj,zval ** table,int * n)567 static HashTable *zend_closure_get_gc(zval *obj, zval **table, int *n) /* {{{ */
568 {
569 	zend_closure *closure = (zend_closure *)Z_OBJ_P(obj);
570 
571 	*table = Z_TYPE(closure->this_ptr) != IS_NULL ? &closure->this_ptr : NULL;
572 	*n = Z_TYPE(closure->this_ptr) != IS_NULL ? 1 : 0;
573 	return (closure->func.type == ZEND_USER_FUNCTION) ?
574 		closure->func.op_array.static_variables : NULL;
575 }
576 /* }}} */
577 
578 /* {{{ proto Closure::__construct()
579    Private constructor preventing instantiation */
ZEND_METHOD(Closure,__construct)580 ZEND_COLD ZEND_METHOD(Closure, __construct)
581 {
582 	zend_throw_error(NULL, "Instantiation of 'Closure' is not allowed");
583 }
584 /* }}} */
585 
586 ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_bindto, 0, 0, 1)
587 	ZEND_ARG_INFO(0, newthis)
588 	ZEND_ARG_INFO(0, newscope)
589 ZEND_END_ARG_INFO()
590 
591 ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_bind, 0, 0, 2)
592 	ZEND_ARG_INFO(0, closure)
593 	ZEND_ARG_INFO(0, newthis)
594 	ZEND_ARG_INFO(0, newscope)
595 ZEND_END_ARG_INFO()
596 
597 ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_call, 0, 0, 1)
598 	ZEND_ARG_INFO(0, newthis)
599 	ZEND_ARG_VARIADIC_INFO(0, parameters)
600 ZEND_END_ARG_INFO()
601 
602 ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_fromcallable, 0, 0, 1)
603 	ZEND_ARG_INFO(0, callable)
604 ZEND_END_ARG_INFO()
605 
606 static const zend_function_entry closure_functions[] = {
607 	ZEND_ME(Closure, __construct, NULL, ZEND_ACC_PRIVATE)
608 	ZEND_ME(Closure, bind, arginfo_closure_bind, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
609 	ZEND_MALIAS(Closure, bindTo, bind, arginfo_closure_bindto, ZEND_ACC_PUBLIC)
610 	ZEND_ME(Closure, call, arginfo_closure_call, ZEND_ACC_PUBLIC)
611 	ZEND_ME(Closure, fromCallable, arginfo_closure_fromcallable, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
612 	ZEND_FE_END
613 };
614 
zend_register_closure_ce(void)615 void zend_register_closure_ce(void) /* {{{ */
616 {
617 	zend_class_entry ce;
618 
619 	INIT_CLASS_ENTRY(ce, "Closure", closure_functions);
620 	zend_ce_closure = zend_register_internal_class(&ce);
621 	zend_ce_closure->ce_flags |= ZEND_ACC_FINAL;
622 	zend_ce_closure->create_object = zend_closure_new;
623 	zend_ce_closure->serialize = zend_class_serialize_deny;
624 	zend_ce_closure->unserialize = zend_class_unserialize_deny;
625 
626 	memcpy(&closure_handlers, &std_object_handlers, sizeof(zend_object_handlers));
627 	closure_handlers.free_obj = zend_closure_free_storage;
628 	closure_handlers.get_constructor = zend_closure_get_constructor;
629 	closure_handlers.get_method = zend_closure_get_method;
630 	closure_handlers.write_property = zend_closure_write_property;
631 	closure_handlers.read_property = zend_closure_read_property;
632 	closure_handlers.get_property_ptr_ptr = zend_closure_get_property_ptr_ptr;
633 	closure_handlers.has_property = zend_closure_has_property;
634 	closure_handlers.unset_property = zend_closure_unset_property;
635 	closure_handlers.compare_objects = zend_closure_compare_objects;
636 	closure_handlers.clone_obj = zend_closure_clone;
637 	closure_handlers.get_debug_info = zend_closure_get_debug_info;
638 	closure_handlers.get_closure = zend_closure_get_closure;
639 	closure_handlers.get_gc = zend_closure_get_gc;
640 }
641 /* }}} */
642 
ZEND_NAMED_FUNCTION(zend_closure_internal_handler)643 static ZEND_NAMED_FUNCTION(zend_closure_internal_handler) /* {{{ */
644 {
645 	zend_closure *closure = (zend_closure*)ZEND_CLOSURE_OBJECT(EX(func));
646 	closure->orig_internal_handler(INTERNAL_FUNCTION_PARAM_PASSTHRU);
647 	OBJ_RELEASE((zend_object*)closure);
648 	EX(func) = NULL;
649 }
650 /* }}} */
651 
zend_create_closure(zval * res,zend_function * func,zend_class_entry * scope,zend_class_entry * called_scope,zval * this_ptr)652 ZEND_API void zend_create_closure(zval *res, zend_function *func, zend_class_entry *scope, zend_class_entry *called_scope, zval *this_ptr) /* {{{ */
653 {
654 	zend_closure *closure;
655 
656 	object_init_ex(res, zend_ce_closure);
657 
658 	closure = (zend_closure *)Z_OBJ_P(res);
659 
660 	if ((scope == NULL) && this_ptr && (Z_TYPE_P(this_ptr) != IS_UNDEF)) {
661 		/* use dummy scope if we're binding an object without specifying a scope */
662 		/* maybe it would be better to create one for this purpose */
663 		scope = zend_ce_closure;
664 	}
665 
666 	if (func->type == ZEND_USER_FUNCTION) {
667 		memcpy(&closure->func, func, sizeof(zend_op_array));
668 		closure->func.common.fn_flags |= ZEND_ACC_CLOSURE;
669 		closure->func.common.fn_flags &= ~ZEND_ACC_IMMUTABLE;
670 		if (closure->func.op_array.static_variables) {
671 			closure->func.op_array.static_variables =
672 				zend_array_dup(closure->func.op_array.static_variables);
673 		}
674 
675 		/* Runtime cache is scope-dependent, so we cannot reuse it if the scope changed */
676 		if (!closure->func.op_array.run_time_cache
677 			|| func->common.scope != scope
678 			|| (func->common.fn_flags & ZEND_ACC_NO_RT_ARENA)
679 		) {
680 			if (!func->op_array.run_time_cache
681 			 && (func->common.fn_flags & ZEND_ACC_CLOSURE)
682 			 && !(func->common.fn_flags & ZEND_ACC_IMMUTABLE)) {
683 				/* If a real closure is used for the first time, we create a shared runtime cache
684 				 * and remember which scope it is for. */
685 				func->common.scope = scope;
686 				func->op_array.run_time_cache = zend_arena_alloc(&CG(arena), func->op_array.cache_size);
687 				closure->func.op_array.run_time_cache = func->op_array.run_time_cache;
688 			} else {
689 				/* Otherwise, we use a non-shared runtime cache */
690 				closure->func.op_array.run_time_cache = emalloc(func->op_array.cache_size);
691 				closure->func.op_array.fn_flags |= ZEND_ACC_NO_RT_ARENA;
692 			}
693 			memset(closure->func.op_array.run_time_cache, 0, func->op_array.cache_size);
694 		}
695 		if (closure->func.op_array.refcount) {
696 			(*closure->func.op_array.refcount)++;
697 		}
698 	} else {
699 		memcpy(&closure->func, func, sizeof(zend_internal_function));
700 		closure->func.common.fn_flags |= ZEND_ACC_CLOSURE;
701 		/* wrap internal function handler to avoid memory leak */
702 		if (UNEXPECTED(closure->func.internal_function.handler == zend_closure_internal_handler)) {
703 			/* avoid infinity recursion, by taking handler from nested closure */
704 			zend_closure *nested = (zend_closure*)((char*)func - XtOffsetOf(zend_closure, func));
705 			ZEND_ASSERT(nested->std.ce == zend_ce_closure);
706 			closure->orig_internal_handler = nested->orig_internal_handler;
707 		} else {
708 			closure->orig_internal_handler = closure->func.internal_function.handler;
709 		}
710 		closure->func.internal_function.handler = zend_closure_internal_handler;
711 		if (!func->common.scope) {
712 			/* if it's a free function, we won't set scope & this since they're meaningless */
713 			this_ptr = NULL;
714 			scope = NULL;
715 		}
716 	}
717 
718 	ZVAL_UNDEF(&closure->this_ptr);
719 	/* Invariant:
720 	 * If the closure is unscoped or static, it has no bound object. */
721 	closure->func.common.scope = scope;
722 	closure->called_scope = called_scope;
723 	if (scope) {
724 		closure->func.common.fn_flags |= ZEND_ACC_PUBLIC;
725 		if (this_ptr && Z_TYPE_P(this_ptr) == IS_OBJECT && (closure->func.common.fn_flags & ZEND_ACC_STATIC) == 0) {
726 			ZVAL_COPY(&closure->this_ptr, this_ptr);
727 		}
728 	}
729 }
730 /* }}} */
731 
zend_create_fake_closure(zval * res,zend_function * func,zend_class_entry * scope,zend_class_entry * called_scope,zval * this_ptr)732 ZEND_API void zend_create_fake_closure(zval *res, zend_function *func, zend_class_entry *scope, zend_class_entry *called_scope, zval *this_ptr) /* {{{ */
733 {
734 	zend_closure *closure;
735 
736 	zend_create_closure(res, func, scope, called_scope, this_ptr);
737 
738 	closure = (zend_closure *)Z_OBJ_P(res);
739 	closure->func.common.fn_flags |= ZEND_ACC_FAKE_CLOSURE;
740 }
741 /* }}} */
742 
zend_closure_bind_var(zval * closure_zv,zend_string * var_name,zval * var)743 void zend_closure_bind_var(zval *closure_zv, zend_string *var_name, zval *var) /* {{{ */
744 {
745 	zend_closure *closure = (zend_closure *) Z_OBJ_P(closure_zv);
746 	HashTable *static_variables = closure->func.op_array.static_variables;
747 	zend_hash_update(static_variables, var_name, var);
748 }
749 /* }}} */
750 
zend_closure_bind_var_ex(zval * closure_zv,uint32_t offset,zval * val)751 void zend_closure_bind_var_ex(zval *closure_zv, uint32_t offset, zval *val) /* {{{ */
752 {
753 	zend_closure *closure = (zend_closure *) Z_OBJ_P(closure_zv);
754 	HashTable *static_variables = closure->func.op_array.static_variables;
755 	zval *var = (zval*)((char*)static_variables->arData + offset);
756 	zval_ptr_dtor(var);
757 	ZVAL_COPY_VALUE(var, val);
758 }
759 /* }}} */
760 
761 /*
762  * Local variables:
763  * tab-width: 4
764  * c-basic-offset: 4
765  * indent-tabs-mode: t
766  * End:
767  * vim600: sw=4 ts=4 fdm=marker
768  * vim<600: sw=4 ts=4
769  */
770