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