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