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