xref: /PHP-8.4/Zend/zend_closures.c (revision 8720063c)
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 #include "zend_closures_arginfo.h"
30 
31 typedef struct _zend_closure {
32 	zend_object       std;
33 	zend_function     func;
34 	zval              this_ptr;
35 	zend_class_entry *called_scope;
36 	zif_handler       orig_internal_handler;
37 } zend_closure;
38 
39 /* non-static since it needs to be referenced */
40 ZEND_API zend_class_entry *zend_ce_closure;
41 static zend_object_handlers closure_handlers;
42 
ZEND_METHOD(Closure,__invoke)43 ZEND_METHOD(Closure, __invoke) /* {{{ */
44 {
45 	zend_function *func = EX(func);
46 	zval *args;
47 	uint32_t num_args;
48 	HashTable *named_args;
49 
50 	ZEND_PARSE_PARAMETERS_START(0, -1)
51 		Z_PARAM_VARIADIC_WITH_NAMED(args, num_args, named_args)
52 	ZEND_PARSE_PARAMETERS_END();
53 
54 	if (call_user_function_named(CG(function_table), NULL, ZEND_THIS, return_value, num_args, args, named_args) == FAILURE) {
55 		RETVAL_FALSE;
56 	}
57 
58 	/* destruct the function also, then - we have allocated it in get_method */
59 	zend_string_release_ex(func->internal_function.function_name, 0);
60 	efree(func);
61 
62 	/* Set the func pointer to NULL. Prior to PHP 8.3, this was only done for debug builds,
63 	 * because debug builds check certain properties after the call and needed to know this
64 	 * had been freed.
65 	 * However, extensions can proxy zend_execute_internal, and it's a bit surprising to have
66 	 * an invalid func pointer sitting on there, so this was changed in PHP 8.3.
67 	 */
68 	execute_data->func = NULL;
69 }
70 /* }}} */
71 
zend_valid_closure_binding(zend_closure * closure,zval * newthis,zend_class_entry * scope)72 static bool zend_valid_closure_binding(
73 		zend_closure *closure, zval *newthis, zend_class_entry *scope) /* {{{ */
74 {
75 	zend_function *func = &closure->func;
76 	bool is_fake_closure = (func->common.fn_flags & ZEND_ACC_FAKE_CLOSURE) != 0;
77 	if (newthis) {
78 		if (func->common.fn_flags & ZEND_ACC_STATIC) {
79 			zend_error(E_WARNING, "Cannot bind an instance to a static closure");
80 			return 0;
81 		}
82 
83 		if (is_fake_closure && func->common.scope &&
84 				!instanceof_function(Z_OBJCE_P(newthis), func->common.scope)) {
85 			/* Binding incompatible $this to an internal method is not supported. */
86 			zend_error(E_WARNING, "Cannot bind method %s::%s() to object of class %s",
87 					ZSTR_VAL(func->common.scope->name),
88 					ZSTR_VAL(func->common.function_name),
89 					ZSTR_VAL(Z_OBJCE_P(newthis)->name));
90 			return 0;
91 		}
92 	} else if (is_fake_closure && func->common.scope
93 			&& !(func->common.fn_flags & ZEND_ACC_STATIC)) {
94 		zend_error(E_WARNING, "Cannot unbind $this of method");
95 		return 0;
96 	} else if (!is_fake_closure && !Z_ISUNDEF(closure->this_ptr)
97 			&& (func->common.fn_flags & ZEND_ACC_USES_THIS)) {
98 		zend_error(E_WARNING, "Cannot unbind $this of closure using $this");
99 		return 0;
100 	}
101 
102 	if (scope && scope != func->common.scope && scope->type == ZEND_INTERNAL_CLASS) {
103 		/* rebinding to internal class is not allowed */
104 		zend_error(E_WARNING, "Cannot bind closure to scope of internal class %s",
105 				ZSTR_VAL(scope->name));
106 		return 0;
107 	}
108 
109 	if (is_fake_closure && scope != func->common.scope) {
110 		if (func->common.scope == NULL) {
111 			zend_error(E_WARNING, "Cannot rebind scope of closure created from function");
112 		} else {
113 			zend_error(E_WARNING, "Cannot rebind scope of closure created from method");
114 		}
115 		return 0;
116 	}
117 
118 	return 1;
119 }
120 /* }}} */
121 
122 /* {{{ Call closure, binding to a given object with its class as the scope */
ZEND_METHOD(Closure,call)123 ZEND_METHOD(Closure, call)
124 {
125 	zval *newthis, closure_result;
126 	zend_closure *closure;
127 	zend_fcall_info fci;
128 	zend_fcall_info_cache fci_cache;
129 	zend_object *newobj;
130 	zend_class_entry *newclass;
131 
132 	fci.param_count = 0;
133 	fci.params = NULL;
134 
135 	ZEND_PARSE_PARAMETERS_START(1, -1)
136 		Z_PARAM_OBJECT(newthis)
137 		Z_PARAM_VARIADIC_WITH_NAMED(fci.params, fci.param_count, fci.named_params)
138 	ZEND_PARSE_PARAMETERS_END();
139 
140 	closure = (zend_closure *) Z_OBJ_P(ZEND_THIS);
141 
142 	newobj = Z_OBJ_P(newthis);
143 	newclass = newobj->ce;
144 
145 	if (!zend_valid_closure_binding(closure, newthis, newclass)) {
146 		return;
147 	}
148 
149 	fci_cache.called_scope = newclass;
150 	fci_cache.object = fci.object = newobj;
151 
152 	fci.size = sizeof(fci);
153 	ZVAL_OBJ(&fci.function_name, &closure->std);
154 	ZVAL_UNDEF(&closure_result);
155 	fci.retval = &closure_result;
156 
157 	if (closure->func.common.fn_flags & ZEND_ACC_GENERATOR) {
158 		zval new_closure;
159 		zend_create_closure(&new_closure, &closure->func, newclass, closure->called_scope, newthis);
160 		closure = (zend_closure *) Z_OBJ(new_closure);
161 		fci_cache.function_handler = &closure->func;
162 
163 		zend_call_function(&fci, &fci_cache);
164 
165 		/* copied upon generator creation */
166 		GC_DELREF(&closure->std);
167 	} else {
168 		zend_closure *fake_closure;
169 		zend_function *my_function;
170 
171 		fake_closure = emalloc(sizeof(zend_closure));
172 		memset(&fake_closure->std, 0, sizeof(fake_closure->std));
173 		fake_closure->std.gc.refcount = 1;
174 		fake_closure->std.gc.u.type_info = GC_NULL;
175 		ZVAL_UNDEF(&fake_closure->this_ptr);
176 		fake_closure->called_scope = NULL;
177 		my_function = &fake_closure->func;
178 		if (ZEND_USER_CODE(closure->func.type)) {
179 			memcpy(my_function, &closure->func, sizeof(zend_op_array));
180 		} else {
181 			memcpy(my_function, &closure->func, sizeof(zend_internal_function));
182 		}
183 		/* use scope of passed object */
184 		my_function->common.scope = newclass;
185 		if (closure->func.type == ZEND_INTERNAL_FUNCTION) {
186 			my_function->internal_function.handler = closure->orig_internal_handler;
187 		}
188 		fci_cache.function_handler = my_function;
189 
190 		/* Runtime cache relies on bound scope to be immutable, hence we need a separate rt cache in case scope changed */
191 		if (ZEND_USER_CODE(my_function->type)
192 		 && (closure->func.common.scope != newclass
193 		  || (closure->func.common.fn_flags & ZEND_ACC_HEAP_RT_CACHE))) {
194 			void *ptr;
195 
196 			my_function->op_array.fn_flags |= ZEND_ACC_HEAP_RT_CACHE;
197 			ptr = emalloc(my_function->op_array.cache_size);
198 			ZEND_MAP_PTR_INIT(my_function->op_array.run_time_cache, ptr);
199 			memset(ptr, 0, my_function->op_array.cache_size);
200 		}
201 
202 		zend_call_function(&fci, &fci_cache);
203 
204 		if (ZEND_USER_CODE(my_function->type)) {
205 			if (fci_cache.function_handler->common.fn_flags & ZEND_ACC_HEAP_RT_CACHE) {
206 				efree(ZEND_MAP_PTR(my_function->op_array.run_time_cache));
207 			}
208 		}
209 		efree_size(fake_closure, sizeof(zend_closure));
210 	}
211 
212 	if (Z_TYPE(closure_result) != IS_UNDEF) {
213 		if (Z_ISREF(closure_result)) {
214 			zend_unwrap_reference(&closure_result);
215 		}
216 		ZVAL_COPY_VALUE(return_value, &closure_result);
217 	}
218 }
219 /* }}} */
220 
do_closure_bind(zval * return_value,zval * zclosure,zval * newthis,zend_object * scope_obj,zend_string * scope_str)221 static void do_closure_bind(zval *return_value, zval *zclosure, zval *newthis, zend_object *scope_obj, zend_string *scope_str)
222 {
223 	zend_class_entry *ce, *called_scope;
224 	zend_closure *closure = (zend_closure *) Z_OBJ_P(zclosure);
225 
226 	if (scope_obj) {
227 		ce = scope_obj->ce;
228 	} else if (scope_str) {
229 		if (zend_string_equals(scope_str, ZSTR_KNOWN(ZEND_STR_STATIC))) {
230 			ce = closure->func.common.scope;
231 		} else if ((ce = zend_lookup_class(scope_str)) == NULL) {
232 			zend_error(E_WARNING, "Class \"%s\" not found", ZSTR_VAL(scope_str));
233 			RETURN_NULL();
234 		}
235 	} else {
236 		ce = NULL;
237 	}
238 
239 	if (!zend_valid_closure_binding(closure, newthis, ce)) {
240 		return;
241 	}
242 
243 	if (newthis) {
244 		called_scope = Z_OBJCE_P(newthis);
245 	} else {
246 		called_scope = ce;
247 	}
248 
249 	zend_create_closure(return_value, &closure->func, ce, called_scope, newthis);
250 }
251 
252 /* {{{ Create a closure from another one and bind to another object and scope */
ZEND_METHOD(Closure,bind)253 ZEND_METHOD(Closure, bind)
254 {
255 	zval *zclosure, *newthis;
256 	zend_object *scope_obj = NULL;
257 	zend_string *scope_str = ZSTR_KNOWN(ZEND_STR_STATIC);
258 
259 	ZEND_PARSE_PARAMETERS_START(2, 3)
260 		Z_PARAM_OBJECT_OF_CLASS(zclosure, zend_ce_closure)
261 		Z_PARAM_OBJECT_OR_NULL(newthis)
262 		Z_PARAM_OPTIONAL
263 		Z_PARAM_OBJ_OR_STR_OR_NULL(scope_obj, scope_str)
264 	ZEND_PARSE_PARAMETERS_END();
265 
266 	do_closure_bind(return_value, zclosure, newthis, scope_obj, scope_str);
267 }
268 
269 /* {{{ Create a closure from another one and bind to another object and scope */
ZEND_METHOD(Closure,bindTo)270 ZEND_METHOD(Closure, bindTo)
271 {
272 	zval *newthis;
273 	zend_object *scope_obj = NULL;
274 	zend_string *scope_str = ZSTR_KNOWN(ZEND_STR_STATIC);
275 
276 	ZEND_PARSE_PARAMETERS_START(1, 2)
277 		Z_PARAM_OBJECT_OR_NULL(newthis)
278 		Z_PARAM_OPTIONAL
279 		Z_PARAM_OBJ_OR_STR_OR_NULL(scope_obj, scope_str)
280 	ZEND_PARSE_PARAMETERS_END();
281 
282 	do_closure_bind(return_value, ZEND_THIS, newthis, scope_obj, scope_str);
283 }
284 
ZEND_NAMED_FUNCTION(zend_closure_call_magic)285 static ZEND_NAMED_FUNCTION(zend_closure_call_magic) /* {{{ */ {
286 	zend_fcall_info fci;
287 	zend_fcall_info_cache fcc;
288 	zval params[2];
289 
290 	memset(&fci, 0, sizeof(zend_fcall_info));
291 	memset(&fcc, 0, sizeof(zend_fcall_info_cache));
292 
293 	fci.size = sizeof(zend_fcall_info);
294 	fci.retval = return_value;
295 
296 	fcc.function_handler = (EX(func)->internal_function.fn_flags & ZEND_ACC_STATIC) ?
297 		EX(func)->internal_function.scope->__callstatic : EX(func)->internal_function.scope->__call;
298 	fci.named_params = NULL;
299 	fci.params = params;
300 	fci.param_count = 2;
301 	ZVAL_STR(&fci.params[0], EX(func)->common.function_name);
302 	if (EX_CALL_INFO() & ZEND_CALL_HAS_EXTRA_NAMED_PARAMS) {
303 		zend_string *name;
304 		zval *named_param_zval;
305 		array_init_size(&fci.params[1], ZEND_NUM_ARGS() + zend_hash_num_elements(EX(extra_named_params)));
306 		/* Avoid conversion from packed to mixed later. */
307 		zend_hash_real_init_mixed(Z_ARRVAL(fci.params[1]));
308 		zend_copy_parameters_array(ZEND_NUM_ARGS(), &fci.params[1]);
309 		ZEND_HASH_MAP_FOREACH_STR_KEY_VAL(EX(extra_named_params), name, named_param_zval) {
310 			Z_TRY_ADDREF_P(named_param_zval);
311 			zend_hash_add_new(Z_ARRVAL(fci.params[1]), name, named_param_zval);
312 		} ZEND_HASH_FOREACH_END();
313 	} else if (ZEND_NUM_ARGS()) {
314 		array_init_size(&fci.params[1], ZEND_NUM_ARGS());
315 		zend_copy_parameters_array(ZEND_NUM_ARGS(), &fci.params[1]);
316 	} else {
317 		ZVAL_EMPTY_ARRAY(&fci.params[1]);
318 	}
319 
320 	fcc.object = fci.object = Z_OBJ_P(ZEND_THIS);
321 	fcc.called_scope = zend_get_called_scope(EG(current_execute_data));
322 
323 	zend_call_function(&fci, &fcc);
324 
325 	zval_ptr_dtor(&fci.params[1]);
326 }
327 /* }}} */
328 
zend_create_closure_from_callable(zval * return_value,zval * callable,char ** error)329 static zend_result zend_create_closure_from_callable(zval *return_value, zval *callable, char **error) /* {{{ */ {
330 	zend_fcall_info_cache fcc;
331 	zend_function *mptr;
332 	zval instance;
333 	zend_internal_function call;
334 
335 	if (!zend_is_callable_ex(callable, NULL, 0, NULL, &fcc, error)) {
336 		return FAILURE;
337 	}
338 
339 	mptr = fcc.function_handler;
340 	if (mptr->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) {
341 		/* For Closure::fromCallable([$closure, "__invoke"]) return $closure. */
342 		if (fcc.object && fcc.object->ce == zend_ce_closure
343 				&& zend_string_equals(mptr->common.function_name, ZSTR_KNOWN(ZEND_STR_MAGIC_INVOKE))) {
344 			RETVAL_OBJ_COPY(fcc.object);
345 			zend_free_trampoline(mptr);
346 			return SUCCESS;
347 		}
348 
349 		if (!mptr->common.scope) {
350 			return FAILURE;
351 		}
352 		if (mptr->common.fn_flags & ZEND_ACC_STATIC) {
353 			if (!mptr->common.scope->__callstatic) {
354 				return FAILURE;
355 			}
356 		} else {
357 			if (!mptr->common.scope->__call) {
358 				return FAILURE;
359 			}
360 		}
361 
362 		memset(&call, 0, sizeof(zend_internal_function));
363 		call.type = ZEND_INTERNAL_FUNCTION;
364 		call.fn_flags = mptr->common.fn_flags & ZEND_ACC_STATIC;
365 		call.handler = zend_closure_call_magic;
366 		call.function_name = mptr->common.function_name;
367 		call.scope = mptr->common.scope;
368 		call.doc_comment = NULL;
369 
370 		zend_free_trampoline(mptr);
371 		mptr = (zend_function *) &call;
372 	}
373 
374 	if (fcc.object) {
375 		ZVAL_OBJ(&instance, fcc.object);
376 		zend_create_fake_closure(return_value, mptr, mptr->common.scope, fcc.called_scope, &instance);
377 	} else {
378 		zend_create_fake_closure(return_value, mptr, mptr->common.scope, fcc.called_scope, NULL);
379 	}
380 
381 	if (&mptr->internal_function == &call) {
382 		zend_string_release(mptr->common.function_name);
383 	}
384 
385 	return SUCCESS;
386 }
387 /* }}} */
388 
389 /* {{{ Create a closure from a callable using the current scope. */
ZEND_METHOD(Closure,fromCallable)390 ZEND_METHOD(Closure, fromCallable)
391 {
392 	zval *callable;
393 	char *error = NULL;
394 
395 	ZEND_PARSE_PARAMETERS_START(1, 1)
396 		Z_PARAM_ZVAL(callable)
397 	ZEND_PARSE_PARAMETERS_END();
398 
399 	if (Z_TYPE_P(callable) == IS_OBJECT && instanceof_function(Z_OBJCE_P(callable), zend_ce_closure)) {
400 		/* It's already a closure */
401 		RETURN_COPY(callable);
402 	}
403 
404 	if (zend_create_closure_from_callable(return_value, callable, &error) == FAILURE) {
405 		if (error) {
406 			zend_type_error("Failed to create closure from callable: %s", error);
407 			efree(error);
408 		} else {
409 			zend_type_error("Failed to create closure from callable");
410 		}
411 	}
412 }
413 /* }}} */
414 
zend_closure_get_constructor(zend_object * object)415 static ZEND_COLD zend_function *zend_closure_get_constructor(zend_object *object) /* {{{ */
416 {
417 	zend_throw_error(NULL, "Instantiation of class Closure is not allowed");
418 	return NULL;
419 }
420 /* }}} */
421 
422 /* int return due to Object Handler API */
zend_closure_compare(zval * o1,zval * o2)423 static int zend_closure_compare(zval *o1, zval *o2) /* {{{ */
424 {
425 	ZEND_COMPARE_OBJECTS_FALLBACK(o1, o2);
426 
427 	zend_closure *lhs = (zend_closure*) Z_OBJ_P(o1);
428 	zend_closure *rhs = (zend_closure*) Z_OBJ_P(o2);
429 
430 	if (!((lhs->func.common.fn_flags & ZEND_ACC_FAKE_CLOSURE) && (rhs->func.common.fn_flags & ZEND_ACC_FAKE_CLOSURE))) {
431 		return ZEND_UNCOMPARABLE;
432 	}
433 
434 	if (Z_TYPE(lhs->this_ptr) != Z_TYPE(rhs->this_ptr)) {
435 		return ZEND_UNCOMPARABLE;
436 	}
437 
438 	if (Z_TYPE(lhs->this_ptr) == IS_OBJECT && Z_OBJ(lhs->this_ptr) != Z_OBJ(rhs->this_ptr)) {
439 		return ZEND_UNCOMPARABLE;
440 	}
441 
442 	if (lhs->called_scope != rhs->called_scope) {
443 		return ZEND_UNCOMPARABLE;
444 	}
445 
446 	if (lhs->func.type != rhs->func.type) {
447 		return ZEND_UNCOMPARABLE;
448 	}
449 
450 	if (lhs->func.common.scope != rhs->func.common.scope) {
451 		return ZEND_UNCOMPARABLE;
452 	}
453 
454 	if (!zend_string_equals(lhs->func.common.function_name, rhs->func.common.function_name)) {
455 		return ZEND_UNCOMPARABLE;
456 	}
457 
458 	return 0;
459 }
460 /* }}} */
461 
zend_get_closure_invoke_method(zend_object * object)462 ZEND_API zend_function *zend_get_closure_invoke_method(zend_object *object) /* {{{ */
463 {
464 	zend_closure *closure = (zend_closure *)object;
465 	zend_function *invoke = (zend_function*)emalloc(sizeof(zend_function));
466 	const uint32_t keep_flags =
467 		ZEND_ACC_RETURN_REFERENCE | ZEND_ACC_VARIADIC | ZEND_ACC_HAS_RETURN_TYPE;
468 
469 	invoke->common = closure->func.common;
470 	/* We return ZEND_INTERNAL_FUNCTION, but arg_info representation is the
471 	 * same as for ZEND_USER_FUNCTION (uses zend_string* instead of char*).
472 	 * This is not a problem, because ZEND_ACC_HAS_TYPE_HINTS is never set,
473 	 * and we won't check arguments on internal function. We also set
474 	 * ZEND_ACC_USER_ARG_INFO flag to prevent invalid usage by Reflection */
475 	invoke->type = ZEND_INTERNAL_FUNCTION;
476 	invoke->internal_function.fn_flags =
477 		ZEND_ACC_PUBLIC | ZEND_ACC_CALL_VIA_HANDLER | (closure->func.common.fn_flags & keep_flags);
478 	if (closure->func.type != ZEND_INTERNAL_FUNCTION || (closure->func.common.fn_flags & ZEND_ACC_USER_ARG_INFO)) {
479 		invoke->internal_function.fn_flags |=
480 			ZEND_ACC_USER_ARG_INFO;
481 	}
482 	invoke->internal_function.handler = ZEND_MN(Closure___invoke);
483 	invoke->internal_function.doc_comment = NULL;
484 	invoke->internal_function.module = 0;
485 	invoke->internal_function.scope = zend_ce_closure;
486 	invoke->internal_function.function_name = ZSTR_KNOWN(ZEND_STR_MAGIC_INVOKE);
487 	return invoke;
488 }
489 /* }}} */
490 
zend_get_closure_method_def(zend_object * obj)491 ZEND_API const zend_function *zend_get_closure_method_def(zend_object *obj) /* {{{ */
492 {
493 	zend_closure *closure = (zend_closure *) obj;
494 	return &closure->func;
495 }
496 /* }}} */
497 
zend_get_closure_this_ptr(zval * obj)498 ZEND_API zval* zend_get_closure_this_ptr(zval *obj) /* {{{ */
499 {
500 	zend_closure *closure = (zend_closure *)Z_OBJ_P(obj);
501 	return &closure->this_ptr;
502 }
503 /* }}} */
504 
zend_closure_get_method(zend_object ** object,zend_string * method,const zval * key)505 static zend_function *zend_closure_get_method(zend_object **object, zend_string *method, const zval *key) /* {{{ */
506 {
507 	if (zend_string_equals_literal_ci(method, ZEND_INVOKE_FUNC_NAME)) {
508 		return zend_get_closure_invoke_method(*object);
509 	}
510 
511 	return zend_std_get_method(object, method, key);
512 }
513 /* }}} */
514 
zend_closure_free_storage(zend_object * object)515 static void zend_closure_free_storage(zend_object *object) /* {{{ */
516 {
517 	zend_closure *closure = (zend_closure *)object;
518 
519 	zend_object_std_dtor(&closure->std);
520 
521 	if (closure->func.type == ZEND_USER_FUNCTION) {
522 		/* We don't own the static variables of fake closures. */
523 		if (!(closure->func.op_array.fn_flags & ZEND_ACC_FAKE_CLOSURE)) {
524 			zend_destroy_static_vars(&closure->func.op_array);
525 			closure->func.op_array.static_variables = NULL;
526 		}
527 		destroy_op_array(&closure->func.op_array);
528 	} else if (closure->func.type == ZEND_INTERNAL_FUNCTION) {
529 		zend_string_release(closure->func.common.function_name);
530 	}
531 
532 	if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
533 		zval_ptr_dtor(&closure->this_ptr);
534 	}
535 }
536 /* }}} */
537 
zend_closure_new(zend_class_entry * class_type)538 static zend_object *zend_closure_new(zend_class_entry *class_type) /* {{{ */
539 {
540 	zend_closure *closure;
541 
542 	closure = emalloc(sizeof(zend_closure));
543 	memset(closure, 0, sizeof(zend_closure));
544 
545 	zend_object_std_init(&closure->std, class_type);
546 
547 	return (zend_object*)closure;
548 }
549 /* }}} */
550 
zend_closure_clone(zend_object * zobject)551 static zend_object *zend_closure_clone(zend_object *zobject) /* {{{ */
552 {
553 	zend_closure *closure = (zend_closure *)zobject;
554 	zval result;
555 
556 	zend_create_closure(&result, &closure->func,
557 		closure->func.common.scope, closure->called_scope, &closure->this_ptr);
558 	return Z_OBJ(result);
559 }
560 /* }}} */
561 
zend_closure_get_closure(zend_object * obj,zend_class_entry ** ce_ptr,zend_function ** fptr_ptr,zend_object ** obj_ptr,bool check_only)562 static zend_result zend_closure_get_closure(zend_object *obj, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zend_object **obj_ptr, bool check_only) /* {{{ */
563 {
564 	zend_closure *closure = (zend_closure*)obj;
565 
566 	*fptr_ptr = &closure->func;
567 	*ce_ptr = closure->called_scope;
568 
569 	if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
570 		*obj_ptr = Z_OBJ(closure->this_ptr);
571 	} else {
572 		*obj_ptr = NULL;
573 	}
574 
575 	return SUCCESS;
576 }
577 /* }}} */
578 
579 /* *is_temp is int due to Object Handler API */
zend_closure_get_debug_info(zend_object * object,int * is_temp)580 static HashTable *zend_closure_get_debug_info(zend_object *object, int *is_temp) /* {{{ */
581 {
582 	zend_closure *closure = (zend_closure *)object;
583 	zval val;
584 	struct _zend_arg_info *arg_info = closure->func.common.arg_info;
585 	HashTable *debug_info;
586 	bool zstr_args = (closure->func.type == ZEND_USER_FUNCTION) || (closure->func.common.fn_flags & ZEND_ACC_USER_ARG_INFO);
587 
588 	*is_temp = 1;
589 
590 	debug_info = zend_new_array(8);
591 
592 	if (closure->func.op_array.fn_flags & ZEND_ACC_FAKE_CLOSURE) {
593 		if (closure->func.common.scope) {
594 			zend_string *class_name = closure->func.common.scope->name;
595 			zend_string *func_name = closure->func.common.function_name;
596 			zend_string *combined = zend_string_concat3(
597 				ZSTR_VAL(class_name), ZSTR_LEN(class_name),
598 				"::", strlen("::"),
599 				ZSTR_VAL(func_name), ZSTR_LEN(func_name)
600 			);
601 			ZVAL_STR(&val, combined);
602 		} else {
603 			ZVAL_STR_COPY(&val, closure->func.common.function_name);
604 		}
605 		zend_hash_update(debug_info, ZSTR_KNOWN(ZEND_STR_FUNCTION), &val);
606 	} else {
607 		ZVAL_STR_COPY(&val, closure->func.common.function_name);
608 		zend_hash_update(debug_info, ZSTR_KNOWN(ZEND_STR_NAME), &val);
609 
610 		ZVAL_STR_COPY(&val, closure->func.op_array.filename);
611 		zend_hash_update(debug_info, ZSTR_KNOWN(ZEND_STR_FILE), &val);
612 
613 		ZVAL_LONG(&val, closure->func.op_array.line_start);
614 		zend_hash_update(debug_info, ZSTR_KNOWN(ZEND_STR_LINE), &val);
615 	}
616 
617 	if (closure->func.type == ZEND_USER_FUNCTION && closure->func.op_array.static_variables) {
618 		zval *var;
619 		zend_string *key;
620 		HashTable *static_variables = ZEND_MAP_PTR_GET(closure->func.op_array.static_variables_ptr);
621 
622 		array_init(&val);
623 
624 		ZEND_HASH_MAP_FOREACH_STR_KEY_VAL(static_variables, key, var) {
625 			zval copy;
626 
627 			if (Z_ISREF_P(var) && Z_REFCOUNT_P(var) == 1) {
628 				var = Z_REFVAL_P(var);
629 			}
630 			ZVAL_COPY(&copy, var);
631 
632 			zend_hash_add_new(Z_ARRVAL(val), key, &copy);
633 		} ZEND_HASH_FOREACH_END();
634 
635 		if (zend_hash_num_elements(Z_ARRVAL(val))) {
636 			zend_hash_update(debug_info, ZSTR_KNOWN(ZEND_STR_STATIC), &val);
637 		} else {
638 			zval_ptr_dtor(&val);
639 		}
640 	}
641 
642 	if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
643 		Z_ADDREF(closure->this_ptr);
644 		zend_hash_update(debug_info, ZSTR_KNOWN(ZEND_STR_THIS), &closure->this_ptr);
645 	}
646 
647 	if (arg_info &&
648 		(closure->func.common.num_args ||
649 		 (closure->func.common.fn_flags & ZEND_ACC_VARIADIC))) {
650 		uint32_t i, num_args, required = closure->func.common.required_num_args;
651 
652 		array_init(&val);
653 
654 		num_args = closure->func.common.num_args;
655 		if (closure->func.common.fn_flags & ZEND_ACC_VARIADIC) {
656 			num_args++;
657 		}
658 		for (i = 0; i < num_args; i++) {
659 			zend_string *name;
660 			zval info;
661 			ZEND_ASSERT(arg_info->name && "Argument should have name");
662 			if (zstr_args) {
663 				name = zend_strpprintf(0, "%s$%s",
664 						ZEND_ARG_SEND_MODE(arg_info) ? "&" : "",
665 						ZSTR_VAL(arg_info->name));
666 			} else {
667 				name = zend_strpprintf(0, "%s$%s",
668 						ZEND_ARG_SEND_MODE(arg_info) ? "&" : "",
669 						((zend_internal_arg_info*)arg_info)->name);
670 			}
671 			ZVAL_NEW_STR(&info, zend_strpprintf(0, "%s", i >= required ? "<optional>" : "<required>"));
672 			zend_hash_update(Z_ARRVAL(val), name, &info);
673 			zend_string_release_ex(name, 0);
674 			arg_info++;
675 		}
676 		zend_hash_str_update(debug_info, "parameter", sizeof("parameter")-1, &val);
677 	}
678 
679 	return debug_info;
680 }
681 /* }}} */
682 
zend_closure_get_gc(zend_object * obj,zval ** table,int * n)683 static HashTable *zend_closure_get_gc(zend_object *obj, zval **table, int *n) /* {{{ */
684 {
685 	zend_closure *closure = (zend_closure *)obj;
686 
687 	*table = Z_TYPE(closure->this_ptr) != IS_NULL ? &closure->this_ptr : NULL;
688 	*n = Z_TYPE(closure->this_ptr) != IS_NULL ? 1 : 0;
689 	/* Fake closures don't own the static variables they reference. */
690 	return (closure->func.type == ZEND_USER_FUNCTION
691 			&& !(closure->func.op_array.fn_flags & ZEND_ACC_FAKE_CLOSURE)) ?
692 		ZEND_MAP_PTR_GET(closure->func.op_array.static_variables_ptr) : NULL;
693 }
694 /* }}} */
695 
696 /* {{{ Private constructor preventing instantiation */
ZEND_METHOD(Closure,__construct)697 ZEND_COLD ZEND_METHOD(Closure, __construct)
698 {
699 	zend_throw_error(NULL, "Instantiation of class Closure is not allowed");
700 }
701 /* }}} */
702 
zend_register_closure_ce(void)703 void zend_register_closure_ce(void) /* {{{ */
704 {
705 	zend_ce_closure = register_class_Closure();
706 	zend_ce_closure->create_object = zend_closure_new;
707 	zend_ce_closure->default_object_handlers = &closure_handlers;
708 
709 	memcpy(&closure_handlers, &std_object_handlers, sizeof(zend_object_handlers));
710 	closure_handlers.free_obj = zend_closure_free_storage;
711 	closure_handlers.get_constructor = zend_closure_get_constructor;
712 	closure_handlers.get_method = zend_closure_get_method;
713 	closure_handlers.compare = zend_closure_compare;
714 	closure_handlers.clone_obj = zend_closure_clone;
715 	closure_handlers.get_debug_info = zend_closure_get_debug_info;
716 	closure_handlers.get_closure = zend_closure_get_closure;
717 	closure_handlers.get_gc = zend_closure_get_gc;
718 }
719 /* }}} */
720 
ZEND_NAMED_FUNCTION(zend_closure_internal_handler)721 static ZEND_NAMED_FUNCTION(zend_closure_internal_handler) /* {{{ */
722 {
723 	zend_closure *closure = (zend_closure*)ZEND_CLOSURE_OBJECT(EX(func));
724 	closure->orig_internal_handler(INTERNAL_FUNCTION_PARAM_PASSTHRU);
725 	// Assign to EX(this) so that it is released after observer checks etc.
726 	ZEND_ADD_CALL_FLAG(execute_data, ZEND_CALL_RELEASE_THIS);
727 	Z_OBJ(EX(This)) = &closure->std;
728 }
729 /* }}} */
730 
zend_create_closure_ex(zval * res,zend_function * func,zend_class_entry * scope,zend_class_entry * called_scope,zval * this_ptr,bool is_fake)731 static void zend_create_closure_ex(zval *res, zend_function *func, zend_class_entry *scope, zend_class_entry *called_scope, zval *this_ptr, bool is_fake) /* {{{ */
732 {
733 	zend_closure *closure;
734 	void *ptr;
735 
736 	object_init_ex(res, zend_ce_closure);
737 
738 	closure = (zend_closure *)Z_OBJ_P(res);
739 
740 	if ((scope == NULL) && this_ptr && (Z_TYPE_P(this_ptr) != IS_UNDEF)) {
741 		/* use dummy scope if we're binding an object without specifying a scope */
742 		/* maybe it would be better to create one for this purpose */
743 		scope = zend_ce_closure;
744 	}
745 
746 	if (func->type == ZEND_USER_FUNCTION) {
747 		memcpy(&closure->func, func, sizeof(zend_op_array));
748 		closure->func.common.fn_flags |= ZEND_ACC_CLOSURE;
749 		closure->func.common.fn_flags &= ~ZEND_ACC_IMMUTABLE;
750 
751 		zend_string_addref(closure->func.op_array.function_name);
752 		if (closure->func.op_array.refcount) {
753 			(*closure->func.op_array.refcount)++;
754 		}
755 
756 		/* For fake closures, we want to reuse the static variables of the original function. */
757 		if (!is_fake) {
758 			if (closure->func.op_array.static_variables) {
759 				closure->func.op_array.static_variables =
760 					zend_array_dup(closure->func.op_array.static_variables);
761 			}
762 			ZEND_MAP_PTR_INIT(closure->func.op_array.static_variables_ptr,
763 				closure->func.op_array.static_variables);
764 		} else if (func->op_array.static_variables) {
765 			HashTable *ht = ZEND_MAP_PTR_GET(func->op_array.static_variables_ptr);
766 
767 			if (!ht) {
768 				ht = zend_array_dup(func->op_array.static_variables);
769 				ZEND_MAP_PTR_SET(func->op_array.static_variables_ptr, ht);
770 			}
771 			ZEND_MAP_PTR_INIT(closure->func.op_array.static_variables_ptr, ht);
772 		}
773 
774 		/* Runtime cache is scope-dependent, so we cannot reuse it if the scope changed */
775 		ptr = ZEND_MAP_PTR_GET(func->op_array.run_time_cache);
776 		if (!ptr
777 			|| func->common.scope != scope
778 			|| (func->common.fn_flags & ZEND_ACC_HEAP_RT_CACHE)
779 		) {
780 			if (!ptr
781 			 && (func->common.fn_flags & ZEND_ACC_CLOSURE)
782 			 && (func->common.scope == scope ||
783 			     !(func->common.fn_flags & ZEND_ACC_IMMUTABLE))) {
784 				/* If a real closure is used for the first time, we create a shared runtime cache
785 				 * and remember which scope it is for. */
786 				if (func->common.scope != scope) {
787 					func->common.scope = scope;
788 				}
789 				ptr = zend_arena_alloc(&CG(arena), func->op_array.cache_size);
790 				ZEND_MAP_PTR_SET(func->op_array.run_time_cache, ptr);
791 				closure->func.op_array.fn_flags &= ~ZEND_ACC_HEAP_RT_CACHE;
792 			} else {
793 				/* Otherwise, we use a non-shared runtime cache */
794 				ptr = emalloc(func->op_array.cache_size);
795 				closure->func.op_array.fn_flags |= ZEND_ACC_HEAP_RT_CACHE;
796 			}
797 			memset(ptr, 0, func->op_array.cache_size);
798 		}
799 		ZEND_MAP_PTR_INIT(closure->func.op_array.run_time_cache, ptr);
800 	} else {
801 		memcpy(&closure->func, func, sizeof(zend_internal_function));
802 		closure->func.common.fn_flags |= ZEND_ACC_CLOSURE;
803 		/* wrap internal function handler to avoid memory leak */
804 		if (UNEXPECTED(closure->func.internal_function.handler == zend_closure_internal_handler)) {
805 			/* avoid infinity recursion, by taking handler from nested closure */
806 			zend_closure *nested = (zend_closure*)((char*)func - XtOffsetOf(zend_closure, func));
807 			ZEND_ASSERT(nested->std.ce == zend_ce_closure);
808 			closure->orig_internal_handler = nested->orig_internal_handler;
809 		} else {
810 			closure->orig_internal_handler = closure->func.internal_function.handler;
811 		}
812 		closure->func.internal_function.handler = zend_closure_internal_handler;
813 		zend_string_addref(closure->func.op_array.function_name);
814 		if (!func->common.scope) {
815 			/* if it's a free function, we won't set scope & this since they're meaningless */
816 			this_ptr = NULL;
817 			scope = NULL;
818 		}
819 	}
820 
821 	ZVAL_UNDEF(&closure->this_ptr);
822 	/* Invariant:
823 	 * If the closure is unscoped or static, it has no bound object. */
824 	closure->func.common.scope = scope;
825 	closure->called_scope = called_scope;
826 	if (scope) {
827 		closure->func.common.fn_flags |= ZEND_ACC_PUBLIC;
828 		if (this_ptr && Z_TYPE_P(this_ptr) == IS_OBJECT && (closure->func.common.fn_flags & ZEND_ACC_STATIC) == 0) {
829 			ZVAL_OBJ_COPY(&closure->this_ptr, Z_OBJ_P(this_ptr));
830 		}
831 	}
832 }
833 /* }}} */
834 
zend_create_closure(zval * res,zend_function * func,zend_class_entry * scope,zend_class_entry * called_scope,zval * this_ptr)835 ZEND_API void zend_create_closure(zval *res, zend_function *func, zend_class_entry *scope, zend_class_entry *called_scope, zval *this_ptr)
836 {
837 	zend_create_closure_ex(res, func, scope, called_scope, this_ptr,
838 		/* is_fake */ (func->common.fn_flags & ZEND_ACC_FAKE_CLOSURE) != 0);
839 }
840 
zend_create_fake_closure(zval * res,zend_function * func,zend_class_entry * scope,zend_class_entry * called_scope,zval * this_ptr)841 ZEND_API void zend_create_fake_closure(zval *res, zend_function *func, zend_class_entry *scope, zend_class_entry *called_scope, zval *this_ptr) /* {{{ */
842 {
843 	zend_closure *closure;
844 
845 	zend_create_closure_ex(res, func, scope, called_scope, this_ptr, /* is_fake */ true);
846 
847 	closure = (zend_closure *)Z_OBJ_P(res);
848 	closure->func.common.fn_flags |= ZEND_ACC_FAKE_CLOSURE;
849 }
850 /* }}} */
851 
852 /* __call and __callStatic name the arguments "$arguments" in the docs. */
853 static zend_internal_arg_info trampoline_arg_info[] = {ZEND_ARG_VARIADIC_TYPE_INFO(false, arguments, IS_MIXED, false)};
854 
zend_closure_from_frame(zval * return_value,zend_execute_data * call)855 void zend_closure_from_frame(zval *return_value, zend_execute_data *call) { /* {{{ */
856 	zval instance;
857 	zend_internal_function trampoline;
858 	zend_function *mptr = call->func;
859 
860 	if (ZEND_CALL_INFO(call) & ZEND_CALL_CLOSURE) {
861 		RETURN_OBJ(ZEND_CLOSURE_OBJECT(mptr));
862 	}
863 
864 	if (mptr->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) {
865 		if ((ZEND_CALL_INFO(call) & ZEND_CALL_HAS_THIS) &&
866 			(Z_OBJCE(call->This) == zend_ce_closure)
867 			&& zend_string_equals(mptr->common.function_name, ZSTR_KNOWN(ZEND_STR_MAGIC_INVOKE))) {
868 	        zend_free_trampoline(mptr);
869 	        RETURN_OBJ_COPY(Z_OBJ(call->This));
870 	    }
871 
872 		memset(&trampoline, 0, sizeof(zend_internal_function));
873 		trampoline.type = ZEND_INTERNAL_FUNCTION;
874 		trampoline.fn_flags = mptr->common.fn_flags & (ZEND_ACC_STATIC | ZEND_ACC_VARIADIC | ZEND_ACC_RETURN_REFERENCE);
875 		trampoline.handler = zend_closure_call_magic;
876 		trampoline.function_name = mptr->common.function_name;
877 		trampoline.scope = mptr->common.scope;
878 		trampoline.doc_comment = NULL;
879 		if (trampoline.fn_flags & ZEND_ACC_VARIADIC) {
880 			trampoline.arg_info = trampoline_arg_info;
881 		}
882 
883 		zend_free_trampoline(mptr);
884 		mptr = (zend_function *) &trampoline;
885 	}
886 
887 	if (ZEND_CALL_INFO(call) & ZEND_CALL_HAS_THIS) {
888 		ZVAL_OBJ(&instance, Z_OBJ(call->This));
889 
890 		zend_create_fake_closure(return_value, mptr, mptr->common.scope, Z_OBJCE(instance), &instance);
891 	} else {
892 		zend_create_fake_closure(return_value, mptr, mptr->common.scope, Z_CE(call->This), NULL);
893 	}
894 
895 	if (&mptr->internal_function == &trampoline) {
896 		zend_string_release(mptr->common.function_name);
897 	}
898 } /* }}} */
899 
zend_closure_bind_var(zval * closure_zv,zend_string * var_name,zval * var)900 void zend_closure_bind_var(zval *closure_zv, zend_string *var_name, zval *var) /* {{{ */
901 {
902 	zend_closure *closure = (zend_closure *) Z_OBJ_P(closure_zv);
903 	HashTable *static_variables = ZEND_MAP_PTR_GET(closure->func.op_array.static_variables_ptr);
904 	zend_hash_update(static_variables, var_name, var);
905 }
906 /* }}} */
907 
zend_closure_bind_var_ex(zval * closure_zv,uint32_t offset,zval * val)908 void zend_closure_bind_var_ex(zval *closure_zv, uint32_t offset, zval *val) /* {{{ */
909 {
910 	zend_closure *closure = (zend_closure *) Z_OBJ_P(closure_zv);
911 	HashTable *static_variables = ZEND_MAP_PTR_GET(closure->func.op_array.static_variables_ptr);
912 	zval *var = (zval*)((char*)static_variables->arData + offset);
913 	zval_ptr_dtor(var);
914 	ZVAL_COPY_VALUE(var, val);
915 }
916 /* }}} */
917