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