xref: /PHP-8.3/ext/ffi/ffi.c (revision c0de7214)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | https://www.php.net/license/3_01.txt                                 |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Author: Dmitry Stogov <dmitry@zend.com>                              |
14    +----------------------------------------------------------------------+
15 */
16 
17 #ifdef HAVE_CONFIG_H
18 # include "config.h"
19 #endif
20 
21 #include "php.h"
22 #include "php_ffi.h"
23 #include "ext/standard/info.h"
24 #include "php_scandir.h"
25 #include "zend_exceptions.h"
26 #include "zend_closures.h"
27 #include "zend_weakrefs.h"
28 #include "main/SAPI.h"
29 #include "zend_observer.h"
30 
31 #include <ffi.h>
32 
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <fcntl.h>
36 
37 #ifdef HAVE_LIBDL
38 #ifdef PHP_WIN32
39 #include "win32/param.h"
40 #include "win32/winutil.h"
41 #define GET_DL_ERROR()  php_win_err()
42 #else
43 #include <sys/param.h>
44 #define GET_DL_ERROR()  DL_ERROR()
45 #endif
46 #endif
47 
48 #ifdef HAVE_GLOB
49 #ifdef PHP_WIN32
50 #include "win32/glob.h"
51 #else
52 #include <glob.h>
53 #endif
54 #endif
55 
56 #ifndef __BIGGEST_ALIGNMENT__
57 /* XXX need something better, perhaps with regard to SIMD, etc. */
58 # define __BIGGEST_ALIGNMENT__ sizeof(size_t)
59 #endif
60 
61 ZEND_DECLARE_MODULE_GLOBALS(ffi)
62 
63 typedef enum _zend_ffi_tag_kind {
64 	ZEND_FFI_TAG_ENUM,
65 	ZEND_FFI_TAG_STRUCT,
66 	ZEND_FFI_TAG_UNION
67 } zend_ffi_tag_kind;
68 
69 static const char *zend_ffi_tag_kind_name[3] = {"enum", "struct", "union"};
70 
71 
72 typedef struct _zend_ffi_tag {
73 	zend_ffi_tag_kind      kind;
74 	zend_ffi_type         *type;
75 } zend_ffi_tag;
76 
77 typedef enum _zend_ffi_type_kind {
78 	ZEND_FFI_TYPE_VOID,
79 	ZEND_FFI_TYPE_FLOAT,
80 	ZEND_FFI_TYPE_DOUBLE,
81 #ifdef HAVE_LONG_DOUBLE
82 	ZEND_FFI_TYPE_LONGDOUBLE,
83 #endif
84 	ZEND_FFI_TYPE_UINT8,
85 	ZEND_FFI_TYPE_SINT8,
86 	ZEND_FFI_TYPE_UINT16,
87 	ZEND_FFI_TYPE_SINT16,
88 	ZEND_FFI_TYPE_UINT32,
89 	ZEND_FFI_TYPE_SINT32,
90 	ZEND_FFI_TYPE_UINT64,
91 	ZEND_FFI_TYPE_SINT64,
92 	ZEND_FFI_TYPE_ENUM,
93 	ZEND_FFI_TYPE_BOOL,
94 	ZEND_FFI_TYPE_CHAR,
95 	ZEND_FFI_TYPE_POINTER,
96 	ZEND_FFI_TYPE_FUNC,
97 	ZEND_FFI_TYPE_ARRAY,
98 	ZEND_FFI_TYPE_STRUCT,
99 } zend_ffi_type_kind;
100 
101 #include "ffi_arginfo.h"
102 
103 typedef enum _zend_ffi_flags {
104 	ZEND_FFI_FLAG_CONST      = (1 << 0),
105 	ZEND_FFI_FLAG_OWNED      = (1 << 1),
106 	ZEND_FFI_FLAG_PERSISTENT = (1 << 2),
107 } zend_ffi_flags;
108 
109 struct _zend_ffi_type {
110 	zend_ffi_type_kind     kind;
111 	size_t                 size;
112 	uint32_t               align;
113 	uint32_t               attr;
114 	union {
115 		struct {
116 			zend_string        *tag_name;
117 			zend_ffi_type_kind  kind;
118 		} enumeration;
119 		struct {
120 			zend_ffi_type *type;
121 			zend_long      length;
122 		} array;
123 		struct {
124 			zend_ffi_type *type;
125 		} pointer;
126 		struct {
127 			zend_string   *tag_name;
128 			HashTable      fields;
129 		} record;
130 		struct {
131 			zend_ffi_type *ret_type;
132 			HashTable     *args;
133 			ffi_abi        abi;
134 		} func;
135 	};
136 };
137 
138 typedef struct _zend_ffi_field {
139 	size_t                 offset;
140 	bool              is_const;
141 	bool              is_nested; /* part of nested anonymous struct */
142 	uint8_t                first_bit;
143 	uint8_t                bits;
144 	zend_ffi_type         *type;
145 } zend_ffi_field;
146 
147 typedef enum _zend_ffi_symbol_kind {
148 	ZEND_FFI_SYM_TYPE,
149 	ZEND_FFI_SYM_CONST,
150 	ZEND_FFI_SYM_VAR,
151 	ZEND_FFI_SYM_FUNC
152 } zend_ffi_symbol_kind;
153 
154 typedef struct _zend_ffi_symbol {
155 	zend_ffi_symbol_kind   kind;
156 	bool              is_const;
157 	zend_ffi_type         *type;
158 	union {
159 		void *addr;
160 		int64_t value;
161 	};
162 } zend_ffi_symbol;
163 
164 typedef struct _zend_ffi_scope {
165 	HashTable             *symbols;
166 	HashTable             *tags;
167 } zend_ffi_scope;
168 
169 typedef struct _zend_ffi {
170 	zend_object            std;
171 	DL_HANDLE              lib;
172 	HashTable             *symbols;
173 	HashTable             *tags;
174 	bool              persistent;
175 } zend_ffi;
176 
177 #define ZEND_FFI_TYPE_OWNED        (1<<0)
178 
179 #define ZEND_FFI_TYPE(t) \
180 	((zend_ffi_type*)(((uintptr_t)(t)) & ~ZEND_FFI_TYPE_OWNED))
181 
182 #define ZEND_FFI_TYPE_IS_OWNED(t) \
183 	(((uintptr_t)(t)) & ZEND_FFI_TYPE_OWNED)
184 
185 #define ZEND_FFI_TYPE_MAKE_OWNED(t) \
186 	((zend_ffi_type*)(((uintptr_t)(t)) | ZEND_FFI_TYPE_OWNED))
187 
188 #define ZEND_FFI_SIZEOF_ARG \
189 	MAX(FFI_SIZEOF_ARG, sizeof(double))
190 
191 typedef struct _zend_ffi_cdata {
192 	zend_object            std;
193 	zend_ffi_type         *type;
194 	void                  *ptr;
195 	void                  *ptr_holder;
196 	zend_ffi_flags         flags;
197 } zend_ffi_cdata;
198 
199 typedef struct _zend_ffi_ctype {
200 	zend_object            std;
201 	zend_ffi_type         *type;
202 } zend_ffi_ctype;
203 
204 static zend_class_entry *zend_ffi_exception_ce;
205 static zend_class_entry *zend_ffi_parser_exception_ce;
206 static zend_class_entry *zend_ffi_ce;
207 static zend_class_entry *zend_ffi_cdata_ce;
208 static zend_class_entry *zend_ffi_ctype_ce;
209 
210 static zend_object_handlers zend_ffi_handlers;
211 static zend_object_handlers zend_ffi_cdata_handlers;
212 static zend_object_handlers zend_ffi_cdata_value_handlers;
213 static zend_object_handlers zend_ffi_cdata_free_handlers;
214 static zend_object_handlers zend_ffi_ctype_handlers;
215 
216 static zend_internal_function zend_ffi_new_fn;
217 static zend_internal_function zend_ffi_cast_fn;
218 static zend_internal_function zend_ffi_type_fn;
219 
220 /* forward declarations */
221 static void _zend_ffi_type_dtor(zend_ffi_type *type);
222 static void zend_ffi_finalize_type(zend_ffi_dcl *dcl);
223 static bool zend_ffi_is_same_type(zend_ffi_type *type1, zend_ffi_type *type2);
224 static zend_ffi_type *zend_ffi_remember_type(zend_ffi_type *type);
225 static char *zend_ffi_parse_directives(const char *filename, char *code_pos, char **scope_name, char **lib, bool preload);
226 static ZEND_FUNCTION(ffi_trampoline);
227 static ZEND_COLD void zend_ffi_return_unsupported(zend_ffi_type *type);
228 static ZEND_COLD void zend_ffi_pass_unsupported(zend_ffi_type *type);
229 static ZEND_COLD void zend_ffi_assign_incompatible(zval *arg, zend_ffi_type *type);
230 static bool zend_ffi_is_compatible_type(zend_ffi_type *dst_type, zend_ffi_type *src_type);
231 
232 #if FFI_CLOSURES
233 static void *zend_ffi_create_callback(zend_ffi_type *type, zval *value);
234 #endif
235 
zend_ffi_type_dtor(zend_ffi_type * type)236 static zend_always_inline void zend_ffi_type_dtor(zend_ffi_type *type) /* {{{ */
237 {
238 	if (UNEXPECTED(ZEND_FFI_TYPE_IS_OWNED(type))) {
239 		_zend_ffi_type_dtor(type);
240 		return;
241 	}
242 }
243 /* }}} */
244 
zend_ffi_object_init(zend_object * object,zend_class_entry * ce)245 static zend_always_inline void zend_ffi_object_init(zend_object *object, zend_class_entry *ce) /* {{{ */
246 {
247 	GC_SET_REFCOUNT(object, 1);
248 	GC_TYPE_INFO(object) = GC_OBJECT | (IS_OBJ_DESTRUCTOR_CALLED << GC_FLAGS_SHIFT);
249 	object->ce = ce;
250 	object->handlers = ce->default_object_handlers;
251 	object->properties = NULL;
252 	zend_objects_store_put(object);
253 }
254 /* }}} */
255 
zend_ffi_cdata_new(zend_class_entry * class_type)256 static zend_object *zend_ffi_cdata_new(zend_class_entry *class_type) /* {{{ */
257 {
258 	zend_ffi_cdata *cdata;
259 
260 	cdata = emalloc(sizeof(zend_ffi_cdata));
261 
262 	zend_ffi_object_init(&cdata->std, class_type);
263 
264 	cdata->type = NULL;
265 	cdata->ptr = NULL;
266 	cdata->flags = 0;
267 
268 	return &cdata->std;
269 }
270 /* }}} */
271 
zend_ffi_func_ptr_are_compatible(zend_ffi_type * dst_type,zend_ffi_type * src_type)272 static bool zend_ffi_func_ptr_are_compatible(zend_ffi_type *dst_type, zend_ffi_type *src_type) /* {{{ */
273 {
274 	uint32_t dst_argc, src_argc, i;
275 	zend_ffi_type *dst_arg, *src_arg;
276 
277 	ZEND_ASSERT(dst_type->kind == ZEND_FFI_TYPE_FUNC);
278 	ZEND_ASSERT(src_type->kind == ZEND_FFI_TYPE_FUNC);
279 
280 	/* Ensure calling convention matches */
281 	if (dst_type->func.abi != src_type->func.abi) {
282 		return 0;
283 	}
284 
285 	/* Ensure variadic attr matches */
286 	if ((dst_type->attr & ZEND_FFI_ATTR_VARIADIC) != (src_type->attr & ZEND_FFI_ATTR_VARIADIC)) {
287 		return 0;
288 	}
289 
290 	/* Ensure same arg count */
291 	dst_argc = dst_type->func.args ? zend_hash_num_elements(dst_type->func.args) : 0;
292 	src_argc = src_type->func.args ? zend_hash_num_elements(src_type->func.args) : 0;
293 	if (dst_argc != src_argc) {
294 		return 0;
295 	}
296 
297 	/* Ensure compatible ret_type */
298 	if (!zend_ffi_is_compatible_type(dst_type->func.ret_type, src_type->func.ret_type)) {
299 		return 0;
300 	}
301 
302 	/* Ensure compatible args */
303 	for (i = 0; i < dst_argc; i++) {
304 		dst_arg = zend_hash_index_find_ptr(dst_type->func.args, i);
305 		src_arg = zend_hash_index_find_ptr(src_type->func.args, i);
306 		if (!zend_ffi_is_compatible_type(ZEND_FFI_TYPE(dst_arg), ZEND_FFI_TYPE(src_arg))) {
307 			return 0;
308 		}
309 	}
310 
311 	return 1;
312 }
313 /* }}} */
314 
zend_ffi_is_compatible_type(zend_ffi_type * dst_type,zend_ffi_type * src_type)315 static bool zend_ffi_is_compatible_type(zend_ffi_type *dst_type, zend_ffi_type *src_type) /* {{{ */
316 {
317 	while (1) {
318 		if (dst_type == src_type) {
319 			return 1;
320 		} else if (dst_type->kind == src_type->kind) {
321 			if (dst_type->kind < ZEND_FFI_TYPE_POINTER) {
322 				return 1;
323 			} else if (dst_type->kind == ZEND_FFI_TYPE_POINTER) {
324 				dst_type = ZEND_FFI_TYPE(dst_type->pointer.type);
325 				src_type = ZEND_FFI_TYPE(src_type->pointer.type);
326 				if (dst_type->kind == ZEND_FFI_TYPE_VOID ||
327 				    src_type->kind == ZEND_FFI_TYPE_VOID) {
328 				    return 1;
329 				} else if (dst_type->kind == ZEND_FFI_TYPE_FUNC &&
330 				           src_type->kind == ZEND_FFI_TYPE_FUNC) {
331 				    return zend_ffi_func_ptr_are_compatible(dst_type, src_type);
332 				}
333 			} else if (dst_type->kind == ZEND_FFI_TYPE_ARRAY &&
334 			           (dst_type->array.length == src_type->array.length ||
335 			            dst_type->array.length == 0)) {
336 				dst_type = ZEND_FFI_TYPE(dst_type->array.type);
337 				src_type = ZEND_FFI_TYPE(src_type->array.type);
338 			} else {
339 				break;
340 			}
341 		} else if (dst_type->kind == ZEND_FFI_TYPE_POINTER &&
342 		           src_type->kind == ZEND_FFI_TYPE_ARRAY) {
343 			dst_type = ZEND_FFI_TYPE(dst_type->pointer.type);
344 			src_type = ZEND_FFI_TYPE(src_type->array.type);
345 			if (dst_type->kind == ZEND_FFI_TYPE_VOID) {
346 			    return 1;
347 			}
348 		} else {
349 			break;
350 		}
351 	}
352 	return 0;
353 }
354 /* }}} */
355 
zend_ffi_face_struct_add_fields(ffi_type * t,zend_ffi_type * type,int * i,size_t size)356 static ffi_type* zend_ffi_face_struct_add_fields(ffi_type* t, zend_ffi_type *type, int *i, size_t size)
357 {
358 	zend_ffi_field *field;
359 
360 	ZEND_HASH_MAP_FOREACH_PTR(&type->record.fields, field) {
361 		switch (ZEND_FFI_TYPE(field->type)->kind) {
362 			case ZEND_FFI_TYPE_FLOAT:
363 				t->elements[(*i)++] = &ffi_type_float;
364 				break;
365 			case ZEND_FFI_TYPE_DOUBLE:
366 				t->elements[(*i)++] = &ffi_type_double;
367 				break;
368 #ifdef HAVE_LONG_DOUBLE
369 			case ZEND_FFI_TYPE_LONGDOUBLE:
370 				t->elements[(*i)++] = &ffi_type_longdouble;
371 				break;
372 #endif
373 			case ZEND_FFI_TYPE_SINT8:
374 			case ZEND_FFI_TYPE_UINT8:
375 			case ZEND_FFI_TYPE_BOOL:
376 			case ZEND_FFI_TYPE_CHAR:
377 				t->elements[(*i)++] = &ffi_type_uint8;
378 				break;
379 			case ZEND_FFI_TYPE_SINT16:
380 			case ZEND_FFI_TYPE_UINT16:
381 				t->elements[(*i)++] = &ffi_type_uint16;
382 				break;
383 			case ZEND_FFI_TYPE_SINT32:
384 			case ZEND_FFI_TYPE_UINT32:
385 				t->elements[(*i)++] = &ffi_type_uint32;
386 				break;
387 			case ZEND_FFI_TYPE_SINT64:
388 			case ZEND_FFI_TYPE_UINT64:
389 				t->elements[(*i)++] = &ffi_type_uint64;
390 				break;
391 			case ZEND_FFI_TYPE_POINTER:
392 				t->elements[(*i)++] = &ffi_type_pointer;
393 				break;
394 			case ZEND_FFI_TYPE_STRUCT: {
395 				zend_ffi_type *field_type = ZEND_FFI_TYPE(field->type);
396 				/* for unions we use only the first field */
397 				uint32_t num_fields = !(field_type->attr & ZEND_FFI_ATTR_UNION) ?
398 					zend_hash_num_elements(&field_type->record.fields) : 1;
399 
400 				if (num_fields > 1) {
401 					size += sizeof(ffi_type*) * (num_fields - 1);
402 					t = erealloc(t, size);
403 					t->elements = (ffi_type**)(t + 1);
404 				}
405 				t = zend_ffi_face_struct_add_fields(t, field_type, i, size);
406 				break;
407 			}
408 			default:
409 				t->elements[(*i)++] = &ffi_type_void;
410 				break;
411 		}
412 		if (type->attr & ZEND_FFI_ATTR_UNION) {
413 			/* for unions we use only the first field */
414 			break;
415 		}
416 	} ZEND_HASH_FOREACH_END();
417 	return t;
418 }
419 
zend_ffi_make_fake_struct_type(zend_ffi_type * type)420 static ffi_type *zend_ffi_make_fake_struct_type(zend_ffi_type *type) /* {{{ */
421 {
422 	/* for unions we use only the first field */
423 	uint32_t num_fields = !(type->attr & ZEND_FFI_ATTR_UNION) ?
424 		zend_hash_num_elements(&type->record.fields) : 1;
425 	size_t size = sizeof(ffi_type) + sizeof(ffi_type*) * (num_fields + 1);
426 	ffi_type *t = emalloc(size);
427 	int i;
428 
429 	t->size = type->size;
430 	t->alignment = type->align;
431 	t->type = FFI_TYPE_STRUCT;
432 	t->elements = (ffi_type**)(t + 1);
433 	i = 0;
434 	t = zend_ffi_face_struct_add_fields(t, type, &i, size);
435 	t->elements[i] = NULL;
436 	return t;
437 }
438 /* }}} */
439 
zend_ffi_get_type(zend_ffi_type * type)440 static ffi_type *zend_ffi_get_type(zend_ffi_type *type) /* {{{ */
441 {
442 	zend_ffi_type_kind kind = type->kind;
443 
444 again:
445 	switch (kind) {
446 		case ZEND_FFI_TYPE_FLOAT:
447 			return &ffi_type_float;
448 		case ZEND_FFI_TYPE_DOUBLE:
449 			return &ffi_type_double;
450 #ifdef HAVE_LONG_DOUBLE
451 		case ZEND_FFI_TYPE_LONGDOUBLE:
452 			return &ffi_type_longdouble;
453 #endif
454 		case ZEND_FFI_TYPE_UINT8:
455 			return &ffi_type_uint8;
456 		case ZEND_FFI_TYPE_SINT8:
457 			return &ffi_type_sint8;
458 		case ZEND_FFI_TYPE_UINT16:
459 			return &ffi_type_uint16;
460 		case ZEND_FFI_TYPE_SINT16:
461 			return &ffi_type_sint16;
462 		case ZEND_FFI_TYPE_UINT32:
463 			return &ffi_type_uint32;
464 		case ZEND_FFI_TYPE_SINT32:
465 			return &ffi_type_sint32;
466 		case ZEND_FFI_TYPE_UINT64:
467 			return &ffi_type_uint64;
468 		case ZEND_FFI_TYPE_SINT64:
469 			return &ffi_type_sint64;
470 		case ZEND_FFI_TYPE_POINTER:
471 			return &ffi_type_pointer;
472 		case ZEND_FFI_TYPE_VOID:
473 			return &ffi_type_void;
474 		case ZEND_FFI_TYPE_BOOL:
475 			return &ffi_type_uint8;
476 		case ZEND_FFI_TYPE_CHAR:
477 			return &ffi_type_sint8;
478 		case ZEND_FFI_TYPE_ENUM:
479 			kind = type->enumeration.kind;
480 			goto again;
481 		case ZEND_FFI_TYPE_STRUCT:
482 			return zend_ffi_make_fake_struct_type(type);
483 		default:
484 			break;
485 	}
486 	return NULL;
487 }
488 /* }}} */
489 
zend_ffi_cdata_to_zval_slow(void * ptr,zend_ffi_type * type,zend_ffi_flags flags)490 static zend_never_inline zend_ffi_cdata *zend_ffi_cdata_to_zval_slow(void *ptr, zend_ffi_type *type, zend_ffi_flags flags) /* {{{ */
491 {
492 	zend_ffi_cdata *cdata = emalloc(sizeof(zend_ffi_cdata));
493 
494 	zend_ffi_object_init(&cdata->std, zend_ffi_cdata_ce);
495 	cdata->std.handlers =
496 		(type->kind < ZEND_FFI_TYPE_POINTER) ?
497 		&zend_ffi_cdata_value_handlers :
498 		&zend_ffi_cdata_handlers;
499 	cdata->type = type;
500 	cdata->flags = flags;
501 	cdata->ptr = ptr;
502 	return cdata;
503 }
504 /* }}} */
505 
zend_ffi_cdata_to_zval_slow_ptr(void * ptr,zend_ffi_type * type,zend_ffi_flags flags)506 static zend_never_inline zend_ffi_cdata *zend_ffi_cdata_to_zval_slow_ptr(void *ptr, zend_ffi_type *type, zend_ffi_flags flags) /* {{{ */
507 {
508 	zend_ffi_cdata *cdata = emalloc(sizeof(zend_ffi_cdata));
509 
510 	zend_ffi_object_init(&cdata->std, zend_ffi_cdata_ce);
511 	cdata->type = type;
512 	cdata->flags = flags;
513 	cdata->ptr = (void*)&cdata->ptr_holder;
514 	*(void**)cdata->ptr = *(void**)ptr;
515 	return cdata;
516 }
517 /* }}} */
518 
zend_ffi_cdata_to_zval_slow_ret(void * ptr,zend_ffi_type * type,zend_ffi_flags flags)519 static zend_never_inline zend_ffi_cdata *zend_ffi_cdata_to_zval_slow_ret(void *ptr, zend_ffi_type *type, zend_ffi_flags flags) /* {{{ */
520 {
521 	zend_ffi_cdata *cdata = emalloc(sizeof(zend_ffi_cdata));
522 
523 	zend_ffi_object_init(&cdata->std, zend_ffi_cdata_ce);
524 	cdata->std.handlers =
525 		(type->kind < ZEND_FFI_TYPE_POINTER) ?
526 		&zend_ffi_cdata_value_handlers :
527 		&zend_ffi_cdata_handlers;
528 	cdata->type = type;
529 	cdata->flags = flags;
530 	if (type->kind == ZEND_FFI_TYPE_POINTER) {
531 		cdata->ptr = (void*)&cdata->ptr_holder;
532 		*(void**)cdata->ptr = *(void**)ptr;
533 	} else if (type->kind == ZEND_FFI_TYPE_STRUCT) {
534 		cdata->ptr = emalloc(type->size);
535 		cdata->flags |= ZEND_FFI_FLAG_OWNED;
536 		memcpy(cdata->ptr, ptr, type->size);
537 	} else {
538 		cdata->ptr = ptr;
539 	}
540 	return cdata;
541 }
542 /* }}} */
543 
zend_ffi_cdata_to_zval(zend_ffi_cdata * cdata,void * ptr,zend_ffi_type * type,int read_type,zval * rv,zend_ffi_flags flags,bool is_ret,bool debug_union)544 static zend_always_inline void zend_ffi_cdata_to_zval(zend_ffi_cdata *cdata, void *ptr, zend_ffi_type *type, int read_type, zval *rv, zend_ffi_flags flags, bool is_ret, bool debug_union) /* {{{ */
545 {
546 	if (read_type == BP_VAR_R) {
547 		zend_ffi_type_kind kind = type->kind;
548 
549 again:
550 	    switch (kind) {
551 			case ZEND_FFI_TYPE_FLOAT:
552 				ZVAL_DOUBLE(rv, *(float*)ptr);
553 				return;
554 			case ZEND_FFI_TYPE_DOUBLE:
555 				ZVAL_DOUBLE(rv, *(double*)ptr);
556 				return;
557 #ifdef HAVE_LONG_DOUBLE
558 			case ZEND_FFI_TYPE_LONGDOUBLE:
559 				ZVAL_DOUBLE(rv, *(long double*)ptr);
560 				return;
561 #endif
562 			case ZEND_FFI_TYPE_UINT8:
563 				ZVAL_LONG(rv, *(uint8_t*)ptr);
564 				return;
565 			case ZEND_FFI_TYPE_SINT8:
566 				ZVAL_LONG(rv, *(int8_t*)ptr);
567 				return;
568 			case ZEND_FFI_TYPE_UINT16:
569 				ZVAL_LONG(rv, *(uint16_t*)ptr);
570 				return;
571 			case ZEND_FFI_TYPE_SINT16:
572 				ZVAL_LONG(rv, *(int16_t*)ptr);
573 				return;
574 			case ZEND_FFI_TYPE_UINT32:
575 				ZVAL_LONG(rv, *(uint32_t*)ptr);
576 				return;
577 			case ZEND_FFI_TYPE_SINT32:
578 				ZVAL_LONG(rv, *(int32_t*)ptr);
579 				return;
580 			case ZEND_FFI_TYPE_UINT64:
581 				ZVAL_LONG(rv, *(uint64_t*)ptr);
582 				return;
583 			case ZEND_FFI_TYPE_SINT64:
584 				ZVAL_LONG(rv, *(int64_t*)ptr);
585 				return;
586 			case ZEND_FFI_TYPE_BOOL:
587 				ZVAL_BOOL(rv, *(uint8_t*)ptr);
588 				return;
589 			case ZEND_FFI_TYPE_CHAR:
590 				ZVAL_CHAR(rv, *(char*)ptr);
591 				return;
592 			case ZEND_FFI_TYPE_ENUM:
593 				kind = type->enumeration.kind;
594 				goto again;
595 			case ZEND_FFI_TYPE_POINTER:
596 				if (*(void**)ptr == NULL) {
597 					ZVAL_NULL(rv);
598 					return;
599 				} else if (debug_union) {
600 					ZVAL_STR(rv, zend_strpprintf(0, "%p", *(void**)ptr));
601 					return;
602 				} else if ((type->attr & ZEND_FFI_ATTR_CONST) && ZEND_FFI_TYPE(type->pointer.type)->kind == ZEND_FFI_TYPE_CHAR) {
603 					ZVAL_STRING(rv, *(char**)ptr);
604 					return;
605 				}
606 				if (!cdata) {
607 					if (is_ret) {
608 						cdata = zend_ffi_cdata_to_zval_slow_ret(ptr, type, flags);
609 					} else {
610 						cdata = zend_ffi_cdata_to_zval_slow_ptr(ptr, type, flags);
611 					}
612 				} else {
613 					GC_ADDREF(&cdata->std);
614 				}
615 				ZVAL_OBJ(rv, &cdata->std);
616 				return;
617 			default:
618 				break;
619 		}
620 	}
621 
622 	if (!cdata) {
623 		if (is_ret) {
624 			cdata = zend_ffi_cdata_to_zval_slow_ret(ptr, type, flags);
625 		} else {
626 			cdata = zend_ffi_cdata_to_zval_slow(ptr, type, flags);
627 		}
628 	} else {
629 		GC_ADDREF(&cdata->std);
630 	}
631 	ZVAL_OBJ(rv, &cdata->std);
632 }
633 /* }}} */
634 
zend_ffi_bit_field_read(void * ptr,zend_ffi_field * field)635 static uint64_t zend_ffi_bit_field_read(void *ptr, zend_ffi_field *field) /* {{{ */
636 {
637 	size_t bit = field->first_bit;
638 	size_t last_bit = bit + field->bits - 1;
639 	uint8_t *p = (uint8_t *) ptr + bit / 8;
640 	uint8_t *last_p = (uint8_t *) ptr + last_bit / 8;
641 	size_t pos = bit % 8;
642 	size_t insert_pos = 0;
643 	uint8_t mask;
644 	uint64_t val = 0;
645 
646 	/* Bitfield fits into a single byte */
647 	if (p == last_p) {
648 		mask = (1U << field->bits) - 1U;
649 		return (*p >> pos) & mask;
650 	}
651 
652 	/* Read partial prefix byte */
653 	if (pos != 0) {
654 		size_t num_bits = 8 - pos;
655 		mask = (1U << num_bits) - 1U;
656 		val = (*p++ >> pos) & mask;
657 		insert_pos += num_bits;
658 	}
659 
660 	/* Read full bytes */
661 	while (p < last_p) {
662 		val |= (uint64_t) *p++ << insert_pos;
663 		insert_pos += 8;
664 	}
665 
666 	/* Read partial suffix byte */
667 	if (p == last_p) {
668 		size_t num_bits = last_bit % 8 + 1;
669 		mask = (1U << num_bits) - 1U;
670 		val |= (uint64_t) (*p & mask) << insert_pos;
671 	}
672 
673 	return val;
674 }
675 /* }}} */
676 
zend_ffi_bit_field_to_zval(void * ptr,zend_ffi_field * field,zval * rv)677 static void zend_ffi_bit_field_to_zval(void *ptr, zend_ffi_field *field, zval *rv) /* {{{ */
678 {
679 	uint64_t val = zend_ffi_bit_field_read(ptr, field);
680 	if (ZEND_FFI_TYPE(field->type)->kind == ZEND_FFI_TYPE_CHAR
681 	 || ZEND_FFI_TYPE(field->type)->kind == ZEND_FFI_TYPE_SINT8
682 	 || ZEND_FFI_TYPE(field->type)->kind == ZEND_FFI_TYPE_SINT16
683 	 || ZEND_FFI_TYPE(field->type)->kind == ZEND_FFI_TYPE_SINT32
684 	 || ZEND_FFI_TYPE(field->type)->kind == ZEND_FFI_TYPE_SINT64) {
685 		/* Sign extend */
686 		uint64_t shift = 64 - (field->bits % 64);
687 		if (shift != 0) {
688 			val = (int64_t)(val << shift) >> shift;
689 		}
690 	}
691 	ZVAL_LONG(rv, val);
692 }
693 /* }}} */
694 
zend_ffi_zval_to_bit_field(void * ptr,zend_ffi_field * field,zval * value)695 static void zend_ffi_zval_to_bit_field(void *ptr, zend_ffi_field *field, zval *value) /* {{{ */
696 {
697 	uint64_t val = zval_get_long(value);
698 	size_t bit = field->first_bit;
699 	size_t last_bit = bit + field->bits - 1;
700 	uint8_t *p = (uint8_t *) ptr + bit / 8;
701 	uint8_t *last_p = (uint8_t *) ptr + last_bit / 8;
702 	size_t pos = bit % 8;
703 	uint8_t mask;
704 
705 	/* Bitfield fits into a single byte */
706 	if (p == last_p) {
707 		mask = ((1U << field->bits) - 1U) << pos;
708 		*p = (*p & ~mask) | ((val << pos) & mask);
709 		return;
710 	}
711 
712 	/* Write partial prefix byte */
713 	if (pos != 0) {
714 		size_t num_bits = 8 - pos;
715 		mask = ((1U << num_bits) - 1U) << pos;
716 		*p = (*p & ~mask) | ((val << pos) & mask);
717 		p++;
718 		val >>= num_bits;
719 	}
720 
721 	/* Write full bytes */
722 	while (p < last_p) {
723 		*p++ = val;
724 		val >>= 8;
725 	}
726 
727 	/* Write partial suffix byte */
728 	if (p == last_p) {
729 		size_t num_bits = last_bit % 8 + 1;
730 		mask = (1U << num_bits) - 1U;
731 		*p = (*p & ~mask) | (val & mask);
732 	}
733 }
734 /* }}} */
735 
zend_ffi_zval_to_cdata(void * ptr,zend_ffi_type * type,zval * value)736 static zend_always_inline zend_result zend_ffi_zval_to_cdata(void *ptr, zend_ffi_type *type, zval *value) /* {{{ */
737 {
738 	zend_long lval;
739 	double dval;
740 	zend_string *tmp_str;
741 	zend_string *str;
742 	zend_ffi_type_kind kind = type->kind;
743 
744 	/* Pointer type has special handling of CData */
745 	if (kind != ZEND_FFI_TYPE_POINTER && Z_TYPE_P(value) == IS_OBJECT && Z_OBJCE_P(value) == zend_ffi_cdata_ce) {
746 		zend_ffi_cdata *cdata = (zend_ffi_cdata*)Z_OBJ_P(value);
747 		if (zend_ffi_is_compatible_type(type, ZEND_FFI_TYPE(cdata->type)) &&
748 			type->size == ZEND_FFI_TYPE(cdata->type)->size) {
749 			memcpy(ptr, cdata->ptr, type->size);
750 			return SUCCESS;
751 		}
752 	}
753 
754 again:
755 	switch (kind) {
756 		case ZEND_FFI_TYPE_FLOAT:
757 			dval = zval_get_double(value);
758 			*(float*)ptr = dval;
759 			break;
760 		case ZEND_FFI_TYPE_DOUBLE:
761 			dval = zval_get_double(value);
762 			*(double*)ptr = dval;
763 			break;
764 #ifdef HAVE_LONG_DOUBLE
765 		case ZEND_FFI_TYPE_LONGDOUBLE:
766 			dval = zval_get_double(value);
767 			*(long double*)ptr = dval;
768 			break;
769 #endif
770 		case ZEND_FFI_TYPE_UINT8:
771 			lval = zval_get_long(value);
772 			*(uint8_t*)ptr = lval;
773 			break;
774 		case ZEND_FFI_TYPE_SINT8:
775 			lval = zval_get_long(value);
776 			*(int8_t*)ptr = lval;
777 			break;
778 		case ZEND_FFI_TYPE_UINT16:
779 			lval = zval_get_long(value);
780 			*(uint16_t*)ptr = lval;
781 			break;
782 		case ZEND_FFI_TYPE_SINT16:
783 			lval = zval_get_long(value);
784 			*(int16_t*)ptr = lval;
785 			break;
786 		case ZEND_FFI_TYPE_UINT32:
787 			lval = zval_get_long(value);
788 			*(uint32_t*)ptr = lval;
789 			break;
790 		case ZEND_FFI_TYPE_SINT32:
791 			lval = zval_get_long(value);
792 			*(int32_t*)ptr = lval;
793 			break;
794 		case ZEND_FFI_TYPE_UINT64:
795 			lval = zval_get_long(value);
796 			*(uint64_t*)ptr = lval;
797 			break;
798 		case ZEND_FFI_TYPE_SINT64:
799 			lval = zval_get_long(value);
800 			*(int64_t*)ptr = lval;
801 			break;
802 		case ZEND_FFI_TYPE_BOOL:
803 			*(uint8_t*)ptr = zend_is_true(value);
804 			break;
805 		case ZEND_FFI_TYPE_CHAR:
806 			str = zval_get_tmp_string(value, &tmp_str);
807 			if (ZSTR_LEN(str) == 1) {
808 				*(char*)ptr = ZSTR_VAL(str)[0];
809 			} else {
810 				zend_ffi_assign_incompatible(value, type);
811 				return FAILURE;
812 			}
813 			zend_tmp_string_release(tmp_str);
814 			break;
815 		case ZEND_FFI_TYPE_ENUM:
816 			kind = type->enumeration.kind;
817 			goto again;
818 		case ZEND_FFI_TYPE_POINTER:
819 			if (Z_TYPE_P(value) == IS_NULL) {
820 				*(void**)ptr = NULL;
821 				break;
822 			} else if (Z_TYPE_P(value) == IS_OBJECT && Z_OBJCE_P(value) == zend_ffi_cdata_ce) {
823 				zend_ffi_cdata *cdata = (zend_ffi_cdata*)Z_OBJ_P(value);
824 
825 				if (zend_ffi_is_compatible_type(type, ZEND_FFI_TYPE(cdata->type))) {
826 					if (ZEND_FFI_TYPE(cdata->type)->kind == ZEND_FFI_TYPE_POINTER) {
827 						*(void**)ptr = *(void**)cdata->ptr;
828 					} else {
829 						if (cdata->flags & ZEND_FFI_FLAG_OWNED) {
830 							zend_throw_error(zend_ffi_exception_ce, "Attempt to perform assign of owned C pointer");
831 							return FAILURE;
832 						}
833 						*(void**)ptr = cdata->ptr;
834 					}
835 					return SUCCESS;
836 				/* Allow transparent assignment of not-owned CData to compatible pointers */
837 				} else if (ZEND_FFI_TYPE(cdata->type)->kind != ZEND_FFI_TYPE_POINTER
838 				 && zend_ffi_is_compatible_type(ZEND_FFI_TYPE(type->pointer.type), ZEND_FFI_TYPE(cdata->type))) {
839 					if (cdata->flags & ZEND_FFI_FLAG_OWNED) {
840 						zend_throw_error(zend_ffi_exception_ce, "Attempt to perform assign pointer to owned C data");
841 						return FAILURE;
842 					}
843 					*(void**)ptr = cdata->ptr;
844 					return SUCCESS;
845 				}
846 #if FFI_CLOSURES
847 			} else if (ZEND_FFI_TYPE(type->pointer.type)->kind == ZEND_FFI_TYPE_FUNC) {
848 				void *callback = zend_ffi_create_callback(ZEND_FFI_TYPE(type->pointer.type), value);
849 
850 				if (callback) {
851 					*(void**)ptr = callback;
852 					break;
853 				} else {
854 					return FAILURE;
855 				}
856 #endif
857 			}
858 			zend_ffi_assign_incompatible(value, type);
859 			return FAILURE;
860 		case ZEND_FFI_TYPE_STRUCT:
861 		case ZEND_FFI_TYPE_ARRAY:
862 		default:
863 			/* Incompatible types, because otherwise the CData check at the entry point would've succeeded. */
864 			zend_ffi_assign_incompatible(value, type);
865 			return FAILURE;
866 	}
867 	return SUCCESS;
868 }
869 /* }}} */
870 
871 #if defined(ZEND_WIN32) && (defined(HAVE_FFI_FASTCALL) || defined(HAVE_FFI_STDCALL) || defined(HAVE_FFI_VECTORCALL_PARTIAL))
zend_ffi_arg_size(zend_ffi_type * type)872 static size_t zend_ffi_arg_size(zend_ffi_type *type) /* {{{ */
873 {
874 	zend_ffi_type *arg_type;
875 	size_t arg_size = 0;
876 
877 	ZEND_HASH_PACKED_FOREACH_PTR(type->func.args, arg_type) {
878 		arg_size += MAX(ZEND_FFI_TYPE(arg_type)->size, sizeof(size_t));
879 	} ZEND_HASH_FOREACH_END();
880 	return arg_size;
881 }
882 /* }}} */
883 #endif
884 
zend_ffi_mangled_func_name(zend_string * name,zend_ffi_type * type)885 static zend_always_inline zend_string *zend_ffi_mangled_func_name(zend_string *name, zend_ffi_type *type) /* {{{ */
886 {
887 #ifdef ZEND_WIN32
888 	switch (type->func.abi) {
889 # ifdef HAVE_FFI_FASTCALL
890 		case FFI_FASTCALL:
891 			return strpprintf(0, "@%s@%zu", ZSTR_VAL(name), zend_ffi_arg_size(type));
892 # endif
893 # ifdef HAVE_FFI_STDCALL
894 		case FFI_STDCALL:
895 			return strpprintf(0, "_%s@%zu", ZSTR_VAL(name), zend_ffi_arg_size(type));
896 # endif
897 # ifdef HAVE_FFI_VECTORCALL_PARTIAL
898 		case FFI_VECTORCALL_PARTIAL:
899 			return strpprintf(0, "%s@@%zu", ZSTR_VAL(name), zend_ffi_arg_size(type));
900 # endif
901 	}
902 #endif
903 	return zend_string_copy(name);
904 }
905 /* }}} */
906 
907 #if FFI_CLOSURES
908 typedef struct _zend_ffi_callback_data {
909 	zend_fcall_info_cache  fcc;
910 	zend_ffi_type         *type;
911 	void                  *code;
912 	void                  *callback;
913 	ffi_cif                cif;
914 	uint32_t               arg_count;
915 	ffi_type              *ret_type;
916 	ffi_type              *arg_types[0];
917 } zend_ffi_callback_data;
918 
zend_ffi_callback_hash_dtor(zval * zv)919 static void zend_ffi_callback_hash_dtor(zval *zv) /* {{{ */
920 {
921 	zend_ffi_callback_data *callback_data = Z_PTR_P(zv);
922 
923 	ffi_closure_free(callback_data->callback);
924 	if (callback_data->fcc.function_handler->common.fn_flags & ZEND_ACC_CLOSURE) {
925 		OBJ_RELEASE(ZEND_CLOSURE_OBJECT(callback_data->fcc.function_handler));
926 	}
927 	for (int i = 0; i < callback_data->arg_count; ++i) {
928 		if (callback_data->arg_types[i]->type == FFI_TYPE_STRUCT) {
929 			efree(callback_data->arg_types[i]);
930 		}
931 	}
932 	if (callback_data->ret_type->type == FFI_TYPE_STRUCT) {
933 		efree(callback_data->ret_type);
934 	}
935 	efree(callback_data);
936 }
937 /* }}} */
938 
zend_ffi_callback_trampoline(ffi_cif * cif,void * ret,void ** args,void * data)939 static void zend_ffi_callback_trampoline(ffi_cif* cif, void* ret, void** args, void* data) /* {{{ */
940 {
941 	zend_ffi_callback_data *callback_data = (zend_ffi_callback_data*)data;
942 	zend_fcall_info fci;
943 	zend_ffi_type *ret_type;
944 	zval retval;
945 	ALLOCA_FLAG(use_heap)
946 
947 	fci.size = sizeof(zend_fcall_info);
948 	ZVAL_UNDEF(&fci.function_name);
949 	fci.retval = &retval;
950 	fci.params = do_alloca(sizeof(zval) *callback_data->arg_count, use_heap);
951 	fci.object = NULL;
952 	fci.param_count = callback_data->arg_count;
953 	fci.named_params = NULL;
954 
955 	if (callback_data->type->func.args) {
956 		int n = 0;
957 		zend_ffi_type *arg_type;
958 
959 		ZEND_HASH_PACKED_FOREACH_PTR(callback_data->type->func.args, arg_type) {
960 			arg_type = ZEND_FFI_TYPE(arg_type);
961 			zend_ffi_cdata_to_zval(NULL, args[n], arg_type, BP_VAR_R, &fci.params[n], (zend_ffi_flags)(arg_type->attr & ZEND_FFI_ATTR_CONST), 0, 0);
962 			n++;
963 		} ZEND_HASH_FOREACH_END();
964 	}
965 
966 	ZVAL_UNDEF(&retval);
967 	if (zend_call_function(&fci, &callback_data->fcc) != SUCCESS) {
968 		zend_throw_error(zend_ffi_exception_ce, "Cannot call callback");
969 	}
970 
971 	if (callback_data->arg_count) {
972 		int n = 0;
973 
974 		for (n = 0; n < callback_data->arg_count; n++) {
975 			zval_ptr_dtor(&fci.params[n]);
976 		}
977 	}
978 	free_alloca(fci.params, use_heap);
979 
980 	if (EG(exception)) {
981 		zend_error(E_ERROR, "Throwing from FFI callbacks is not allowed");
982 	}
983 
984 	ret_type = ZEND_FFI_TYPE(callback_data->type->func.ret_type);
985 	if (ret_type->kind != ZEND_FFI_TYPE_VOID) {
986 		zend_ffi_zval_to_cdata(ret, ret_type, &retval);
987 	}
988 
989 	zval_ptr_dtor(&retval);
990 }
991 /* }}} */
992 
zend_ffi_create_callback(zend_ffi_type * type,zval * value)993 static void *zend_ffi_create_callback(zend_ffi_type *type, zval *value) /* {{{ */
994 {
995 	zend_fcall_info_cache fcc;
996 	char *error = NULL;
997 	uint32_t arg_count;
998 	void *code;
999 	void *callback;
1000 	zend_ffi_callback_data *callback_data;
1001 
1002 	if (type->attr & ZEND_FFI_ATTR_VARIADIC) {
1003 		zend_throw_error(zend_ffi_exception_ce, "Variadic function closures are not supported");
1004 		return NULL;
1005 	}
1006 
1007 	if (!zend_is_callable_ex(value, NULL, 0, NULL, &fcc, &error)) {
1008 		zend_throw_error(zend_ffi_exception_ce, "Attempt to assign an invalid callback, %s", error);
1009 		return NULL;
1010 	}
1011 
1012 	arg_count = type->func.args ? zend_hash_num_elements(type->func.args) : 0;
1013 	if (arg_count < fcc.function_handler->common.required_num_args) {
1014 		zend_throw_error(zend_ffi_exception_ce, "Attempt to assign an invalid callback, insufficient number of arguments");
1015 		return NULL;
1016 	}
1017 
1018 	callback = ffi_closure_alloc(sizeof(ffi_closure), &code);
1019 	if (!callback) {
1020 		zend_throw_error(zend_ffi_exception_ce, "Cannot allocate callback");
1021 		return NULL;
1022 	}
1023 
1024 	callback_data = emalloc(sizeof(zend_ffi_callback_data) + sizeof(ffi_type*) * arg_count);
1025 	memcpy(&callback_data->fcc, &fcc, sizeof(zend_fcall_info_cache));
1026 	callback_data->type = type;
1027 	callback_data->callback = callback;
1028 	callback_data->code = code;
1029 	callback_data->arg_count = arg_count;
1030 
1031 	if (type->func.args) {
1032 		int n = 0;
1033 		zend_ffi_type *arg_type;
1034 
1035 		ZEND_HASH_PACKED_FOREACH_PTR(type->func.args, arg_type) {
1036 			arg_type = ZEND_FFI_TYPE(arg_type);
1037 			callback_data->arg_types[n] = zend_ffi_get_type(arg_type);
1038 			if (!callback_data->arg_types[n]) {
1039 				zend_ffi_pass_unsupported(arg_type);
1040 				for (int i = 0; i < n; ++i) {
1041 					if (callback_data->arg_types[i]->type == FFI_TYPE_STRUCT) {
1042 						efree(callback_data->arg_types[i]);
1043 					}
1044 				}
1045 				efree(callback_data);
1046 				ffi_closure_free(callback);
1047 				return NULL;
1048 			}
1049 			n++;
1050 		} ZEND_HASH_FOREACH_END();
1051 	}
1052 	callback_data->ret_type = zend_ffi_get_type(ZEND_FFI_TYPE(type->func.ret_type));
1053 	if (!callback_data->ret_type) {
1054 		zend_ffi_return_unsupported(type->func.ret_type);
1055 		for (int i = 0; i < callback_data->arg_count; ++i) {
1056 			if (callback_data->arg_types[i]->type == FFI_TYPE_STRUCT) {
1057 				efree(callback_data->arg_types[i]);
1058 			}
1059 		}
1060 		efree(callback_data);
1061 		ffi_closure_free(callback);
1062 		return NULL;
1063 	}
1064 
1065 	if (ffi_prep_cif(&callback_data->cif, type->func.abi, callback_data->arg_count, callback_data->ret_type, callback_data->arg_types) != FFI_OK) {
1066 		zend_throw_error(zend_ffi_exception_ce, "Cannot prepare callback CIF");
1067 		goto free_on_failure;
1068 	}
1069 
1070 	if (ffi_prep_closure_loc(callback, &callback_data->cif, zend_ffi_callback_trampoline, callback_data, code) != FFI_OK) {
1071 		zend_throw_error(zend_ffi_exception_ce, "Cannot prepare callback");
1072 free_on_failure: ;
1073 		for (int i = 0; i < callback_data->arg_count; ++i) {
1074 			if (callback_data->arg_types[i]->type == FFI_TYPE_STRUCT) {
1075 				efree(callback_data->arg_types[i]);
1076 			}
1077 		}
1078 		if (callback_data->ret_type->type == FFI_TYPE_STRUCT) {
1079 			efree(callback_data->ret_type);
1080 		}
1081 		efree(callback_data);
1082 		ffi_closure_free(callback);
1083 		return NULL;
1084 	}
1085 
1086 	if (!FFI_G(callbacks)) {
1087 		FFI_G(callbacks) = emalloc(sizeof(HashTable));
1088 		zend_hash_init(FFI_G(callbacks), 0, NULL, zend_ffi_callback_hash_dtor, 0);
1089 	}
1090 	zend_hash_next_index_insert_ptr(FFI_G(callbacks), callback_data);
1091 
1092 	if (fcc.function_handler->common.fn_flags & ZEND_ACC_CLOSURE) {
1093 		GC_ADDREF(ZEND_CLOSURE_OBJECT(fcc.function_handler));
1094 	}
1095 
1096 	return code;
1097 }
1098 /* }}} */
1099 #endif
1100 
zend_ffi_cdata_get(zend_object * obj,zend_string * member,int read_type,void ** cache_slot,zval * rv)1101 static zval *zend_ffi_cdata_get(zend_object *obj, zend_string *member, int read_type, void **cache_slot, zval *rv) /* {{{ */
1102 {
1103 	zend_ffi_cdata *cdata = (zend_ffi_cdata*)obj;
1104 	zend_ffi_type  *type = ZEND_FFI_TYPE(cdata->type);
1105 
1106 #if 0
1107 	if (UNEXPECTED(!cdata->ptr)) {
1108 		zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
1109 		return &EG(uninitialized_zval);
1110 	}
1111 #endif
1112 
1113 	if (UNEXPECTED(!zend_string_equals_literal(member, "cdata"))) {
1114 		zend_throw_error(zend_ffi_exception_ce, "Only 'cdata' property may be read");
1115 		return &EG(uninitialized_zval);
1116 	}
1117 
1118 	zend_ffi_cdata_to_zval(cdata, cdata->ptr, type, BP_VAR_R, rv, 0, 0, 0);
1119 	return rv;
1120 }
1121 /* }}} */
1122 
zend_ffi_cdata_set(zend_object * obj,zend_string * member,zval * value,void ** cache_slot)1123 static zval *zend_ffi_cdata_set(zend_object *obj, zend_string *member, zval *value, void **cache_slot) /* {{{ */
1124 {
1125 	zend_ffi_cdata *cdata = (zend_ffi_cdata*)obj;
1126 	zend_ffi_type  *type = ZEND_FFI_TYPE(cdata->type);
1127 
1128 #if 0
1129 	if (UNEXPECTED(!cdata->ptr)) {
1130 		zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
1131 		return &EG(uninitialized_zval);
1132 	}
1133 #endif
1134 
1135 	if (UNEXPECTED(!zend_string_equals_literal(member, "cdata"))) {
1136 		zend_throw_error(zend_ffi_exception_ce, "Only 'cdata' property may be set");
1137 		return &EG(uninitialized_zval);
1138 	}
1139 
1140 	zend_ffi_zval_to_cdata(cdata->ptr, type, value);
1141 
1142 	return value;
1143 }
1144 /* }}} */
1145 
zend_ffi_cdata_cast_object(zend_object * readobj,zval * writeobj,int type)1146 static zend_result zend_ffi_cdata_cast_object(zend_object *readobj, zval *writeobj, int type) /* {{{ */
1147 {
1148 	if (type == IS_STRING) {
1149 		zend_ffi_cdata *cdata = (zend_ffi_cdata*)readobj;
1150 		zend_ffi_type  *ctype = ZEND_FFI_TYPE(cdata->type);
1151 		void           *ptr = cdata->ptr;
1152 		zend_ffi_type_kind kind = ctype->kind;
1153 
1154 again:
1155 	    switch (kind) {
1156 			case ZEND_FFI_TYPE_FLOAT:
1157 				ZVAL_DOUBLE(writeobj, *(float*)ptr);
1158 				break;
1159 			case ZEND_FFI_TYPE_DOUBLE:
1160 				ZVAL_DOUBLE(writeobj, *(double*)ptr);
1161 				break;
1162 #ifdef HAVE_LONG_DOUBLE
1163 			case ZEND_FFI_TYPE_LONGDOUBLE:
1164 				ZVAL_DOUBLE(writeobj, *(long double*)ptr);
1165 				break;
1166 #endif
1167 			case ZEND_FFI_TYPE_UINT8:
1168 				ZVAL_LONG(writeobj, *(uint8_t*)ptr);
1169 				break;
1170 			case ZEND_FFI_TYPE_SINT8:
1171 				ZVAL_LONG(writeobj, *(int8_t*)ptr);
1172 				break;
1173 			case ZEND_FFI_TYPE_UINT16:
1174 				ZVAL_LONG(writeobj, *(uint16_t*)ptr);
1175 				break;
1176 			case ZEND_FFI_TYPE_SINT16:
1177 				ZVAL_LONG(writeobj, *(int16_t*)ptr);
1178 				break;
1179 			case ZEND_FFI_TYPE_UINT32:
1180 				ZVAL_LONG(writeobj, *(uint32_t*)ptr);
1181 				break;
1182 			case ZEND_FFI_TYPE_SINT32:
1183 				ZVAL_LONG(writeobj, *(int32_t*)ptr);
1184 				break;
1185 			case ZEND_FFI_TYPE_UINT64:
1186 				ZVAL_LONG(writeobj, *(uint64_t*)ptr);
1187 				break;
1188 			case ZEND_FFI_TYPE_SINT64:
1189 				ZVAL_LONG(writeobj, *(int64_t*)ptr);
1190 				break;
1191 			case ZEND_FFI_TYPE_BOOL:
1192 				ZVAL_BOOL(writeobj, *(uint8_t*)ptr);
1193 				break;
1194 			case ZEND_FFI_TYPE_CHAR:
1195 				ZVAL_CHAR(writeobj, *(char*)ptr);
1196 				return SUCCESS;
1197 			case ZEND_FFI_TYPE_ENUM:
1198 				kind = ctype->enumeration.kind;
1199 				goto again;
1200 			case ZEND_FFI_TYPE_POINTER:
1201 				if (*(void**)ptr == NULL) {
1202 					ZVAL_NULL(writeobj);
1203 					break;
1204 				} else if ((ctype->attr & ZEND_FFI_ATTR_CONST) && ZEND_FFI_TYPE(ctype->pointer.type)->kind == ZEND_FFI_TYPE_CHAR) {
1205 					ZVAL_STRING(writeobj, *(char**)ptr);
1206 					return SUCCESS;
1207 				}
1208 				return FAILURE;
1209 			default:
1210 				return FAILURE;
1211 		}
1212 		convert_to_string(writeobj);
1213 		return SUCCESS;
1214 	} else if (type == _IS_BOOL) {
1215 		ZVAL_TRUE(writeobj);
1216 		return SUCCESS;
1217 	}
1218 
1219 	return FAILURE;
1220 }
1221 /* }}} */
1222 
zend_ffi_cdata_read_field(zend_object * obj,zend_string * field_name,int read_type,void ** cache_slot,zval * rv)1223 static zval *zend_ffi_cdata_read_field(zend_object *obj, zend_string *field_name, int read_type, void **cache_slot, zval *rv) /* {{{ */
1224 {
1225 	zend_ffi_cdata *cdata = (zend_ffi_cdata*)obj;
1226 	zend_ffi_type  *type = ZEND_FFI_TYPE(cdata->type);
1227 	void           *ptr = cdata->ptr;
1228 	zend_ffi_field *field;
1229 
1230 	if (cache_slot && *cache_slot == type) {
1231 		field = *(cache_slot + 1);
1232 	} else {
1233 		if (type->kind == ZEND_FFI_TYPE_POINTER) {
1234 			type = ZEND_FFI_TYPE(type->pointer.type);
1235 		}
1236 		if (UNEXPECTED(type->kind != ZEND_FFI_TYPE_STRUCT)) {
1237 			if (UNEXPECTED(type->kind != ZEND_FFI_TYPE_STRUCT)) {
1238 				zend_throw_error(zend_ffi_exception_ce, "Attempt to read field '%s' of non C struct/union", ZSTR_VAL(field_name));
1239 				return &EG(uninitialized_zval);
1240 			}
1241 		}
1242 
1243 		field = zend_hash_find_ptr(&type->record.fields, field_name);
1244 		if (UNEXPECTED(!field)) {
1245 			zend_throw_error(zend_ffi_exception_ce, "Attempt to read undefined field '%s' of C struct/union", ZSTR_VAL(field_name));
1246 			return &EG(uninitialized_zval);
1247 		}
1248 
1249 		if (cache_slot) {
1250 			*cache_slot = type;
1251 			*(cache_slot + 1) = field;
1252 		}
1253 	}
1254 
1255 	if (ZEND_FFI_TYPE(cdata->type)->kind == ZEND_FFI_TYPE_POINTER) {
1256 		/* transparently dereference the pointer */
1257 		if (UNEXPECTED(!ptr)) {
1258 			zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
1259 			return &EG(uninitialized_zval);
1260 		}
1261 		ptr = (void*)(*(char**)ptr);
1262 		if (UNEXPECTED(!ptr)) {
1263 			zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
1264 			return &EG(uninitialized_zval);
1265 		}
1266 		type = ZEND_FFI_TYPE(type->pointer.type);
1267 	}
1268 
1269 #if 0
1270 	if (UNEXPECTED(!ptr)) {
1271 		zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
1272 		return &EG(uninitialized_zval);
1273 	}
1274 #endif
1275 
1276 	if (EXPECTED(!field->bits)) {
1277 		zend_ffi_type *field_type = field->type;
1278 
1279 		if (ZEND_FFI_TYPE_IS_OWNED(field_type)) {
1280 			field_type = ZEND_FFI_TYPE(field_type);
1281 			if (!(field_type->attr & ZEND_FFI_ATTR_STORED)
1282 			 && field_type->kind == ZEND_FFI_TYPE_POINTER) {
1283 				field->type = field_type = zend_ffi_remember_type(field_type);
1284 			}
1285 		}
1286 		ptr = (void*)(((char*)ptr) + field->offset);
1287 		zend_ffi_cdata_to_zval(NULL, ptr, field_type, read_type, rv, (cdata->flags & ZEND_FFI_FLAG_CONST) | (zend_ffi_flags)field->is_const, 0, 0);
1288 	} else {
1289 		zend_ffi_bit_field_to_zval(ptr, field, rv);
1290 	}
1291 
1292 	return rv;
1293 }
1294 /* }}} */
1295 
zend_ffi_cdata_write_field(zend_object * obj,zend_string * field_name,zval * value,void ** cache_slot)1296 static zval *zend_ffi_cdata_write_field(zend_object *obj, zend_string *field_name, zval *value, void **cache_slot) /* {{{ */
1297 {
1298 	zend_ffi_cdata *cdata = (zend_ffi_cdata*)obj;
1299 	zend_ffi_type  *type = ZEND_FFI_TYPE(cdata->type);
1300 	void           *ptr = cdata->ptr;
1301 	zend_ffi_field *field;
1302 
1303 	if (cache_slot && *cache_slot == type) {
1304 		field = *(cache_slot + 1);
1305 	} else {
1306 		if (UNEXPECTED(type == NULL)) {
1307 			zend_throw_error(zend_ffi_exception_ce, "Attempt to assign field '%s' to uninitialized FFI\\CData object", ZSTR_VAL(field_name));
1308 			return value;
1309 		}
1310 		if (type->kind == ZEND_FFI_TYPE_POINTER) {
1311 			type = ZEND_FFI_TYPE(type->pointer.type);
1312 		}
1313 		if (UNEXPECTED(type->kind != ZEND_FFI_TYPE_STRUCT)) {
1314 			if (UNEXPECTED(type->kind != ZEND_FFI_TYPE_STRUCT)) {
1315 				zend_throw_error(zend_ffi_exception_ce, "Attempt to assign field '%s' of non C struct/union", ZSTR_VAL(field_name));
1316 				return value;
1317 			}
1318 		}
1319 
1320 		field = zend_hash_find_ptr(&type->record.fields, field_name);
1321 		if (UNEXPECTED(!field)) {
1322 			zend_throw_error(zend_ffi_exception_ce, "Attempt to assign undefined field '%s' of C struct/union", ZSTR_VAL(field_name));
1323 			return value;
1324 		}
1325 
1326 		if (cache_slot) {
1327 			*cache_slot = type;
1328 			*(cache_slot + 1) = field;
1329 		}
1330 	}
1331 
1332 	if (ZEND_FFI_TYPE(cdata->type)->kind == ZEND_FFI_TYPE_POINTER) {
1333 		/* transparently dereference the pointer */
1334 		if (UNEXPECTED(!ptr)) {
1335 			zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
1336 			return value;
1337 		}
1338 		ptr = (void*)(*(char**)ptr);
1339 		if (UNEXPECTED(!ptr)) {
1340 			zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
1341 			return value;
1342 		}
1343 	}
1344 
1345 #if 0
1346 	if (UNEXPECTED(!ptr)) {
1347 		zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
1348 		return value;
1349 	}
1350 #endif
1351 
1352 	if (UNEXPECTED(cdata->flags & ZEND_FFI_FLAG_CONST)) {
1353 		zend_throw_error(zend_ffi_exception_ce, "Attempt to assign read-only location");
1354 		return value;
1355 	} else if (UNEXPECTED(field->is_const)) {
1356 		zend_throw_error(zend_ffi_exception_ce, "Attempt to assign read-only field '%s'", ZSTR_VAL(field_name));
1357 		return value;
1358 	}
1359 
1360 	if (EXPECTED(!field->bits)) {
1361 		ptr = (void*)(((char*)ptr) + field->offset);
1362 		zend_ffi_zval_to_cdata(ptr, ZEND_FFI_TYPE(field->type), value);
1363 	} else {
1364 		zend_ffi_zval_to_bit_field(ptr, field, value);
1365 	}
1366 	return value;
1367 }
1368 /* }}} */
1369 
zend_ffi_cdata_read_dim(zend_object * obj,zval * offset,int read_type,zval * rv)1370 static zval *zend_ffi_cdata_read_dim(zend_object *obj, zval *offset, int read_type, zval *rv) /* {{{ */
1371 {
1372 	zend_ffi_cdata *cdata = (zend_ffi_cdata*)obj;
1373 	zend_ffi_type  *type = ZEND_FFI_TYPE(cdata->type);
1374 	zend_long       dim = zval_get_long(offset);
1375 	zend_ffi_type  *dim_type;
1376 	void           *ptr;
1377 	zend_ffi_flags  is_const;
1378 
1379 	if (EXPECTED(type->kind == ZEND_FFI_TYPE_ARRAY)) {
1380 		if (UNEXPECTED((zend_ulong)(dim) >= (zend_ulong)type->array.length)
1381 		 && (UNEXPECTED(dim < 0) || UNEXPECTED(type->array.length != 0))) {
1382 			zend_throw_error(zend_ffi_exception_ce, "C array index out of bounds");
1383 			return &EG(uninitialized_zval);
1384 		}
1385 
1386 		is_const = (cdata->flags & ZEND_FFI_FLAG_CONST) | (zend_ffi_flags)(type->attr & ZEND_FFI_ATTR_CONST);
1387 
1388 		dim_type = type->array.type;
1389 		if (ZEND_FFI_TYPE_IS_OWNED(dim_type)) {
1390 			dim_type = ZEND_FFI_TYPE(dim_type);
1391 			if (!(dim_type->attr & ZEND_FFI_ATTR_STORED)
1392 			 && dim_type->kind == ZEND_FFI_TYPE_POINTER) {
1393 				type->array.type = dim_type = zend_ffi_remember_type(dim_type);
1394 			}
1395 		}
1396 #if 0
1397 		if (UNEXPECTED(!cdata->ptr)) {
1398 			zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
1399 			return &EG(uninitialized_zval);
1400 		}
1401 #endif
1402 		ptr = (void*)(((char*)cdata->ptr) + dim_type->size * dim);
1403 	} else if (EXPECTED(type->kind == ZEND_FFI_TYPE_POINTER)) {
1404 		is_const = (cdata->flags & ZEND_FFI_FLAG_CONST) | (zend_ffi_flags)(type->attr & ZEND_FFI_ATTR_CONST);
1405 		dim_type = type->pointer.type;
1406 		if (ZEND_FFI_TYPE_IS_OWNED(dim_type)) {
1407 			dim_type = ZEND_FFI_TYPE(dim_type);
1408 			if (!(dim_type->attr & ZEND_FFI_ATTR_STORED)
1409 			 && dim_type->kind == ZEND_FFI_TYPE_POINTER) {
1410 				type->pointer.type = dim_type = zend_ffi_remember_type(dim_type);
1411 			}
1412 		}
1413 		if (UNEXPECTED(!cdata->ptr)) {
1414 			zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
1415 			return &EG(uninitialized_zval);
1416 		}
1417 		ptr = (void*)((*(char**)cdata->ptr) + dim_type->size * dim);
1418 	} else {
1419 		zend_throw_error(zend_ffi_exception_ce, "Attempt to read element of non C array");
1420 		return &EG(uninitialized_zval);
1421 	}
1422 
1423 	zend_ffi_cdata_to_zval(NULL, ptr, dim_type, read_type, rv, is_const, 0, 0);
1424 	return rv;
1425 }
1426 /* }}} */
1427 
zend_ffi_cdata_write_dim(zend_object * obj,zval * offset,zval * value)1428 static void zend_ffi_cdata_write_dim(zend_object *obj, zval *offset, zval *value) /* {{{ */
1429 {
1430 	zend_ffi_cdata *cdata = (zend_ffi_cdata*)obj;
1431 	zend_ffi_type  *type = ZEND_FFI_TYPE(cdata->type);
1432 	zend_long       dim;
1433 	void           *ptr;
1434 	zend_ffi_flags  is_const;
1435 
1436 	if (offset == NULL) {
1437 		zend_throw_error(zend_ffi_exception_ce, "Cannot add next element to object of type FFI\\CData");
1438 		return;
1439 	}
1440 
1441 	dim = zval_get_long(offset);
1442 	if (EXPECTED(type->kind == ZEND_FFI_TYPE_ARRAY)) {
1443 		if (UNEXPECTED((zend_ulong)(dim) >= (zend_ulong)type->array.length)
1444 		 && (UNEXPECTED(dim < 0) || UNEXPECTED(type->array.length != 0))) {
1445 			zend_throw_error(zend_ffi_exception_ce, "C array index out of bounds");
1446 			return;
1447 		}
1448 
1449 		is_const = (cdata->flags & ZEND_FFI_FLAG_CONST) | (zend_ffi_flags)(type->attr & ZEND_FFI_ATTR_CONST);
1450 		type = ZEND_FFI_TYPE(type->array.type);
1451 #if 0
1452 		if (UNEXPECTED(!cdata->ptr)) {
1453 			zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
1454 			return;
1455 		}
1456 #endif
1457 		ptr = (void*)(((char*)cdata->ptr) + type->size * dim);
1458 	} else if (EXPECTED(type->kind == ZEND_FFI_TYPE_POINTER)) {
1459 		is_const = (cdata->flags & ZEND_FFI_FLAG_CONST) | (zend_ffi_flags)(type->attr & ZEND_FFI_ATTR_CONST);
1460 		type = ZEND_FFI_TYPE(type->pointer.type);
1461 		if (UNEXPECTED(!cdata->ptr)) {
1462 			zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
1463 			return;
1464 		}
1465 		ptr = (void*)((*(char**)cdata->ptr) + type->size * dim);
1466 	} else {
1467 		zend_throw_error(zend_ffi_exception_ce, "Attempt to assign element of non C array");
1468 		return;
1469 	}
1470 
1471 	if (UNEXPECTED(is_const)) {
1472 		zend_throw_error(zend_ffi_exception_ce, "Attempt to assign read-only location");
1473 		return;
1474 	}
1475 
1476 	zend_ffi_zval_to_cdata(ptr, type, value);
1477 }
1478 /* }}} */
1479 
1480 #define MAX_TYPE_NAME_LEN 256
1481 
1482 typedef struct _zend_ffi_ctype_name_buf {
1483 	char *start;
1484 	char *end;
1485 	char buf[MAX_TYPE_NAME_LEN];
1486 } zend_ffi_ctype_name_buf;
1487 
zend_ffi_ctype_name_prepend(zend_ffi_ctype_name_buf * buf,const char * str,size_t len)1488 static bool zend_ffi_ctype_name_prepend(zend_ffi_ctype_name_buf *buf, const char *str, size_t len) /* {{{ */
1489 {
1490 	buf->start -= len;
1491 	if (buf->start < buf->buf) {
1492 		return 0;
1493 	}
1494 	memcpy(buf->start, str, len);
1495 	return 1;
1496 }
1497 /* }}} */
1498 
zend_ffi_ctype_name_append(zend_ffi_ctype_name_buf * buf,const char * str,size_t len)1499 static bool zend_ffi_ctype_name_append(zend_ffi_ctype_name_buf *buf, const char *str, size_t len) /* {{{ */
1500 {
1501 	if (buf->end + len > buf->buf + MAX_TYPE_NAME_LEN) {
1502 		return 0;
1503 	}
1504 	memcpy(buf->end, str, len);
1505 	buf->end += len;
1506 	return 1;
1507 }
1508 /* }}} */
1509 
zend_ffi_ctype_name(zend_ffi_ctype_name_buf * buf,const zend_ffi_type * type)1510 static bool zend_ffi_ctype_name(zend_ffi_ctype_name_buf *buf, const zend_ffi_type *type) /* {{{ */
1511 {
1512 	const char *name = NULL;
1513 	bool is_ptr = 0;
1514 
1515 	while (1) {
1516 		switch (type->kind) {
1517 			case ZEND_FFI_TYPE_VOID:
1518 				name = "void";
1519 				break;
1520 			case ZEND_FFI_TYPE_FLOAT:
1521 				name = "float";
1522 				break;
1523 			case ZEND_FFI_TYPE_DOUBLE:
1524 				name = "double";
1525 				break;
1526 #ifdef HAVE_LONG_DOUBLE
1527 			case ZEND_FFI_TYPE_LONGDOUBLE:
1528 				name = "long double";
1529 				break;
1530 #endif
1531 			case ZEND_FFI_TYPE_UINT8:
1532 				name = "uint8_t";
1533 				break;
1534 			case ZEND_FFI_TYPE_SINT8:
1535 				name = "int8_t";
1536 				break;
1537 			case ZEND_FFI_TYPE_UINT16:
1538 				name = "uint16_t";
1539 				break;
1540 			case ZEND_FFI_TYPE_SINT16:
1541 				name = "int16_t";
1542 				break;
1543 			case ZEND_FFI_TYPE_UINT32:
1544 				name = "uint32_t";
1545 				break;
1546 			case ZEND_FFI_TYPE_SINT32:
1547 				name = "int32_t";
1548 				break;
1549 			case ZEND_FFI_TYPE_UINT64:
1550 				name = "uint64_t";
1551 				break;
1552 			case ZEND_FFI_TYPE_SINT64:
1553 				name = "int64_t";
1554 				break;
1555 			case ZEND_FFI_TYPE_ENUM:
1556 				if (type->enumeration.tag_name) {
1557 					zend_ffi_ctype_name_prepend(buf, ZSTR_VAL(type->enumeration.tag_name), ZSTR_LEN(type->enumeration.tag_name));
1558 				} else {
1559 					zend_ffi_ctype_name_prepend(buf, "<anonymous>", sizeof("<anonymous>")-1);
1560 				}
1561 				name = "enum ";
1562 				break;
1563 			case ZEND_FFI_TYPE_BOOL:
1564 				name = "bool";
1565 				break;
1566 			case ZEND_FFI_TYPE_CHAR:
1567 				name = "char";
1568 				break;
1569 			case ZEND_FFI_TYPE_POINTER:
1570 				if (!zend_ffi_ctype_name_prepend(buf, "*", 1)) {
1571 					return 0;
1572 				}
1573 				is_ptr = 1;
1574 				type = ZEND_FFI_TYPE(type->pointer.type);
1575 				break;
1576 			case ZEND_FFI_TYPE_FUNC:
1577 				if (is_ptr) {
1578 					is_ptr = 0;
1579 					if (!zend_ffi_ctype_name_prepend(buf, "(", 1)
1580 					 || !zend_ffi_ctype_name_append(buf, ")", 1)) {
1581 						return 0;
1582 					}
1583 				}
1584 				if (!zend_ffi_ctype_name_append(buf, "(", 1)
1585 				 || !zend_ffi_ctype_name_append(buf, ")", 1)) {
1586 					return 0;
1587 				}
1588 				type = ZEND_FFI_TYPE(type->func.ret_type);
1589 				break;
1590 			case ZEND_FFI_TYPE_ARRAY:
1591 				if (is_ptr) {
1592 					is_ptr = 0;
1593 					if (!zend_ffi_ctype_name_prepend(buf, "(", 1)
1594 					 || !zend_ffi_ctype_name_append(buf, ")", 1)) {
1595 						return 0;
1596 					}
1597 				}
1598 				if (!zend_ffi_ctype_name_append(buf, "[", 1)) {
1599 					return 0;
1600 				}
1601 				if (type->attr & ZEND_FFI_ATTR_VLA) {
1602 					if (!zend_ffi_ctype_name_append(buf, "*", 1)) {
1603 						return 0;
1604 					}
1605 				} else if (!(type->attr & ZEND_FFI_ATTR_INCOMPLETE_ARRAY)) {
1606 					char str[MAX_LENGTH_OF_LONG + 1];
1607 					char *s = zend_print_long_to_buf(str + sizeof(str) - 1, type->array.length);
1608 
1609 					if (!zend_ffi_ctype_name_append(buf, s, strlen(s))) {
1610 						return 0;
1611 					}
1612 				}
1613 				if (!zend_ffi_ctype_name_append(buf, "]", 1)) {
1614 					return 0;
1615 				}
1616 				type = ZEND_FFI_TYPE(type->array.type);
1617 				break;
1618 			case ZEND_FFI_TYPE_STRUCT:
1619 				if (type->attr & ZEND_FFI_ATTR_UNION) {
1620 					if (type->record.tag_name) {
1621 						zend_ffi_ctype_name_prepend(buf, ZSTR_VAL(type->record.tag_name), ZSTR_LEN(type->record.tag_name));
1622 					} else {
1623 						zend_ffi_ctype_name_prepend(buf, "<anonymous>", sizeof("<anonymous>")-1);
1624 					}
1625 					name = "union ";
1626 				} else {
1627 					if (type->record.tag_name) {
1628 						zend_ffi_ctype_name_prepend(buf, ZSTR_VAL(type->record.tag_name), ZSTR_LEN(type->record.tag_name));
1629 					} else {
1630 						zend_ffi_ctype_name_prepend(buf, "<anonymous>", sizeof("<anonymous>")-1);
1631 					}
1632 					name = "struct ";
1633 				}
1634 				break;
1635 			default:
1636 				ZEND_UNREACHABLE();
1637 		}
1638 		if (name) {
1639 			break;
1640 		}
1641 	}
1642 
1643 //	if (buf->start != buf->end && *buf->start != '[') {
1644 //		if (!zend_ffi_ctype_name_prepend(buf, " ", 1)) {
1645 //			return 0;
1646 //		}
1647 //	}
1648 	return zend_ffi_ctype_name_prepend(buf, name, strlen(name));
1649 }
1650 /* }}} */
1651 
zend_ffi_return_unsupported(zend_ffi_type * type)1652 static ZEND_COLD void zend_ffi_return_unsupported(zend_ffi_type *type) /* {{{ */
1653 {
1654 	type = ZEND_FFI_TYPE(type);
1655 	if (type->kind == ZEND_FFI_TYPE_STRUCT) {
1656 		zend_throw_error(zend_ffi_exception_ce, "FFI return struct/union is not implemented");
1657 	} else if (type->kind == ZEND_FFI_TYPE_ARRAY) {
1658 		zend_throw_error(zend_ffi_exception_ce, "FFI return array is not implemented");
1659 	} else {
1660 		zend_throw_error(zend_ffi_exception_ce, "FFI internal error. Unsupported return type");
1661 	}
1662 }
1663 /* }}} */
1664 
zend_ffi_pass_unsupported(zend_ffi_type * type)1665 static ZEND_COLD void zend_ffi_pass_unsupported(zend_ffi_type *type) /* {{{ */
1666 {
1667 	type = ZEND_FFI_TYPE(type);
1668 	if (type->kind == ZEND_FFI_TYPE_STRUCT) {
1669 		zend_throw_error(zend_ffi_exception_ce, "FFI passing struct/union is not implemented");
1670 	} else if (type->kind == ZEND_FFI_TYPE_ARRAY) {
1671 		zend_throw_error(zend_ffi_exception_ce, "FFI passing array is not implemented");
1672 	} else {
1673 		zend_throw_error(zend_ffi_exception_ce, "FFI internal error. Unsupported parameter type");
1674 	}
1675 }
1676 /* }}} */
1677 
zend_ffi_pass_incompatible(zval * arg,zend_ffi_type * type,uint32_t n,zend_execute_data * execute_data)1678 static ZEND_COLD void zend_ffi_pass_incompatible(zval *arg, zend_ffi_type *type, uint32_t n, zend_execute_data *execute_data) /* {{{ */
1679 {
1680 	zend_ffi_ctype_name_buf buf1, buf2;
1681 
1682 	buf1.start = buf1.end = buf1.buf + ((MAX_TYPE_NAME_LEN * 3) / 4);
1683 	if (!zend_ffi_ctype_name(&buf1, type)) {
1684 		zend_throw_error(zend_ffi_exception_ce, "Passing incompatible argument %d of C function '%s'", n + 1, ZSTR_VAL(EX(func)->internal_function.function_name));
1685 	} else {
1686 		*buf1.end = 0;
1687 		if (Z_TYPE_P(arg) == IS_OBJECT && Z_OBJCE_P(arg) == zend_ffi_cdata_ce) {
1688 			zend_ffi_cdata *cdata = (zend_ffi_cdata*)Z_OBJ_P(arg);
1689 
1690 			type = ZEND_FFI_TYPE(cdata->type);
1691 			buf2.start = buf2.end = buf2.buf + ((MAX_TYPE_NAME_LEN * 3) / 4);
1692 			if (!zend_ffi_ctype_name(&buf2, type)) {
1693 				zend_throw_error(zend_ffi_exception_ce, "Passing incompatible argument %d of C function '%s', expecting '%s'", n + 1, ZSTR_VAL(EX(func)->internal_function.function_name), buf1.start);
1694 			} else {
1695 				*buf2.end = 0;
1696 				zend_throw_error(zend_ffi_exception_ce, "Passing incompatible argument %d of C function '%s', expecting '%s', found '%s'", n + 1, ZSTR_VAL(EX(func)->internal_function.function_name), buf1.start, buf2.start);
1697 			}
1698 		} else {
1699 			zend_throw_error(zend_ffi_exception_ce, "Passing incompatible argument %d of C function '%s', expecting '%s', found PHP '%s'", n + 1, ZSTR_VAL(EX(func)->internal_function.function_name), buf1.start, zend_zval_value_name(arg));
1700 		}
1701 	}
1702 }
1703 /* }}} */
1704 
zend_ffi_assign_incompatible(zval * arg,zend_ffi_type * type)1705 static ZEND_COLD void zend_ffi_assign_incompatible(zval *arg, zend_ffi_type *type) /* {{{ */
1706 {
1707 	zend_ffi_ctype_name_buf buf1, buf2;
1708 
1709 	buf1.start = buf1.end = buf1.buf + ((MAX_TYPE_NAME_LEN * 3) / 4);
1710 	if (!zend_ffi_ctype_name(&buf1, type)) {
1711 		zend_throw_error(zend_ffi_exception_ce, "Incompatible types when assigning");
1712 	} else {
1713 		*buf1.end = 0;
1714 		if (Z_TYPE_P(arg) == IS_OBJECT && Z_OBJCE_P(arg) == zend_ffi_cdata_ce) {
1715 			zend_ffi_cdata *cdata = (zend_ffi_cdata*)Z_OBJ_P(arg);
1716 
1717 			type = ZEND_FFI_TYPE(cdata->type);
1718 			buf2.start = buf2.end = buf2.buf + ((MAX_TYPE_NAME_LEN * 3) / 4);
1719 			if (!zend_ffi_ctype_name(&buf2, type)) {
1720 				zend_throw_error(zend_ffi_exception_ce, "Incompatible types when assigning to type '%s'", buf1.start);
1721 			} else {
1722 				*buf2.end = 0;
1723 				zend_throw_error(zend_ffi_exception_ce, "Incompatible types when assigning to type '%s' from type '%s'", buf1.start, buf2.start);
1724 			}
1725 		} else {
1726 			zend_throw_error(zend_ffi_exception_ce, "Incompatible types when assigning to type '%s' from PHP '%s'", buf1.start, zend_zval_value_name(arg));
1727 		}
1728 	}
1729 }
1730 /* }}} */
1731 
zend_ffi_get_class_name(zend_string * prefix,const zend_ffi_type * type)1732 static zend_string *zend_ffi_get_class_name(zend_string *prefix, const zend_ffi_type *type) /* {{{ */
1733 {
1734 	zend_ffi_ctype_name_buf buf;
1735 
1736 	buf.start = buf.end = buf.buf + ((MAX_TYPE_NAME_LEN * 3) / 4);
1737 	if (!zend_ffi_ctype_name(&buf, type)) {
1738 		return zend_string_copy(prefix);
1739 	} else {
1740 		return zend_string_concat3(
1741 			ZSTR_VAL(prefix), ZSTR_LEN(prefix), ":", 1, buf.start, buf.end - buf.start);
1742 	}
1743 }
1744 /* }}} */
1745 
zend_ffi_cdata_get_class_name(const zend_object * zobj)1746 static zend_string *zend_ffi_cdata_get_class_name(const zend_object *zobj) /* {{{ */
1747 {
1748 	zend_ffi_cdata *cdata = (zend_ffi_cdata*)zobj;
1749 
1750 	return zend_ffi_get_class_name(zobj->ce->name, ZEND_FFI_TYPE(cdata->type));
1751 }
1752 /* }}} */
1753 
zend_ffi_cdata_compare_objects(zval * o1,zval * o2)1754 static int zend_ffi_cdata_compare_objects(zval *o1, zval *o2) /* {{{ */
1755 {
1756 	if (Z_TYPE_P(o1) == IS_OBJECT && Z_OBJCE_P(o1) == zend_ffi_cdata_ce &&
1757 	    Z_TYPE_P(o2) == IS_OBJECT && Z_OBJCE_P(o2) == zend_ffi_cdata_ce) {
1758 		zend_ffi_cdata *cdata1 = (zend_ffi_cdata*)Z_OBJ_P(o1);
1759 		zend_ffi_cdata *cdata2 = (zend_ffi_cdata*)Z_OBJ_P(o2);
1760 		zend_ffi_type *type1 = ZEND_FFI_TYPE(cdata1->type);
1761 		zend_ffi_type *type2 = ZEND_FFI_TYPE(cdata2->type);
1762 
1763 		if (type1->kind == ZEND_FFI_TYPE_POINTER && type2->kind == ZEND_FFI_TYPE_POINTER) {
1764 			void *ptr1 = *(void**)cdata1->ptr;
1765 			void *ptr2 = *(void**)cdata2->ptr;
1766 
1767 			if (!ptr1 || !ptr2) {
1768 				zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
1769 				return 0;
1770 			}
1771 			return ptr1 == ptr2 ? 0 : (ptr1 < ptr2 ? -1 : 1);
1772 		}
1773 	}
1774 	zend_throw_error(zend_ffi_exception_ce, "Comparison of incompatible C types");
1775 	return 0;
1776 }
1777 /* }}} */
1778 
zend_ffi_cdata_count_elements(zend_object * obj,zend_long * count)1779 static zend_result zend_ffi_cdata_count_elements(zend_object *obj, zend_long *count) /* {{{ */
1780 {
1781 	zend_ffi_cdata *cdata = (zend_ffi_cdata*)obj;
1782 	zend_ffi_type  *type = ZEND_FFI_TYPE(cdata->type);
1783 
1784 	if (type->kind != ZEND_FFI_TYPE_ARRAY) {
1785 		zend_throw_error(zend_ffi_exception_ce, "Attempt to count() on non C array");
1786 		return FAILURE;
1787 	} else {
1788 		*count = type->array.length;
1789 		return SUCCESS;
1790 	}
1791 }
1792 /* }}} */
1793 
zend_ffi_add(zend_ffi_cdata * base_cdata,zend_ffi_type * base_type,zend_long offset)1794 static zend_object* zend_ffi_add(zend_ffi_cdata *base_cdata, zend_ffi_type *base_type, zend_long offset) /* {{{ */
1795 {
1796 	char *ptr;
1797 	zend_ffi_type *ptr_type;
1798 	zend_ffi_cdata *cdata =
1799 		(zend_ffi_cdata*)zend_ffi_cdata_new(zend_ffi_cdata_ce);
1800 
1801 	if (base_type->kind == ZEND_FFI_TYPE_POINTER) {
1802 		if (ZEND_FFI_TYPE_IS_OWNED(base_cdata->type)) {
1803 			if (!(base_type->attr & ZEND_FFI_ATTR_STORED)) {
1804 				if (GC_REFCOUNT(&base_cdata->std) == 1) {
1805 					/* transfer type ownership */
1806 					base_cdata->type = base_type;
1807 					base_type = ZEND_FFI_TYPE_MAKE_OWNED(base_type);
1808 				} else {
1809 					base_cdata->type = base_type = zend_ffi_remember_type(base_type);
1810 				}
1811 			}
1812 		}
1813 		cdata->type = base_type;
1814 		ptr = (char*)(*(void**)base_cdata->ptr);
1815 		ptr_type = ZEND_FFI_TYPE(base_type)->pointer.type;
1816 	} else {
1817 		zend_ffi_type *new_type = emalloc(sizeof(zend_ffi_type));
1818 
1819 		new_type->kind = ZEND_FFI_TYPE_POINTER;
1820 		new_type->attr = 0;
1821 		new_type->size = sizeof(void*);
1822 		new_type->align = _Alignof(void*);
1823 
1824 		ptr_type = base_type->array.type;
1825 		if (ZEND_FFI_TYPE_IS_OWNED(ptr_type)) {
1826 			ptr_type = ZEND_FFI_TYPE(ptr_type);
1827 			if (!(ptr_type->attr & ZEND_FFI_ATTR_STORED)) {
1828 				if (GC_REFCOUNT(&base_cdata->std) == 1) {
1829 					/* transfer type ownership */
1830 					base_type->array.type = ptr_type;
1831 					ptr_type = ZEND_FFI_TYPE_MAKE_OWNED(ptr_type);
1832 				} else {
1833 					base_type->array.type = ptr_type = zend_ffi_remember_type(ptr_type);
1834 				}
1835 			}
1836 		}
1837 		new_type->pointer.type = ptr_type;
1838 
1839 		cdata->type = ZEND_FFI_TYPE_MAKE_OWNED(new_type);
1840 		ptr = (char*)base_cdata->ptr;
1841 	}
1842 	cdata->ptr = &cdata->ptr_holder;
1843 	cdata->ptr_holder = ptr +
1844 		(ptrdiff_t) (offset * ZEND_FFI_TYPE(ptr_type)->size);
1845 	cdata->flags = base_cdata->flags & ZEND_FFI_FLAG_CONST;
1846 	return &cdata->std;
1847 }
1848 /* }}} */
1849 
zend_ffi_cdata_do_operation(uint8_t opcode,zval * result,zval * op1,zval * op2)1850 static zend_result zend_ffi_cdata_do_operation(uint8_t opcode, zval *result, zval *op1, zval *op2) /* {{{ */
1851 {
1852 	zend_long offset;
1853 
1854 	ZVAL_DEREF(op1);
1855 	ZVAL_DEREF(op2);
1856 	if (Z_TYPE_P(op1) == IS_OBJECT && Z_OBJCE_P(op1) == zend_ffi_cdata_ce) {
1857 		zend_ffi_cdata *cdata1 = (zend_ffi_cdata*)Z_OBJ_P(op1);
1858 		zend_ffi_type *type1 = ZEND_FFI_TYPE(cdata1->type);
1859 
1860 		if (type1->kind == ZEND_FFI_TYPE_POINTER || type1->kind == ZEND_FFI_TYPE_ARRAY) {
1861 			if (opcode == ZEND_ADD) {
1862 				offset = zval_get_long(op2);
1863 				ZVAL_OBJ(result, zend_ffi_add(cdata1, type1, offset));
1864 				if (result == op1) {
1865 					OBJ_RELEASE(&cdata1->std);
1866 				}
1867 				return SUCCESS;
1868 			} else if (opcode == ZEND_SUB) {
1869 				if (Z_TYPE_P(op2) == IS_OBJECT && Z_OBJCE_P(op2) == zend_ffi_cdata_ce) {
1870 					zend_ffi_cdata *cdata2 = (zend_ffi_cdata*)Z_OBJ_P(op2);
1871 					zend_ffi_type *type2 = ZEND_FFI_TYPE(cdata2->type);
1872 
1873 					if (type2->kind == ZEND_FFI_TYPE_POINTER || type2->kind == ZEND_FFI_TYPE_ARRAY) {
1874 						zend_ffi_type *t1, *t2;
1875 						char *p1, *p2;
1876 
1877 						if (type1->kind == ZEND_FFI_TYPE_POINTER) {
1878 							t1 = ZEND_FFI_TYPE(type1->pointer.type);
1879 							p1 = (char*)(*(void**)cdata1->ptr);
1880 						} else {
1881 							t1 = ZEND_FFI_TYPE(type1->array.type);
1882 							p1 = cdata1->ptr;
1883 						}
1884 						if (type2->kind == ZEND_FFI_TYPE_POINTER) {
1885 							t2 = ZEND_FFI_TYPE(type2->pointer.type);
1886 							p2 = (char*)(*(void**)cdata2->ptr);
1887 						} else {
1888 							t2 = ZEND_FFI_TYPE(type2->array.type);
1889 							p2 = cdata2->ptr;
1890 						}
1891 						if (zend_ffi_is_same_type(t1, t2)) {
1892 							ZVAL_LONG(result,
1893 								(zend_long)(p1 - p2) / (zend_long)t1->size);
1894 							return SUCCESS;
1895 						}
1896 					}
1897 				}
1898 				offset = zval_get_long(op2);
1899 				ZVAL_OBJ(result, zend_ffi_add(cdata1, type1, -offset));
1900 				if (result == op1) {
1901 					OBJ_RELEASE(&cdata1->std);
1902 				}
1903 				return SUCCESS;
1904 			}
1905 		}
1906 	} else if (Z_TYPE_P(op2) == IS_OBJECT && Z_OBJCE_P(op2) == zend_ffi_cdata_ce) {
1907 		zend_ffi_cdata *cdata2 = (zend_ffi_cdata*)Z_OBJ_P(op2);
1908 		zend_ffi_type *type2 = ZEND_FFI_TYPE(cdata2->type);
1909 
1910 		if (type2->kind == ZEND_FFI_TYPE_POINTER || type2->kind == ZEND_FFI_TYPE_ARRAY) {
1911 			if (opcode == ZEND_ADD) {
1912 				offset = zval_get_long(op1);
1913 				ZVAL_OBJ(result, zend_ffi_add(cdata2, type2, offset));
1914 				return SUCCESS;
1915 			}
1916 		}
1917 	}
1918 
1919 	return FAILURE;
1920 }
1921 /* }}} */
1922 
1923 typedef struct _zend_ffi_cdata_iterator {
1924 	zend_object_iterator it;
1925 	zend_long key;
1926 	zval value;
1927 	bool by_ref;
1928 } zend_ffi_cdata_iterator;
1929 
zend_ffi_cdata_it_dtor(zend_object_iterator * iter)1930 static void zend_ffi_cdata_it_dtor(zend_object_iterator *iter) /* {{{ */
1931 {
1932 	zval_ptr_dtor(&((zend_ffi_cdata_iterator*)iter)->value);
1933 	zval_ptr_dtor(&iter->data);
1934 }
1935 /* }}} */
1936 
zend_ffi_cdata_it_valid(zend_object_iterator * it)1937 static int zend_ffi_cdata_it_valid(zend_object_iterator *it) /* {{{ */
1938 {
1939 	zend_ffi_cdata_iterator *iter = (zend_ffi_cdata_iterator*)it;
1940 	zend_ffi_cdata *cdata = (zend_ffi_cdata*)Z_OBJ(iter->it.data);
1941 	zend_ffi_type  *type = ZEND_FFI_TYPE(cdata->type);
1942 
1943 	return (iter->key >= 0 && iter->key < type->array.length) ? SUCCESS : FAILURE;
1944 }
1945 /* }}} */
1946 
zend_ffi_cdata_it_get_current_data(zend_object_iterator * it)1947 static zval *zend_ffi_cdata_it_get_current_data(zend_object_iterator *it) /* {{{ */
1948 {
1949 	zend_ffi_cdata_iterator *iter = (zend_ffi_cdata_iterator*)it;
1950 	zend_ffi_cdata *cdata = (zend_ffi_cdata*)Z_OBJ(iter->it.data);
1951 	zend_ffi_type  *type = ZEND_FFI_TYPE(cdata->type);
1952 	zend_ffi_type  *dim_type;
1953 	void *ptr;
1954 
1955 	if (!cdata->ptr) {
1956 		zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
1957 		return &EG(uninitialized_zval);
1958 	}
1959 	dim_type = type->array.type;
1960 	if (ZEND_FFI_TYPE_IS_OWNED(dim_type)) {
1961 		dim_type = ZEND_FFI_TYPE(dim_type);
1962 		if (!(dim_type->attr & ZEND_FFI_ATTR_STORED)
1963 		 && dim_type->kind == ZEND_FFI_TYPE_POINTER) {
1964 			type->array.type = dim_type = zend_ffi_remember_type(dim_type);
1965 		}
1966 	}
1967 	ptr = (void*)((char*)cdata->ptr + dim_type->size * iter->it.index);
1968 
1969 	zval_ptr_dtor(&iter->value);
1970 	zend_ffi_cdata_to_zval(NULL, ptr, dim_type, iter->by_ref ? BP_VAR_RW : BP_VAR_R, &iter->value, (cdata->flags & ZEND_FFI_FLAG_CONST) | (zend_ffi_flags)(type->attr & ZEND_FFI_ATTR_CONST), 0, 0);
1971 	return &iter->value;
1972 }
1973 /* }}} */
1974 
zend_ffi_cdata_it_get_current_key(zend_object_iterator * it,zval * key)1975 static void zend_ffi_cdata_it_get_current_key(zend_object_iterator *it, zval *key) /* {{{ */
1976 {
1977 	zend_ffi_cdata_iterator *iter = (zend_ffi_cdata_iterator*)it;
1978 	ZVAL_LONG(key, iter->key);
1979 }
1980 /* }}} */
1981 
zend_ffi_cdata_it_move_forward(zend_object_iterator * it)1982 static void zend_ffi_cdata_it_move_forward(zend_object_iterator *it) /* {{{ */
1983 {
1984 	zend_ffi_cdata_iterator *iter = (zend_ffi_cdata_iterator*)it;
1985 	iter->key++;
1986 }
1987 /* }}} */
1988 
zend_ffi_cdata_it_rewind(zend_object_iterator * it)1989 static void zend_ffi_cdata_it_rewind(zend_object_iterator *it) /* {{{ */
1990 {
1991 	zend_ffi_cdata_iterator *iter = (zend_ffi_cdata_iterator*)it;
1992 	iter->key = 0;
1993 }
1994 /* }}} */
1995 
1996 static const zend_object_iterator_funcs zend_ffi_cdata_it_funcs = {
1997 	zend_ffi_cdata_it_dtor,
1998 	zend_ffi_cdata_it_valid,
1999 	zend_ffi_cdata_it_get_current_data,
2000 	zend_ffi_cdata_it_get_current_key,
2001 	zend_ffi_cdata_it_move_forward,
2002 	zend_ffi_cdata_it_rewind,
2003 	NULL,
2004 	NULL, /* get_gc */
2005 };
2006 
zend_ffi_cdata_get_iterator(zend_class_entry * ce,zval * object,int by_ref)2007 static zend_object_iterator *zend_ffi_cdata_get_iterator(zend_class_entry *ce, zval *object, int by_ref) /* {{{ */
2008 {
2009 	zend_ffi_cdata *cdata = (zend_ffi_cdata*)Z_OBJ_P(object);
2010 	zend_ffi_type  *type = ZEND_FFI_TYPE(cdata->type);
2011 	zend_ffi_cdata_iterator *iter;
2012 
2013 	if (type->kind != ZEND_FFI_TYPE_ARRAY) {
2014 		zend_throw_error(zend_ffi_exception_ce, "Attempt to iterate on non C array");
2015 		return NULL;
2016 	}
2017 
2018 	iter = emalloc(sizeof(zend_ffi_cdata_iterator));
2019 
2020 	zend_iterator_init(&iter->it);
2021 
2022 	Z_ADDREF_P(object);
2023 	ZVAL_OBJ(&iter->it.data, Z_OBJ_P(object));
2024 	iter->it.funcs = &zend_ffi_cdata_it_funcs;
2025 	iter->key = 0;
2026 	iter->by_ref = by_ref;
2027 	ZVAL_UNDEF(&iter->value);
2028 
2029 	return &iter->it;
2030 }
2031 /* }}} */
2032 
zend_ffi_cdata_get_debug_info(zend_object * obj,int * is_temp)2033 static HashTable *zend_ffi_cdata_get_debug_info(zend_object *obj, int *is_temp) /* {{{ */
2034 {
2035 	zend_ffi_cdata *cdata = (zend_ffi_cdata*)obj;
2036 	zend_ffi_type  *type = ZEND_FFI_TYPE(cdata->type);
2037 	void           *ptr = cdata->ptr;
2038 	HashTable      *ht = NULL;
2039 	zend_string    *key;
2040 	zend_ffi_field *f;
2041 	zend_long       n;
2042 	zval            tmp;
2043 
2044 	if (!cdata->ptr) {
2045 		zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
2046 		return NULL;
2047 	}
2048 
2049 	switch (type->kind) {
2050 		case ZEND_FFI_TYPE_VOID:
2051 			return NULL;
2052 		case ZEND_FFI_TYPE_BOOL:
2053 		case ZEND_FFI_TYPE_CHAR:
2054 		case ZEND_FFI_TYPE_ENUM:
2055 		case ZEND_FFI_TYPE_FLOAT:
2056 		case ZEND_FFI_TYPE_DOUBLE:
2057 #ifdef HAVE_LONG_DOUBLE
2058 		case ZEND_FFI_TYPE_LONGDOUBLE:
2059 #endif
2060 		case ZEND_FFI_TYPE_UINT8:
2061 		case ZEND_FFI_TYPE_SINT8:
2062 		case ZEND_FFI_TYPE_UINT16:
2063 		case ZEND_FFI_TYPE_SINT16:
2064 		case ZEND_FFI_TYPE_UINT32:
2065 		case ZEND_FFI_TYPE_SINT32:
2066 		case ZEND_FFI_TYPE_UINT64:
2067 		case ZEND_FFI_TYPE_SINT64:
2068 			zend_ffi_cdata_to_zval(cdata, ptr, type, BP_VAR_R, &tmp, ZEND_FFI_FLAG_CONST, 0, 0);
2069 			ht = zend_new_array(1);
2070 			zend_hash_str_add(ht, "cdata", sizeof("cdata")-1, &tmp);
2071 			*is_temp = 1;
2072 			return ht;
2073 			break;
2074 		case ZEND_FFI_TYPE_POINTER:
2075 			if (*(void**)ptr == NULL) {
2076 				ZVAL_NULL(&tmp);
2077 				ht = zend_new_array(1);
2078 				zend_hash_index_add_new(ht, 0, &tmp);
2079 				*is_temp = 1;
2080 				return ht;
2081 			} else if (ZEND_FFI_TYPE(type->pointer.type)->kind == ZEND_FFI_TYPE_VOID) {
2082 				ZVAL_LONG(&tmp, (uintptr_t)*(void**)ptr);
2083 				ht = zend_new_array(1);
2084 				zend_hash_index_add_new(ht, 0, &tmp);
2085 				*is_temp = 1;
2086 				return ht;
2087 			} else {
2088 				zend_ffi_cdata_to_zval(NULL, *(void**)ptr, ZEND_FFI_TYPE(type->pointer.type), BP_VAR_R, &tmp, ZEND_FFI_FLAG_CONST, 0, 0);
2089 				ht = zend_new_array(1);
2090 				zend_hash_index_add_new(ht, 0, &tmp);
2091 				*is_temp = 1;
2092 				return ht;
2093 			}
2094 			break;
2095 		case ZEND_FFI_TYPE_STRUCT:
2096 			ht = zend_new_array(zend_hash_num_elements(&type->record.fields));
2097 			ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(&type->record.fields, key, f) {
2098 				if (key) {
2099 					if (!f->bits) {
2100 						void *f_ptr = (void*)(((char*)ptr) + f->offset);
2101 						zend_ffi_cdata_to_zval(NULL, f_ptr, ZEND_FFI_TYPE(f->type), BP_VAR_R, &tmp, ZEND_FFI_FLAG_CONST, 0, type->attr & ZEND_FFI_ATTR_UNION);
2102 						zend_hash_add(ht, key, &tmp);
2103 					} else {
2104 						zend_ffi_bit_field_to_zval(ptr, f, &tmp);
2105 						zend_hash_add(ht, key, &tmp);
2106 					}
2107 				}
2108 			} ZEND_HASH_FOREACH_END();
2109 			*is_temp = 1;
2110 			return ht;
2111 		case ZEND_FFI_TYPE_ARRAY:
2112 			ht = zend_new_array(type->array.length);
2113 			for (n = 0; n < type->array.length; n++) {
2114 				zend_ffi_cdata_to_zval(NULL, ptr, ZEND_FFI_TYPE(type->array.type), BP_VAR_R, &tmp, ZEND_FFI_FLAG_CONST, 0, 0);
2115 				zend_hash_index_add(ht, n, &tmp);
2116 				ptr = (void*)(((char*)ptr) + ZEND_FFI_TYPE(type->array.type)->size);
2117 			}
2118 			*is_temp = 1;
2119 			return ht;
2120 		case ZEND_FFI_TYPE_FUNC:
2121 			ht = zend_new_array(0);
2122 			// TODO: function name ???
2123 			*is_temp = 1;
2124 			return ht;
2125 			break;
2126 		default:
2127 			ZEND_UNREACHABLE();
2128 			break;
2129 	}
2130 	return NULL;
2131 }
2132 /* }}} */
2133 
zend_ffi_cdata_get_closure(zend_object * obj,zend_class_entry ** ce_ptr,zend_function ** fptr_ptr,zend_object ** obj_ptr,bool check_only)2134 static zend_result zend_ffi_cdata_get_closure(zend_object *obj, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zend_object **obj_ptr, bool check_only) /* {{{ */
2135 {
2136 	zend_ffi_cdata *cdata = (zend_ffi_cdata*)obj;
2137 	zend_ffi_type  *type = ZEND_FFI_TYPE(cdata->type);
2138 	zend_function  *func;
2139 
2140 	if (type->kind != ZEND_FFI_TYPE_POINTER) {
2141 		if (!check_only) {
2142 			zend_throw_error(zend_ffi_exception_ce, "Attempt to call non C function pointer");
2143 		}
2144 		return FAILURE;
2145 	}
2146 	type = ZEND_FFI_TYPE(type->pointer.type);
2147 	if (type->kind != ZEND_FFI_TYPE_FUNC) {
2148 		if (!check_only) {
2149 			zend_throw_error(zend_ffi_exception_ce, "Attempt to call non C function pointer");
2150 		}
2151 		return FAILURE;
2152 	}
2153 	if (!cdata->ptr) {
2154 		if (!check_only) {
2155 			zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
2156 		}
2157 		return FAILURE;
2158 	}
2159 
2160 	if (EXPECTED(EG(trampoline).common.function_name == NULL)) {
2161 		func = &EG(trampoline);
2162 	} else {
2163 		func = ecalloc(1, sizeof(zend_internal_function));
2164 	}
2165 	func->type = ZEND_INTERNAL_FUNCTION;
2166 	func->common.arg_flags[0] = 0;
2167 	func->common.arg_flags[1] = 0;
2168 	func->common.arg_flags[2] = 0;
2169 	func->common.fn_flags = ZEND_ACC_CALL_VIA_TRAMPOLINE;
2170 	func->common.function_name = ZSTR_KNOWN(ZEND_STR_MAGIC_INVOKE);
2171 	/* set to 0 to avoid arg_info[] allocation, because all values are passed by value anyway */
2172 	func->common.num_args = 0;
2173 	func->common.required_num_args = type->func.args ? zend_hash_num_elements(type->func.args) : 0;
2174 	func->common.scope = NULL;
2175 	func->common.prototype = NULL;
2176 	func->common.arg_info = NULL;
2177 	func->internal_function.handler = ZEND_FN(ffi_trampoline);
2178 	func->internal_function.module = NULL;
2179 
2180 	func->internal_function.reserved[0] = type;
2181 	func->internal_function.reserved[1] = *(void**)cdata->ptr;
2182 
2183 	*ce_ptr = NULL;
2184 	*fptr_ptr= func;
2185 	*obj_ptr = NULL;
2186 
2187 	return SUCCESS;
2188 }
2189 /* }}} */
2190 
zend_ffi_ctype_new(zend_class_entry * class_type)2191 static zend_object *zend_ffi_ctype_new(zend_class_entry *class_type) /* {{{ */
2192 {
2193 	zend_ffi_ctype *ctype;
2194 
2195 	ctype = emalloc(sizeof(zend_ffi_ctype));
2196 
2197 	zend_ffi_object_init(&ctype->std, class_type);
2198 
2199 	ctype->type = NULL;
2200 
2201 	return &ctype->std;
2202 }
2203 /* }}} */
2204 
zend_ffi_ctype_free_obj(zend_object * object)2205 static void zend_ffi_ctype_free_obj(zend_object *object) /* {{{ */
2206 {
2207 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)object;
2208 
2209 	zend_ffi_type_dtor(ctype->type);
2210 
2211     if (UNEXPECTED(GC_FLAGS(object) & IS_OBJ_WEAKLY_REFERENCED)) {
2212         zend_weakrefs_notify(object);
2213     }
2214 }
2215 /* }}} */
2216 
zend_ffi_is_same_type(zend_ffi_type * type1,zend_ffi_type * type2)2217 static bool zend_ffi_is_same_type(zend_ffi_type *type1, zend_ffi_type *type2) /* {{{ */
2218 {
2219 	while (1) {
2220 		if (type1 == type2) {
2221 			return 1;
2222 		} else if (type1->kind == type2->kind) {
2223 			if (type1->kind < ZEND_FFI_TYPE_POINTER) {
2224 				return 1;
2225 			} else if (type1->kind == ZEND_FFI_TYPE_POINTER) {
2226 				type1 = ZEND_FFI_TYPE(type1->pointer.type);
2227 				type2 = ZEND_FFI_TYPE(type2->pointer.type);
2228 				if (type1->kind == ZEND_FFI_TYPE_VOID ||
2229 				    type2->kind == ZEND_FFI_TYPE_VOID) {
2230 				    return 1;
2231 				}
2232 			} else if (type1->kind == ZEND_FFI_TYPE_ARRAY &&
2233 			           type1->array.length == type2->array.length) {
2234 				type1 = ZEND_FFI_TYPE(type1->array.type);
2235 				type2 = ZEND_FFI_TYPE(type2->array.type);
2236 			} else {
2237 				break;
2238 			}
2239 		} else {
2240 			break;
2241 		}
2242 	}
2243 	return 0;
2244 }
2245 /* }}} */
2246 
zend_ffi_ctype_get_class_name(const zend_object * zobj)2247 static zend_string *zend_ffi_ctype_get_class_name(const zend_object *zobj) /* {{{ */
2248 {
2249 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)zobj;
2250 
2251 	return zend_ffi_get_class_name(zobj->ce->name, ZEND_FFI_TYPE(ctype->type));
2252 }
2253 /* }}} */
2254 
zend_ffi_ctype_compare_objects(zval * o1,zval * o2)2255 static int zend_ffi_ctype_compare_objects(zval *o1, zval *o2) /* {{{ */
2256 {
2257 	if (Z_TYPE_P(o1) == IS_OBJECT && Z_OBJCE_P(o1) == zend_ffi_ctype_ce &&
2258 	    Z_TYPE_P(o2) == IS_OBJECT && Z_OBJCE_P(o2) == zend_ffi_ctype_ce) {
2259 		zend_ffi_ctype *ctype1 = (zend_ffi_ctype*)Z_OBJ_P(o1);
2260 		zend_ffi_ctype *ctype2 = (zend_ffi_ctype*)Z_OBJ_P(o2);
2261 		zend_ffi_type *type1 = ZEND_FFI_TYPE(ctype1->type);
2262 		zend_ffi_type *type2 = ZEND_FFI_TYPE(ctype2->type);
2263 
2264 		if (zend_ffi_is_same_type(type1, type2)) {
2265 			return 0;
2266 		} else {
2267 			return 1;
2268 		}
2269 	}
2270 	zend_throw_error(zend_ffi_exception_ce, "Comparison of incompatible C types");
2271 	return 0;
2272 }
2273 /* }}} */
2274 
zend_ffi_ctype_get_debug_info(zend_object * obj,int * is_temp)2275 static HashTable *zend_ffi_ctype_get_debug_info(zend_object *obj, int *is_temp) /* {{{ */
2276 {
2277 	return NULL;
2278 }
2279 /* }}} */
2280 
zend_ffi_new(zend_class_entry * class_type)2281 static zend_object *zend_ffi_new(zend_class_entry *class_type) /* {{{ */
2282 {
2283 	zend_ffi *ffi;
2284 
2285 	ffi = emalloc(sizeof(zend_ffi));
2286 
2287 	zend_ffi_object_init(&ffi->std, class_type);
2288 
2289 	ffi->lib = NULL;
2290 	ffi->symbols = NULL;
2291 	ffi->tags = NULL;
2292 	ffi->persistent = 0;
2293 
2294 	return &ffi->std;
2295 }
2296 /* }}} */
2297 
_zend_ffi_type_dtor(zend_ffi_type * type)2298 static void _zend_ffi_type_dtor(zend_ffi_type *type) /* {{{ */
2299 {
2300 	type = ZEND_FFI_TYPE(type);
2301 
2302 	switch (type->kind) {
2303 		case ZEND_FFI_TYPE_ENUM:
2304 			if (type->enumeration.tag_name) {
2305 				zend_string_release(type->enumeration.tag_name);
2306 			}
2307 			break;
2308 		case ZEND_FFI_TYPE_STRUCT:
2309 			if (type->record.tag_name) {
2310 				zend_string_release(type->record.tag_name);
2311 			}
2312 			zend_hash_destroy(&type->record.fields);
2313 			break;
2314 		case ZEND_FFI_TYPE_POINTER:
2315 			zend_ffi_type_dtor(type->pointer.type);
2316 			break;
2317 		case ZEND_FFI_TYPE_ARRAY:
2318 			zend_ffi_type_dtor(type->array.type);
2319 			break;
2320 		case ZEND_FFI_TYPE_FUNC:
2321 			if (type->func.args) {
2322 				zend_hash_destroy(type->func.args);
2323 				pefree(type->func.args, type->attr & ZEND_FFI_ATTR_PERSISTENT);
2324 			}
2325 			zend_ffi_type_dtor(type->func.ret_type);
2326 			break;
2327 		default:
2328 			break;
2329 	}
2330 	pefree(type, type->attr & ZEND_FFI_ATTR_PERSISTENT);
2331 }
2332 /* }}} */
2333 
zend_ffi_type_hash_dtor(zval * zv)2334 static void zend_ffi_type_hash_dtor(zval *zv) /* {{{ */
2335 {
2336 	zend_ffi_type *type = Z_PTR_P(zv);
2337 	zend_ffi_type_dtor(type);
2338 }
2339 /* }}} */
2340 
zend_ffi_field_hash_dtor(zval * zv)2341 static void zend_ffi_field_hash_dtor(zval *zv) /* {{{ */
2342 {
2343 	zend_ffi_field *field = Z_PTR_P(zv);
2344 	zend_ffi_type_dtor(field->type);
2345 	efree(field);
2346 }
2347 /* }}} */
2348 
zend_ffi_field_hash_persistent_dtor(zval * zv)2349 static void zend_ffi_field_hash_persistent_dtor(zval *zv) /* {{{ */
2350 {
2351 	zend_ffi_field *field = Z_PTR_P(zv);
2352 	zend_ffi_type_dtor(field->type);
2353 	free(field);
2354 }
2355 /* }}} */
2356 
zend_ffi_symbol_hash_dtor(zval * zv)2357 static void zend_ffi_symbol_hash_dtor(zval *zv) /* {{{ */
2358 {
2359 	zend_ffi_symbol *sym = Z_PTR_P(zv);
2360 	zend_ffi_type_dtor(sym->type);
2361 	efree(sym);
2362 }
2363 /* }}} */
2364 
zend_ffi_symbol_hash_persistent_dtor(zval * zv)2365 static void zend_ffi_symbol_hash_persistent_dtor(zval *zv) /* {{{ */
2366 {
2367 	zend_ffi_symbol *sym = Z_PTR_P(zv);
2368 	zend_ffi_type_dtor(sym->type);
2369 	free(sym);
2370 }
2371 /* }}} */
2372 
zend_ffi_tag_hash_dtor(zval * zv)2373 static void zend_ffi_tag_hash_dtor(zval *zv) /* {{{ */
2374 {
2375 	zend_ffi_tag *tag = Z_PTR_P(zv);
2376 	zend_ffi_type_dtor(tag->type);
2377 	efree(tag);
2378 }
2379 /* }}} */
2380 
zend_ffi_tag_hash_persistent_dtor(zval * zv)2381 static void zend_ffi_tag_hash_persistent_dtor(zval *zv) /* {{{ */
2382 {
2383 	zend_ffi_tag *tag = Z_PTR_P(zv);
2384 	zend_ffi_type_dtor(tag->type);
2385 	free(tag);
2386 }
2387 /* }}} */
2388 
zend_ffi_cdata_dtor(zend_ffi_cdata * cdata)2389 static void zend_ffi_cdata_dtor(zend_ffi_cdata *cdata) /* {{{ */
2390 {
2391 	zend_ffi_type_dtor(cdata->type);
2392 	if (cdata->flags & ZEND_FFI_FLAG_OWNED) {
2393 		if (cdata->ptr != (void*)&cdata->ptr_holder) {
2394 			pefree(cdata->ptr, cdata->flags & ZEND_FFI_FLAG_PERSISTENT);
2395 		} else {
2396 			pefree(cdata->ptr_holder, cdata->flags & ZEND_FFI_FLAG_PERSISTENT);
2397 		}
2398 	}
2399 }
2400 /* }}} */
2401 
zend_ffi_scope_hash_dtor(zval * zv)2402 static void zend_ffi_scope_hash_dtor(zval *zv) /* {{{ */
2403 {
2404 	zend_ffi_scope *scope = Z_PTR_P(zv);
2405 	if (scope->symbols) {
2406 		zend_hash_destroy(scope->symbols);
2407 		free(scope->symbols);
2408 	}
2409 	if (scope->tags) {
2410 		zend_hash_destroy(scope->tags);
2411 		free(scope->tags);
2412 	}
2413 	free(scope);
2414 }
2415 /* }}} */
2416 
zend_ffi_free_obj(zend_object * object)2417 static void zend_ffi_free_obj(zend_object *object) /* {{{ */
2418 {
2419 	zend_ffi *ffi = (zend_ffi*)object;
2420 
2421 	if (ffi->persistent) {
2422 		return;
2423 	}
2424 
2425 	if (ffi->lib) {
2426 		DL_UNLOAD(ffi->lib);
2427 		ffi->lib = NULL;
2428 	}
2429 
2430 	if (ffi->symbols) {
2431 		zend_hash_destroy(ffi->symbols);
2432 		efree(ffi->symbols);
2433 	}
2434 
2435 	if (ffi->tags) {
2436 		zend_hash_destroy(ffi->tags);
2437 		efree(ffi->tags);
2438 	}
2439 
2440     if (UNEXPECTED(GC_FLAGS(object) & IS_OBJ_WEAKLY_REFERENCED)) {
2441         zend_weakrefs_notify(object);
2442     }
2443 }
2444 /* }}} */
2445 
zend_ffi_cdata_free_obj(zend_object * object)2446 static void zend_ffi_cdata_free_obj(zend_object *object) /* {{{ */
2447 {
2448 	zend_ffi_cdata *cdata = (zend_ffi_cdata*)object;
2449 
2450 	zend_ffi_cdata_dtor(cdata);
2451 
2452     if (UNEXPECTED(GC_FLAGS(object) & IS_OBJ_WEAKLY_REFERENCED)) {
2453         zend_weakrefs_notify(object);
2454     }
2455 }
2456 /* }}} */
2457 
zend_ffi_cdata_clone_obj(zend_object * obj)2458 static zend_object *zend_ffi_cdata_clone_obj(zend_object *obj) /* {{{ */
2459 {
2460 	zend_ffi_cdata *old_cdata = (zend_ffi_cdata*)obj;
2461 	zend_ffi_type *type = ZEND_FFI_TYPE(old_cdata->type);
2462 	zend_ffi_cdata *new_cdata;
2463 
2464 	new_cdata = (zend_ffi_cdata*)zend_ffi_cdata_new(zend_ffi_cdata_ce);
2465 	if (type->kind < ZEND_FFI_TYPE_POINTER) {
2466 		new_cdata->std.handlers = &zend_ffi_cdata_value_handlers;
2467 	}
2468 	new_cdata->type = type;
2469 	new_cdata->ptr = emalloc(type->size);
2470 	memcpy(new_cdata->ptr, old_cdata->ptr, type->size);
2471 	new_cdata->flags |= ZEND_FFI_FLAG_OWNED;
2472 
2473 	return &new_cdata->std;
2474 }
2475 /* }}} */
2476 
zend_ffi_read_var(zend_object * obj,zend_string * var_name,int read_type,void ** cache_slot,zval * rv)2477 static zval *zend_ffi_read_var(zend_object *obj, zend_string *var_name, int read_type, void **cache_slot, zval *rv) /* {{{ */
2478 {
2479 	zend_ffi        *ffi = (zend_ffi*)obj;
2480 	zend_ffi_symbol *sym = NULL;
2481 
2482 	if (ffi->symbols) {
2483 		sym = zend_hash_find_ptr(ffi->symbols, var_name);
2484 		if (sym && sym->kind != ZEND_FFI_SYM_VAR && sym->kind != ZEND_FFI_SYM_CONST && sym->kind != ZEND_FFI_SYM_FUNC) {
2485 			sym = NULL;
2486 		}
2487 	}
2488 	if (!sym) {
2489 		zend_throw_error(zend_ffi_exception_ce, "Attempt to read undefined C variable '%s'", ZSTR_VAL(var_name));
2490 		return &EG(uninitialized_zval);
2491 	}
2492 
2493 	if (sym->kind == ZEND_FFI_SYM_VAR) {
2494 		zend_ffi_cdata_to_zval(NULL, sym->addr, ZEND_FFI_TYPE(sym->type), read_type, rv, (zend_ffi_flags)sym->is_const, 0, 0);
2495 	} else if (sym->kind == ZEND_FFI_SYM_FUNC) {
2496 		zend_ffi_cdata *cdata;
2497 		zend_ffi_type *new_type = emalloc(sizeof(zend_ffi_type));
2498 
2499 		new_type->kind = ZEND_FFI_TYPE_POINTER;
2500 		new_type->attr = 0;
2501 		new_type->size = sizeof(void*);
2502 		new_type->align = _Alignof(void*);
2503 		new_type->pointer.type = ZEND_FFI_TYPE(sym->type);
2504 
2505 		cdata = emalloc(sizeof(zend_ffi_cdata));
2506 		zend_ffi_object_init(&cdata->std, zend_ffi_cdata_ce);
2507 		cdata->type = ZEND_FFI_TYPE_MAKE_OWNED(new_type);
2508 		cdata->flags = ZEND_FFI_FLAG_CONST;
2509 		cdata->ptr_holder = sym->addr;
2510 		cdata->ptr = &cdata->ptr_holder;
2511 		ZVAL_OBJ(rv, &cdata->std);
2512 	} else {
2513 		ZVAL_LONG(rv, sym->value);
2514 	}
2515 
2516 	return rv;
2517 }
2518 /* }}} */
2519 
zend_ffi_write_var(zend_object * obj,zend_string * var_name,zval * value,void ** cache_slot)2520 static zval *zend_ffi_write_var(zend_object *obj, zend_string *var_name, zval *value, void **cache_slot) /* {{{ */
2521 {
2522 	zend_ffi        *ffi = (zend_ffi*)obj;
2523 	zend_ffi_symbol *sym = NULL;
2524 
2525 	if (ffi->symbols) {
2526 		sym = zend_hash_find_ptr(ffi->symbols, var_name);
2527 		if (sym && sym->kind != ZEND_FFI_SYM_VAR) {
2528 			sym = NULL;
2529 		}
2530 	}
2531 	if (!sym) {
2532 		zend_throw_error(zend_ffi_exception_ce, "Attempt to assign undefined C variable '%s'", ZSTR_VAL(var_name));
2533 		return value;
2534 	}
2535 
2536 	if (sym->is_const) {
2537 		zend_throw_error(zend_ffi_exception_ce, "Attempt to assign read-only C variable '%s'", ZSTR_VAL(var_name));
2538 		return value;
2539 	}
2540 
2541 	zend_ffi_zval_to_cdata(sym->addr, ZEND_FFI_TYPE(sym->type), value);
2542 	return value;
2543 }
2544 /* }}} */
2545 
zend_ffi_pass_arg(zval * arg,zend_ffi_type * type,ffi_type ** pass_type,void ** arg_values,uint32_t n,zend_execute_data * execute_data)2546 static zend_result zend_ffi_pass_arg(zval *arg, zend_ffi_type *type, ffi_type **pass_type, void **arg_values, uint32_t n, zend_execute_data *execute_data) /* {{{ */
2547 {
2548 	zend_long lval;
2549 	double dval;
2550 	zend_string *str, *tmp_str;
2551 	zend_ffi_type_kind kind = type->kind;
2552 
2553 	ZVAL_DEREF(arg);
2554 
2555 again:
2556 	switch (kind) {
2557 		case ZEND_FFI_TYPE_FLOAT:
2558 			dval = zval_get_double(arg);
2559 			*pass_type = &ffi_type_float;
2560 			*(float*)arg_values[n] = (float)dval;
2561 			break;
2562 		case ZEND_FFI_TYPE_DOUBLE:
2563 			dval = zval_get_double(arg);
2564 			*pass_type = &ffi_type_double;
2565 			*(double*)arg_values[n] = dval;
2566 			break;
2567 #ifdef HAVE_LONG_DOUBLE
2568 		case ZEND_FFI_TYPE_LONGDOUBLE:
2569 			dval = zval_get_double(arg);
2570 			*pass_type = &ffi_type_double;
2571 			*(long double*)arg_values[n] = (long double)dval;
2572 			break;
2573 #endif
2574 		case ZEND_FFI_TYPE_UINT8:
2575 			lval = zval_get_long(arg);
2576 			*pass_type = &ffi_type_uint8;
2577 			*(uint8_t*)arg_values[n] = (uint8_t)lval;
2578 			break;
2579 		case ZEND_FFI_TYPE_SINT8:
2580 			lval = zval_get_long(arg);
2581 			*pass_type = &ffi_type_sint8;
2582 			*(int8_t*)arg_values[n] = (int8_t)lval;
2583 			break;
2584 		case ZEND_FFI_TYPE_UINT16:
2585 			lval = zval_get_long(arg);
2586 			*pass_type = &ffi_type_uint16;
2587 			*(uint16_t*)arg_values[n] = (uint16_t)lval;
2588 			break;
2589 		case ZEND_FFI_TYPE_SINT16:
2590 			lval = zval_get_long(arg);
2591 			*pass_type = &ffi_type_sint16;
2592 			*(int16_t*)arg_values[n] = (int16_t)lval;
2593 			break;
2594 		case ZEND_FFI_TYPE_UINT32:
2595 			lval = zval_get_long(arg);
2596 			*pass_type = &ffi_type_uint32;
2597 			*(uint32_t*)arg_values[n] = (uint32_t)lval;
2598 			break;
2599 		case ZEND_FFI_TYPE_SINT32:
2600 			lval = zval_get_long(arg);
2601 			*pass_type = &ffi_type_sint32;
2602 			*(int32_t*)arg_values[n] = (int32_t)lval;
2603 			break;
2604 		case ZEND_FFI_TYPE_UINT64:
2605 			lval = zval_get_long(arg);
2606 			*pass_type = &ffi_type_uint64;
2607 			*(uint64_t*)arg_values[n] = (uint64_t)lval;
2608 			break;
2609 		case ZEND_FFI_TYPE_SINT64:
2610 			lval = zval_get_long(arg);
2611 			*pass_type = &ffi_type_sint64;
2612 			*(int64_t*)arg_values[n] = (int64_t)lval;
2613 			break;
2614 		case ZEND_FFI_TYPE_POINTER:
2615 			*pass_type = &ffi_type_pointer;
2616 			if (Z_TYPE_P(arg) == IS_NULL) {
2617 				*(void**)arg_values[n] = NULL;
2618 				return SUCCESS;
2619 			} else if (Z_TYPE_P(arg) == IS_STRING
2620 			        && ((ZEND_FFI_TYPE(type->pointer.type)->kind == ZEND_FFI_TYPE_CHAR)
2621 			         || (ZEND_FFI_TYPE(type->pointer.type)->kind == ZEND_FFI_TYPE_VOID))) {
2622 				*(void**)arg_values[n] = Z_STRVAL_P(arg);
2623 				return SUCCESS;
2624 			} else if (Z_TYPE_P(arg) == IS_OBJECT && Z_OBJCE_P(arg) == zend_ffi_cdata_ce) {
2625 				zend_ffi_cdata *cdata = (zend_ffi_cdata*)Z_OBJ_P(arg);
2626 
2627 				if (zend_ffi_is_compatible_type(type, ZEND_FFI_TYPE(cdata->type))) {
2628 					if (ZEND_FFI_TYPE(cdata->type)->kind == ZEND_FFI_TYPE_POINTER) {
2629 						if (!cdata->ptr) {
2630 							zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
2631 							return FAILURE;
2632 						}
2633 						*(void**)arg_values[n] = *(void**)cdata->ptr;
2634 					} else {
2635 						*(void**)arg_values[n] = cdata->ptr;
2636 					}
2637 					return SUCCESS;
2638 				}
2639 #if FFI_CLOSURES
2640 			} else if (ZEND_FFI_TYPE(type->pointer.type)->kind == ZEND_FFI_TYPE_FUNC) {
2641 				void *callback = zend_ffi_create_callback(ZEND_FFI_TYPE(type->pointer.type), arg);
2642 
2643 				if (callback) {
2644 					*(void**)arg_values[n] = callback;
2645 					break;
2646 				} else {
2647 					return FAILURE;
2648 				}
2649 #endif
2650 			}
2651 			zend_ffi_pass_incompatible(arg, type, n, execute_data);
2652 			return FAILURE;
2653 		case ZEND_FFI_TYPE_BOOL:
2654 			*pass_type = &ffi_type_uint8;
2655 			*(uint8_t*)arg_values[n] = zend_is_true(arg);
2656 			break;
2657 		case ZEND_FFI_TYPE_CHAR:
2658 			str = zval_get_tmp_string(arg, &tmp_str);
2659 			*pass_type = &ffi_type_sint8;
2660 			*(char*)arg_values[n] = ZSTR_VAL(str)[0];
2661 			if (ZSTR_LEN(str) != 1) {
2662 				zend_ffi_pass_incompatible(arg, type, n, execute_data);
2663 			}
2664 			zend_tmp_string_release(tmp_str);
2665 			break;
2666 		case ZEND_FFI_TYPE_ENUM:
2667 			kind = type->enumeration.kind;
2668 			goto again;
2669 		case ZEND_FFI_TYPE_STRUCT:
2670 			if (Z_TYPE_P(arg) == IS_OBJECT && Z_OBJCE_P(arg) == zend_ffi_cdata_ce) {
2671 				zend_ffi_cdata *cdata = (zend_ffi_cdata*)Z_OBJ_P(arg);
2672 
2673 				if (zend_ffi_is_compatible_type(type, ZEND_FFI_TYPE(cdata->type))) {
2674 					*pass_type = zend_ffi_make_fake_struct_type(type);
2675 					arg_values[n] = cdata->ptr;
2676 					break;
2677 				}
2678 			}
2679 			zend_ffi_pass_incompatible(arg, type, n, execute_data);
2680 			return FAILURE;
2681 		default:
2682 			zend_ffi_pass_unsupported(type);
2683 			return FAILURE;
2684 	}
2685 	return SUCCESS;
2686 }
2687 /* }}} */
2688 
zend_ffi_pass_var_arg(zval * arg,ffi_type ** pass_type,void ** arg_values,uint32_t n,zend_execute_data * execute_data)2689 static zend_result zend_ffi_pass_var_arg(zval *arg, ffi_type **pass_type, void **arg_values, uint32_t n, zend_execute_data *execute_data) /* {{{ */
2690 {
2691 	ZVAL_DEREF(arg);
2692 	switch (Z_TYPE_P(arg)) {
2693 		case IS_NULL:
2694 			*pass_type = &ffi_type_pointer;
2695 			*(void**)arg_values[n] = NULL;
2696 			break;
2697 		case IS_FALSE:
2698 			*pass_type = &ffi_type_uint8;
2699 			*(uint8_t*)arg_values[n] = 0;
2700 			break;
2701 		case IS_TRUE:
2702 			*pass_type = &ffi_type_uint8;
2703 			*(uint8_t*)arg_values[n] = 1;
2704 			break;
2705 		case IS_LONG:
2706 			if (sizeof(zend_long) == 4) {
2707 				*pass_type = &ffi_type_sint32;
2708 				*(int32_t*)arg_values[n] = Z_LVAL_P(arg);
2709 			} else {
2710 				*pass_type = &ffi_type_sint64;
2711 				*(int64_t*)arg_values[n] = Z_LVAL_P(arg);
2712 			}
2713 			break;
2714 		case IS_DOUBLE:
2715 			*pass_type = &ffi_type_double;
2716 			*(double*)arg_values[n] = Z_DVAL_P(arg);
2717 			break;
2718 		case IS_STRING:
2719 			*pass_type = &ffi_type_pointer;
2720 			*(char**)arg_values[n] = Z_STRVAL_P(arg);
2721 			break;
2722 		case IS_OBJECT:
2723 			if (Z_OBJCE_P(arg) == zend_ffi_cdata_ce) {
2724 				zend_ffi_cdata *cdata = (zend_ffi_cdata*)Z_OBJ_P(arg);
2725 				zend_ffi_type *type = ZEND_FFI_TYPE(cdata->type);
2726 
2727 				return zend_ffi_pass_arg(arg, type, pass_type, arg_values, n, execute_data);
2728 			}
2729 			ZEND_FALLTHROUGH;
2730 		default:
2731 			zend_throw_error(zend_ffi_exception_ce, "Unsupported argument type");
2732 			return FAILURE;
2733 	}
2734 	return SUCCESS;
2735 }
2736 /* }}} */
2737 
ZEND_FUNCTION(ffi_trampoline)2738 static ZEND_FUNCTION(ffi_trampoline) /* {{{ */
2739 {
2740 	zend_ffi_type *type = EX(func)->internal_function.reserved[0];
2741 	void *addr = EX(func)->internal_function.reserved[1];
2742 	ffi_cif cif;
2743 	ffi_type *ret_type = NULL;
2744 	ffi_type **arg_types = NULL;
2745 	void **arg_values = NULL;
2746 	uint32_t n, arg_count;
2747 	void *ret;
2748 	zend_ffi_type *arg_type;
2749 	ALLOCA_FLAG(arg_types_use_heap = 0)
2750 	ALLOCA_FLAG(arg_values_use_heap = 0)
2751 	ALLOCA_FLAG(ret_use_heap = 0)
2752 
2753 	ZEND_ASSERT(type->kind == ZEND_FFI_TYPE_FUNC);
2754 	arg_count = type->func.args ? zend_hash_num_elements(type->func.args) : 0;
2755 	if (type->attr & ZEND_FFI_ATTR_VARIADIC) {
2756 		if (arg_count > EX_NUM_ARGS()) {
2757 			zend_throw_error(zend_ffi_exception_ce, "Incorrect number of arguments for C function '%s', expecting at least %d parameter%s", ZSTR_VAL(EX(func)->internal_function.function_name), arg_count, (arg_count != 1) ? "s" : "");
2758 			goto exit;
2759 		}
2760 		if (EX_NUM_ARGS()) {
2761 			arg_types = do_alloca(
2762 				sizeof(ffi_type*) * EX_NUM_ARGS(), arg_types_use_heap);
2763 			arg_values = do_alloca(
2764 				(sizeof(void*) + ZEND_FFI_SIZEOF_ARG) * EX_NUM_ARGS(), arg_values_use_heap);
2765 			n = 0;
2766 			if (type->func.args) {
2767 				ZEND_HASH_PACKED_FOREACH_PTR(type->func.args, arg_type) {
2768 					arg_type = ZEND_FFI_TYPE(arg_type);
2769 					arg_values[n] = ((char*)arg_values) + (sizeof(void*) * EX_NUM_ARGS()) + (ZEND_FFI_SIZEOF_ARG * n);
2770 					if (zend_ffi_pass_arg(EX_VAR_NUM(n), arg_type, &arg_types[n], arg_values, n, execute_data) == FAILURE) {
2771 						free_alloca(arg_types, arg_types_use_heap);
2772 						free_alloca(arg_values, arg_values_use_heap);
2773 						goto exit;
2774 					}
2775 					n++;
2776 				} ZEND_HASH_FOREACH_END();
2777 			}
2778 			for (; n < EX_NUM_ARGS(); n++) {
2779 				arg_values[n] = ((char*)arg_values) + (sizeof(void*) * EX_NUM_ARGS()) + (ZEND_FFI_SIZEOF_ARG * n);
2780 				if (zend_ffi_pass_var_arg(EX_VAR_NUM(n), &arg_types[n], arg_values, n, execute_data) == FAILURE) {
2781 					free_alloca(arg_types, arg_types_use_heap);
2782 					free_alloca(arg_values, arg_values_use_heap);
2783 					goto exit;
2784 				}
2785 			}
2786 		}
2787 		ret_type = zend_ffi_get_type(ZEND_FFI_TYPE(type->func.ret_type));
2788 		if (!ret_type) {
2789 			zend_ffi_return_unsupported(type->func.ret_type);
2790 			free_alloca(arg_types, arg_types_use_heap);
2791 			free_alloca(arg_values, arg_values_use_heap);
2792 			goto exit;
2793 		}
2794 		if (ffi_prep_cif_var(&cif, type->func.abi, arg_count, EX_NUM_ARGS(), ret_type, arg_types) != FFI_OK) {
2795 			zend_throw_error(zend_ffi_exception_ce, "Cannot prepare callback CIF");
2796 			free_alloca(arg_types, arg_types_use_heap);
2797 			free_alloca(arg_values, arg_values_use_heap);
2798 			goto exit;
2799 		}
2800 	} else {
2801 		if (arg_count != EX_NUM_ARGS()) {
2802 			zend_throw_error(zend_ffi_exception_ce, "Incorrect number of arguments for C function '%s', expecting exactly %d parameter%s", ZSTR_VAL(EX(func)->internal_function.function_name), arg_count, (arg_count != 1) ? "s" : "");
2803 			goto exit;
2804 		}
2805 		if (EX_NUM_ARGS()) {
2806 			arg_types = do_alloca(
2807 				(sizeof(ffi_type*) + sizeof(ffi_type)) * EX_NUM_ARGS(), arg_types_use_heap);
2808 			arg_values = do_alloca(
2809 				(sizeof(void*) + ZEND_FFI_SIZEOF_ARG) * EX_NUM_ARGS(), arg_values_use_heap);
2810 			n = 0;
2811 			if (type->func.args) {
2812 				ZEND_HASH_PACKED_FOREACH_PTR(type->func.args, arg_type) {
2813 					arg_type = ZEND_FFI_TYPE(arg_type);
2814 					arg_values[n] = ((char*)arg_values) + (sizeof(void*) * EX_NUM_ARGS()) + (ZEND_FFI_SIZEOF_ARG * n);
2815 					if (zend_ffi_pass_arg(EX_VAR_NUM(n), arg_type, &arg_types[n], arg_values, n, execute_data) == FAILURE) {
2816 						free_alloca(arg_types, arg_types_use_heap);
2817 						free_alloca(arg_values, arg_values_use_heap);
2818 						goto exit;
2819 					}
2820 					n++;
2821 				} ZEND_HASH_FOREACH_END();
2822 			}
2823 		}
2824 		ret_type = zend_ffi_get_type(ZEND_FFI_TYPE(type->func.ret_type));
2825 		if (!ret_type) {
2826 			zend_ffi_return_unsupported(type->func.ret_type);
2827 			free_alloca(arg_types, arg_types_use_heap);
2828 			free_alloca(arg_values, arg_values_use_heap);
2829 			goto exit;
2830 		}
2831 		if (ffi_prep_cif(&cif, type->func.abi, arg_count, ret_type, arg_types) != FFI_OK) {
2832 			zend_throw_error(zend_ffi_exception_ce, "Cannot prepare callback CIF");
2833 			free_alloca(arg_types, arg_types_use_heap);
2834 			free_alloca(arg_values, arg_values_use_heap);
2835 			goto exit;
2836 		}
2837 	}
2838 
2839 	ret = do_alloca(MAX(ret_type->size, sizeof(ffi_arg)), ret_use_heap);
2840 	ffi_call(&cif, addr, ret, arg_values);
2841 
2842 	for (n = 0; n < arg_count; n++) {
2843 		if (arg_types[n]->type == FFI_TYPE_STRUCT) {
2844 			efree(arg_types[n]);
2845 		}
2846 	}
2847 	if (ret_type->type == FFI_TYPE_STRUCT) {
2848 		efree(ret_type);
2849 	}
2850 
2851 	if (EX_NUM_ARGS()) {
2852 		free_alloca(arg_types, arg_types_use_heap);
2853 		free_alloca(arg_values, arg_values_use_heap);
2854 	}
2855 
2856 	if (ZEND_FFI_TYPE(type->func.ret_type)->kind != ZEND_FFI_TYPE_VOID) {
2857 		zend_ffi_cdata_to_zval(NULL, ret, ZEND_FFI_TYPE(type->func.ret_type), BP_VAR_R, return_value, 0, 1, 0);
2858 	} else {
2859 		ZVAL_NULL(return_value);
2860 	}
2861 	free_alloca(ret, ret_use_heap);
2862 
2863 exit:
2864 	zend_string_release(EX(func)->common.function_name);
2865 	if (EX(func)->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) {
2866 		zend_free_trampoline(EX(func));
2867 		EX(func) = NULL;
2868 	}
2869 }
2870 /* }}} */
2871 
zend_ffi_get_func(zend_object ** obj,zend_string * name,const zval * key)2872 static zend_function *zend_ffi_get_func(zend_object **obj, zend_string *name, const zval *key) /* {{{ */
2873 {
2874 	zend_ffi        *ffi = (zend_ffi*)*obj;
2875 	zend_ffi_symbol *sym = NULL;
2876 	zend_function   *func;
2877 	zend_ffi_type   *type;
2878 
2879 	if (ZSTR_LEN(name) == sizeof("new") -1
2880 	 && (ZSTR_VAL(name)[0] == 'n' || ZSTR_VAL(name)[0] == 'N')
2881 	 && (ZSTR_VAL(name)[1] == 'e' || ZSTR_VAL(name)[1] == 'E')
2882 	 && (ZSTR_VAL(name)[2] == 'w' || ZSTR_VAL(name)[2] == 'W')) {
2883 		return (zend_function*)&zend_ffi_new_fn;
2884 	} else if (ZSTR_LEN(name) == sizeof("cast") -1
2885 	 && (ZSTR_VAL(name)[0] == 'c' || ZSTR_VAL(name)[0] == 'C')
2886 	 && (ZSTR_VAL(name)[1] == 'a' || ZSTR_VAL(name)[1] == 'A')
2887 	 && (ZSTR_VAL(name)[2] == 's' || ZSTR_VAL(name)[2] == 'S')
2888 	 && (ZSTR_VAL(name)[3] == 't' || ZSTR_VAL(name)[3] == 'T')) {
2889 		return (zend_function*)&zend_ffi_cast_fn;
2890 	} else if (ZSTR_LEN(name) == sizeof("type") -1
2891 	 && (ZSTR_VAL(name)[0] == 't' || ZSTR_VAL(name)[0] == 'T')
2892 	 && (ZSTR_VAL(name)[1] == 'y' || ZSTR_VAL(name)[1] == 'Y')
2893 	 && (ZSTR_VAL(name)[2] == 'p' || ZSTR_VAL(name)[2] == 'P')
2894 	 && (ZSTR_VAL(name)[3] == 'e' || ZSTR_VAL(name)[3] == 'E')) {
2895 		return (zend_function*)&zend_ffi_type_fn;
2896 	}
2897 
2898 	if (ffi->symbols) {
2899 		sym = zend_hash_find_ptr(ffi->symbols, name);
2900 		if (sym && sym->kind != ZEND_FFI_SYM_FUNC) {
2901 			sym = NULL;
2902 		}
2903 	}
2904 	if (!sym) {
2905 		zend_throw_error(zend_ffi_exception_ce, "Attempt to call undefined C function '%s'", ZSTR_VAL(name));
2906 		return NULL;
2907 	}
2908 
2909 	type = ZEND_FFI_TYPE(sym->type);
2910 	ZEND_ASSERT(type->kind == ZEND_FFI_TYPE_FUNC);
2911 
2912 	if (EXPECTED(EG(trampoline).common.function_name == NULL)) {
2913 		func = &EG(trampoline);
2914 	} else {
2915 		func = ecalloc(1, sizeof(zend_internal_function));
2916 	}
2917 	func->common.type = ZEND_INTERNAL_FUNCTION;
2918 	func->common.arg_flags[0] = 0;
2919 	func->common.arg_flags[1] = 0;
2920 	func->common.arg_flags[2] = 0;
2921 	func->common.fn_flags = ZEND_ACC_CALL_VIA_TRAMPOLINE;
2922 	func->common.function_name = zend_string_copy(name);
2923 	/* set to 0 to avoid arg_info[] allocation, because all values are passed by value anyway */
2924 	func->common.num_args = 0;
2925 	func->common.required_num_args = type->func.args ? zend_hash_num_elements(type->func.args) : 0;
2926 	func->common.scope = NULL;
2927 	func->common.prototype = NULL;
2928 	func->common.arg_info = NULL;
2929 	func->internal_function.handler = ZEND_FN(ffi_trampoline);
2930 	func->internal_function.module = NULL;
2931 
2932 	func->internal_function.reserved[0] = type;
2933 	func->internal_function.reserved[1] = sym->addr;
2934 
2935 	return func;
2936 }
2937 /* }}} */
2938 
zend_ffi_disabled(void)2939 static zend_never_inline int zend_ffi_disabled(void) /* {{{ */
2940 {
2941 	zend_throw_error(zend_ffi_exception_ce, "FFI API is restricted by \"ffi.enable\" configuration directive");
2942 	return 0;
2943 }
2944 /* }}} */
2945 
zend_ffi_validate_api_restriction(zend_execute_data * execute_data)2946 static zend_always_inline bool zend_ffi_validate_api_restriction(zend_execute_data *execute_data) /* {{{ */
2947 {
2948 	if (EXPECTED(FFI_G(restriction) > ZEND_FFI_ENABLED)) {
2949 		ZEND_ASSERT(FFI_G(restriction) == ZEND_FFI_PRELOAD);
2950 		if (FFI_G(is_cli)
2951 		 || (execute_data->prev_execute_data
2952 		  && (execute_data->prev_execute_data->func->common.fn_flags & ZEND_ACC_PRELOADED))
2953 		 || (CG(compiler_options) & ZEND_COMPILE_PRELOAD)) {
2954 			return 1;
2955 		}
2956 	} else if (EXPECTED(FFI_G(restriction) == ZEND_FFI_ENABLED)) {
2957 		return 1;
2958 	}
2959 	return zend_ffi_disabled();
2960 }
2961 /* }}} */
2962 
2963 #define ZEND_FFI_VALIDATE_API_RESTRICTION() do { \
2964 		if (UNEXPECTED(!zend_ffi_validate_api_restriction(execute_data))) { \
2965 			RETURN_THROWS(); \
2966 		} \
2967 	} while (0)
2968 
ZEND_METHOD(FFI,cdef)2969 ZEND_METHOD(FFI, cdef) /* {{{ */
2970 {
2971 	zend_string *code = NULL;
2972 	zend_string *lib = NULL;
2973 	zend_ffi *ffi = NULL;
2974 	DL_HANDLE handle = NULL;
2975 	char *err;
2976 	void *addr;
2977 
2978 	ZEND_FFI_VALIDATE_API_RESTRICTION();
2979 	ZEND_PARSE_PARAMETERS_START(0, 2)
2980 		Z_PARAM_OPTIONAL
2981 		Z_PARAM_STR(code)
2982 		Z_PARAM_STR_OR_NULL(lib)
2983 	ZEND_PARSE_PARAMETERS_END();
2984 
2985 	if (lib) {
2986 		handle = DL_LOAD(ZSTR_VAL(lib));
2987 		if (!handle) {
2988 			err = GET_DL_ERROR();
2989 #ifdef PHP_WIN32
2990 			if (err && err[0]) {
2991 				zend_throw_error(zend_ffi_exception_ce, "Failed loading '%s' (%s)", ZSTR_VAL(lib), err);
2992 				php_win32_error_msg_free(err);
2993 			} else {
2994 				zend_throw_error(zend_ffi_exception_ce, "Failed loading '%s' (Unknown reason)", ZSTR_VAL(lib));
2995 			}
2996 #else
2997 			zend_throw_error(zend_ffi_exception_ce, "Failed loading '%s' (%s)", ZSTR_VAL(lib), err);
2998 			GET_DL_ERROR(); /* free the buffer storing the error */
2999 #endif
3000 			RETURN_THROWS();
3001 		}
3002 
3003 #ifdef RTLD_DEFAULT
3004 	} else if (1) {
3005 		// TODO: this might need to be disabled or protected ???
3006 		handle = RTLD_DEFAULT;
3007 #endif
3008 	}
3009 
3010 	FFI_G(symbols) = NULL;
3011 	FFI_G(tags) = NULL;
3012 
3013 	if (code && ZSTR_LEN(code)) {
3014 		/* Parse C definitions */
3015 		FFI_G(default_type_attr) = ZEND_FFI_ATTR_STORED;
3016 
3017 		if (zend_ffi_parse_decl(ZSTR_VAL(code), ZSTR_LEN(code)) == FAILURE) {
3018 			if (FFI_G(symbols)) {
3019 				zend_hash_destroy(FFI_G(symbols));
3020 				efree(FFI_G(symbols));
3021 				FFI_G(symbols) = NULL;
3022 			}
3023 			if (FFI_G(tags)) {
3024 				zend_hash_destroy(FFI_G(tags));
3025 				efree(FFI_G(tags));
3026 				FFI_G(tags) = NULL;
3027 			}
3028 			RETURN_THROWS();
3029 		}
3030 
3031 		if (FFI_G(symbols)) {
3032 			zend_string *name;
3033 			zend_ffi_symbol *sym;
3034 
3035 			ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(FFI_G(symbols), name, sym) {
3036 				if (sym->kind == ZEND_FFI_SYM_VAR) {
3037 					addr = DL_FETCH_SYMBOL(handle, ZSTR_VAL(name));
3038 					if (!addr) {
3039 						zend_throw_error(zend_ffi_exception_ce, "Failed resolving C variable '%s'", ZSTR_VAL(name));
3040 						RETURN_THROWS();
3041 					}
3042 					sym->addr = addr;
3043 				} else if (sym->kind == ZEND_FFI_SYM_FUNC) {
3044 					zend_string *mangled_name = zend_ffi_mangled_func_name(name, ZEND_FFI_TYPE(sym->type));
3045 
3046 					addr = DL_FETCH_SYMBOL(handle, ZSTR_VAL(mangled_name));
3047 					zend_string_release(mangled_name);
3048 					if (!addr) {
3049 						zend_throw_error(zend_ffi_exception_ce, "Failed resolving C function '%s'", ZSTR_VAL(name));
3050 						RETURN_THROWS();
3051 					}
3052 					sym->addr = addr;
3053 				}
3054 			} ZEND_HASH_FOREACH_END();
3055 		}
3056 	}
3057 
3058 	ffi = (zend_ffi*)zend_ffi_new(zend_ffi_ce);
3059 	ffi->lib = handle;
3060 	ffi->symbols = FFI_G(symbols);
3061 	ffi->tags = FFI_G(tags);
3062 
3063 	FFI_G(symbols) = NULL;
3064 	FFI_G(tags) = NULL;
3065 
3066 	RETURN_OBJ(&ffi->std);
3067 }
3068 /* }}} */
3069 
zend_ffi_same_types(zend_ffi_type * old,zend_ffi_type * type)3070 static bool zend_ffi_same_types(zend_ffi_type *old, zend_ffi_type *type) /* {{{ */
3071 {
3072 	if (old == type) {
3073 		return 1;
3074 	}
3075 
3076 	if (old->kind != type->kind
3077 	 || old->size != type->size
3078 	 || old->align != type->align
3079 	 || old->attr != type->attr) {
3080 		return 0;
3081 	}
3082 
3083 	switch (old->kind) {
3084 		case ZEND_FFI_TYPE_ENUM:
3085 			return old->enumeration.kind == type->enumeration.kind;
3086 		case ZEND_FFI_TYPE_ARRAY:
3087 			return old->array.length == type->array.length
3088 			 &&	zend_ffi_same_types(ZEND_FFI_TYPE(old->array.type), ZEND_FFI_TYPE(type->array.type));
3089 		case ZEND_FFI_TYPE_POINTER:
3090 			return zend_ffi_same_types(ZEND_FFI_TYPE(old->pointer.type), ZEND_FFI_TYPE(type->pointer.type));
3091 		case ZEND_FFI_TYPE_STRUCT:
3092 			if (zend_hash_num_elements(&old->record.fields) != zend_hash_num_elements(&type->record.fields)) {
3093 				return 0;
3094 			} else {
3095 				zend_ffi_field *old_field, *field;
3096 				zend_string *key;
3097 				Bucket *b = type->record.fields.arData;
3098 
3099 				ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(&old->record.fields, key, old_field) {
3100 					while (Z_TYPE(b->val) == IS_UNDEF) {
3101 						b++;
3102 					}
3103 					if (key) {
3104 						if (!b->key
3105 						 || !zend_string_equals(key, b->key)) {
3106 							return 0;
3107 						}
3108 					} else if (b->key) {
3109 						return 0;
3110 					}
3111 					field = Z_PTR(b->val);
3112 					if (old_field->offset != field->offset
3113 					 || old_field->is_const != field->is_const
3114 					 || old_field->is_nested != field->is_nested
3115 					 || old_field->first_bit != field->first_bit
3116 					 || old_field->bits != field->bits
3117 					 || !zend_ffi_same_types(ZEND_FFI_TYPE(old_field->type), ZEND_FFI_TYPE(field->type))) {
3118 						return 0;
3119 					}
3120 					b++;
3121 				} ZEND_HASH_FOREACH_END();
3122 			}
3123 			break;
3124 		case ZEND_FFI_TYPE_FUNC:
3125 			if (old->func.abi != type->func.abi
3126 			 || ((old->func.args ? zend_hash_num_elements(old->func.args) : 0) != (type->func.args ? zend_hash_num_elements(type->func.args) : 0))
3127 			 || !zend_ffi_same_types(ZEND_FFI_TYPE(old->func.ret_type), ZEND_FFI_TYPE(type->func.ret_type))) {
3128 				return 0;
3129 			} else if (old->func.args) {
3130 				zend_ffi_type *arg_type;
3131 				zval *zv = type->func.args->arPacked;
3132 
3133 				ZEND_HASH_PACKED_FOREACH_PTR(old->func.args, arg_type) {
3134 					while (Z_TYPE_P(zv) == IS_UNDEF) {
3135 						zv++;
3136 					}
3137 					if (!zend_ffi_same_types(ZEND_FFI_TYPE(arg_type), ZEND_FFI_TYPE(Z_PTR_P(zv)))) {
3138 						return 0;
3139 					}
3140 					zv++;
3141 				} ZEND_HASH_FOREACH_END();
3142 			}
3143 			break;
3144 		default:
3145 			break;
3146 	}
3147 
3148 	return 1;
3149 }
3150 /* }}} */
3151 
zend_ffi_same_symbols(zend_ffi_symbol * old,zend_ffi_symbol * sym)3152 static bool zend_ffi_same_symbols(zend_ffi_symbol *old, zend_ffi_symbol *sym) /* {{{ */
3153 {
3154 	if (old->kind != sym->kind || old->is_const != sym->is_const) {
3155 		return 0;
3156 	}
3157 
3158 	if (old->kind == ZEND_FFI_SYM_CONST) {
3159 		if (old->value != sym->value) {
3160 			return 0;
3161 		}
3162 	}
3163 
3164 	return zend_ffi_same_types(ZEND_FFI_TYPE(old->type), ZEND_FFI_TYPE(sym->type));
3165 }
3166 /* }}} */
3167 
zend_ffi_same_tags(zend_ffi_tag * old,zend_ffi_tag * tag)3168 static bool zend_ffi_same_tags(zend_ffi_tag *old, zend_ffi_tag *tag) /* {{{ */
3169 {
3170 	if (old->kind != tag->kind) {
3171 		return 0;
3172 	}
3173 
3174 	return zend_ffi_same_types(ZEND_FFI_TYPE(old->type), ZEND_FFI_TYPE(tag->type));
3175 }
3176 /* }}} */
3177 
zend_ffi_subst_old_type(zend_ffi_type ** dcl,zend_ffi_type * old,zend_ffi_type * type)3178 static bool zend_ffi_subst_old_type(zend_ffi_type **dcl, zend_ffi_type *old, zend_ffi_type *type) /* {{{ */
3179 {
3180 	zend_ffi_type *dcl_type;
3181 	zend_ffi_field *field;
3182 
3183 	if (ZEND_FFI_TYPE(*dcl) == type) {
3184 		*dcl = old;
3185 		return 1;
3186 	}
3187 	dcl_type = *dcl;
3188 	switch (dcl_type->kind) {
3189 		case ZEND_FFI_TYPE_POINTER:
3190 			return zend_ffi_subst_old_type(&dcl_type->pointer.type, old, type);
3191 		case ZEND_FFI_TYPE_ARRAY:
3192 			return zend_ffi_subst_old_type(&dcl_type->array.type, old, type);
3193 		case ZEND_FFI_TYPE_FUNC:
3194 			if (zend_ffi_subst_old_type(&dcl_type->func.ret_type, old, type)) {
3195 				return 1;
3196 			}
3197 			if (dcl_type->func.args) {
3198 				zval *zv;
3199 
3200 				ZEND_HASH_PACKED_FOREACH_VAL(dcl_type->func.args, zv) {
3201 					if (zend_ffi_subst_old_type((zend_ffi_type**)&Z_PTR_P(zv), old, type)) {
3202 						return 1;
3203 					}
3204 				} ZEND_HASH_FOREACH_END();
3205 			}
3206 			break;
3207 		case ZEND_FFI_TYPE_STRUCT:
3208 			ZEND_HASH_MAP_FOREACH_PTR(&dcl_type->record.fields, field) {
3209 				if (zend_ffi_subst_old_type(&field->type, old, type)) {
3210 					return 1;
3211 				}
3212 			} ZEND_HASH_FOREACH_END();
3213 			break;
3214 		default:
3215 			break;
3216 	}
3217 	return 0;
3218 } /* }}} */
3219 
zend_ffi_cleanup_type(zend_ffi_type * old,zend_ffi_type * type)3220 static void zend_ffi_cleanup_type(zend_ffi_type *old, zend_ffi_type *type) /* {{{ */
3221 {
3222 	zend_ffi_symbol *sym;
3223 	zend_ffi_tag *tag;
3224 
3225 	if (FFI_G(symbols)) {
3226 		ZEND_HASH_MAP_FOREACH_PTR(FFI_G(symbols), sym) {
3227 			zend_ffi_subst_old_type(&sym->type, old, type);
3228 		} ZEND_HASH_FOREACH_END();
3229 	}
3230 	if (FFI_G(tags)) {
3231 		ZEND_HASH_MAP_FOREACH_PTR(FFI_G(tags), tag) {
3232 			zend_ffi_subst_old_type(&tag->type, old, type);
3233 		} ZEND_HASH_FOREACH_END();
3234 	}
3235 }
3236 /* }}} */
3237 
zend_ffi_remember_type(zend_ffi_type * type)3238 static zend_ffi_type *zend_ffi_remember_type(zend_ffi_type *type) /* {{{ */
3239 {
3240 	if (!FFI_G(weak_types)) {
3241 		FFI_G(weak_types) = emalloc(sizeof(HashTable));
3242 		zend_hash_init(FFI_G(weak_types), 0, NULL, zend_ffi_type_hash_dtor, 0);
3243 	}
3244 	// TODO: avoid dups ???
3245 	type->attr |= ZEND_FFI_ATTR_STORED;
3246 	zend_hash_next_index_insert_ptr(FFI_G(weak_types), ZEND_FFI_TYPE_MAKE_OWNED(type));
3247 	return type;
3248 }
3249 /* }}} */
3250 
zend_ffi_load(const char * filename,bool preload)3251 static zend_ffi *zend_ffi_load(const char *filename, bool preload) /* {{{ */
3252 {
3253 	struct stat buf;
3254 	int fd;
3255 	char *code, *code_pos, *scope_name, *lib, *err;
3256 	size_t code_size, scope_name_len;
3257 	zend_ffi *ffi;
3258 	DL_HANDLE handle = NULL;
3259 	zend_ffi_scope *scope = NULL;
3260 	zend_string *name;
3261 	zend_ffi_symbol *sym;
3262 	zend_ffi_tag *tag;
3263 	void *addr;
3264 
3265 	if (stat(filename, &buf) != 0) {
3266 		if (preload) {
3267 			zend_error(E_WARNING, "FFI: failed pre-loading '%s', file doesn't exist", filename);
3268 		} else {
3269 			zend_throw_error(zend_ffi_exception_ce, "Failed loading '%s', file doesn't exist", filename);
3270 		}
3271 		return NULL;
3272 	}
3273 
3274 	if ((buf.st_mode & S_IFMT) != S_IFREG) {
3275 		if (preload) {
3276 			zend_error(E_WARNING, "FFI: failed pre-loading '%s', not a regular file", filename);
3277 		} else {
3278 			zend_throw_error(zend_ffi_exception_ce, "Failed loading '%s', not a regular file", filename);
3279 		}
3280 		return NULL;
3281 	}
3282 
3283 	code_size = buf.st_size;
3284 	code = emalloc(code_size + 1);
3285 	int open_flags = O_RDONLY;
3286 #ifdef PHP_WIN32
3287 	open_flags |= _O_BINARY;
3288 #endif
3289 	fd = open(filename, open_flags, 0);
3290 	if (fd < 0 || read(fd, code, code_size) != code_size) {
3291 		if (preload) {
3292 			zend_error(E_WARNING, "FFI: Failed pre-loading '%s', cannot read_file", filename);
3293 		} else {
3294 			zend_throw_error(zend_ffi_exception_ce, "Failed loading '%s', cannot read_file", filename);
3295 		}
3296 		efree(code);
3297 		close(fd);
3298 		return NULL;
3299 	}
3300 	close(fd);
3301 	code[code_size] = 0;
3302 
3303 	FFI_G(symbols) = NULL;
3304 	FFI_G(tags) = NULL;
3305 	FFI_G(persistent) = preload;
3306 	FFI_G(default_type_attr) = preload ?
3307 		ZEND_FFI_ATTR_STORED | ZEND_FFI_ATTR_PERSISTENT :
3308 		ZEND_FFI_ATTR_STORED;
3309 
3310 	scope_name = NULL;
3311 	scope_name_len = 0;
3312 	lib = NULL;
3313 	code_pos = zend_ffi_parse_directives(filename, code, &scope_name, &lib, preload);
3314 	if (!code_pos) {
3315 		efree(code);
3316 		FFI_G(persistent) = 0;
3317 		return NULL;
3318 	}
3319 	code_size -= code_pos - code;
3320 
3321 	if (zend_ffi_parse_decl(code_pos, code_size) == FAILURE) {
3322 		if (preload) {
3323 			zend_error(E_WARNING, "FFI: failed pre-loading '%s'", filename);
3324 		} else {
3325 			zend_throw_error(zend_ffi_exception_ce, "Failed loading '%s'", filename);
3326 		}
3327 		goto cleanup;
3328 	}
3329 
3330 	if (lib) {
3331 		handle = DL_LOAD(lib);
3332 		if (!handle) {
3333 			if (preload) {
3334 				zend_error(E_WARNING, "FFI: Failed pre-loading '%s'", lib);
3335 			} else {
3336 				err = GET_DL_ERROR();
3337 #ifdef PHP_WIN32
3338 				if (err && err[0]) {
3339 					zend_throw_error(zend_ffi_exception_ce, "Failed loading '%s' (%s)", lib, err);
3340 					php_win32_error_msg_free(err);
3341 				} else {
3342 					zend_throw_error(zend_ffi_exception_ce, "Failed loading '%s' (Unknown reason)", lib);
3343 				}
3344 #else
3345 				zend_throw_error(zend_ffi_exception_ce, "Failed loading '%s' (%s)", lib, err);
3346 				GET_DL_ERROR(); /* free the buffer storing the error */
3347 #endif
3348 			}
3349 			goto cleanup;
3350 		}
3351 #ifdef RTLD_DEFAULT
3352 	} else if (1) {
3353 		// TODO: this might need to be disabled or protected ???
3354 		handle = RTLD_DEFAULT;
3355 #endif
3356 	}
3357 
3358 	if (preload) {
3359 		if (!scope_name) {
3360 			scope_name = "C";
3361 		}
3362 		scope_name_len = strlen(scope_name);
3363 		if (FFI_G(scopes)) {
3364 			scope = zend_hash_str_find_ptr(FFI_G(scopes), scope_name, scope_name_len);
3365 		}
3366 	}
3367 
3368 	if (FFI_G(symbols)) {
3369 		ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(FFI_G(symbols), name, sym) {
3370 			if (sym->kind == ZEND_FFI_SYM_VAR) {
3371 				addr = DL_FETCH_SYMBOL(handle, ZSTR_VAL(name));
3372 				if (!addr) {
3373 					if (preload) {
3374 						zend_error(E_WARNING, "FFI: failed pre-loading '%s', cannot resolve C variable '%s'", filename, ZSTR_VAL(name));
3375 					} else {
3376 						zend_throw_error(zend_ffi_exception_ce, "Failed resolving C variable '%s'", ZSTR_VAL(name));
3377 					}
3378 					if (lib) {
3379 						DL_UNLOAD(handle);
3380 					}
3381 					goto cleanup;
3382 				}
3383 				sym->addr = addr;
3384 			} else if (sym->kind == ZEND_FFI_SYM_FUNC) {
3385 				zend_string *mangled_name = zend_ffi_mangled_func_name(name, ZEND_FFI_TYPE(sym->type));
3386 
3387 				addr = DL_FETCH_SYMBOL(handle, ZSTR_VAL(mangled_name));
3388 				zend_string_release(mangled_name);
3389 				if (!addr) {
3390 					if (preload) {
3391 						zend_error(E_WARNING, "failed pre-loading '%s', cannot resolve C function '%s'", filename, ZSTR_VAL(name));
3392 					} else {
3393 						zend_throw_error(zend_ffi_exception_ce, "Failed resolving C function '%s'", ZSTR_VAL(name));
3394 					}
3395 					if (lib) {
3396 						DL_UNLOAD(handle);
3397 					}
3398 					goto cleanup;
3399 				}
3400 				sym->addr = addr;
3401 			}
3402 			if (scope && scope->symbols) {
3403 				zend_ffi_symbol *old_sym = zend_hash_find_ptr(scope->symbols, name);
3404 
3405 				if (old_sym) {
3406 					if (zend_ffi_same_symbols(old_sym, sym)) {
3407 						if (ZEND_FFI_TYPE_IS_OWNED(sym->type)
3408 						 && ZEND_FFI_TYPE(old_sym->type) != ZEND_FFI_TYPE(sym->type)) {
3409 							zend_ffi_type *type = ZEND_FFI_TYPE(sym->type);
3410 							zend_ffi_cleanup_type(ZEND_FFI_TYPE(old_sym->type), ZEND_FFI_TYPE(type));
3411 							zend_ffi_type_dtor(type);
3412 						}
3413 					} else {
3414 						zend_error(E_WARNING, "FFI: failed pre-loading '%s', redefinition of '%s'", filename, ZSTR_VAL(name));
3415 						if (lib) {
3416 							DL_UNLOAD(handle);
3417 						}
3418 						goto cleanup;
3419 					}
3420 				}
3421 			}
3422 		} ZEND_HASH_FOREACH_END();
3423 	}
3424 
3425 	if (preload) {
3426 		if (scope && scope->tags && FFI_G(tags)) {
3427 			ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(FFI_G(tags), name, tag) {
3428 				zend_ffi_tag *old_tag = zend_hash_find_ptr(scope->tags, name);
3429 
3430 				if (old_tag) {
3431 					if (zend_ffi_same_tags(old_tag, tag)) {
3432 						if (ZEND_FFI_TYPE_IS_OWNED(tag->type)
3433 						 && ZEND_FFI_TYPE(old_tag->type) != ZEND_FFI_TYPE(tag->type)) {
3434 							zend_ffi_type *type = ZEND_FFI_TYPE(tag->type);
3435 							zend_ffi_cleanup_type(ZEND_FFI_TYPE(old_tag->type), ZEND_FFI_TYPE(type));
3436 							zend_ffi_type_dtor(type);
3437 						}
3438 					} else {
3439 						zend_error(E_WARNING, "FFI: failed pre-loading '%s', redefinition of '%s %s'", filename, zend_ffi_tag_kind_name[tag->kind], ZSTR_VAL(name));
3440 						if (lib) {
3441 							DL_UNLOAD(handle);
3442 						}
3443 						goto cleanup;
3444 					}
3445 				}
3446 			} ZEND_HASH_FOREACH_END();
3447 		}
3448 
3449 		if (!scope) {
3450 			scope = malloc(sizeof(zend_ffi_scope));
3451 			scope->symbols = FFI_G(symbols);
3452 			scope->tags = FFI_G(tags);
3453 
3454 			if (!FFI_G(scopes)) {
3455 				FFI_G(scopes) = malloc(sizeof(HashTable));
3456 				zend_hash_init(FFI_G(scopes), 0, NULL, zend_ffi_scope_hash_dtor, 1);
3457 			}
3458 
3459 			zend_hash_str_add_ptr(FFI_G(scopes), scope_name, scope_name_len, scope);
3460 		} else {
3461 			if (FFI_G(symbols)) {
3462 				if (!scope->symbols) {
3463 					scope->symbols = FFI_G(symbols);
3464 					FFI_G(symbols) = NULL;
3465 				} else {
3466 					ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(FFI_G(symbols), name, sym) {
3467 						if (!zend_hash_add_ptr(scope->symbols, name, sym)) {
3468 							zend_ffi_type_dtor(sym->type);
3469 							free(sym);
3470 						}
3471 					} ZEND_HASH_FOREACH_END();
3472 					FFI_G(symbols)->pDestructor = NULL;
3473 					zend_hash_destroy(FFI_G(symbols));
3474 				}
3475 			}
3476 			if (FFI_G(tags)) {
3477 				if (!scope->tags) {
3478 					scope->tags = FFI_G(tags);
3479 					FFI_G(tags) = NULL;
3480 				} else {
3481 					ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(FFI_G(tags), name, tag) {
3482 						if (!zend_hash_add_ptr(scope->tags, name, tag)) {
3483 							zend_ffi_type_dtor(tag->type);
3484 							free(tag);
3485 						}
3486 					} ZEND_HASH_FOREACH_END();
3487 					FFI_G(tags)->pDestructor = NULL;
3488 					zend_hash_destroy(FFI_G(tags));
3489 				}
3490 			}
3491 		}
3492 
3493 		if (EG(objects_store).object_buckets) {
3494 			ffi = (zend_ffi*)zend_ffi_new(zend_ffi_ce);
3495 		} else {
3496 			ffi = ecalloc(1, sizeof(zend_ffi));
3497 		}
3498 		ffi->symbols = scope->symbols;
3499 		ffi->tags = scope->tags;
3500 		ffi->persistent = 1;
3501 	} else {
3502 		ffi = (zend_ffi*)zend_ffi_new(zend_ffi_ce);
3503 		ffi->lib = handle;
3504 		ffi->symbols = FFI_G(symbols);
3505 		ffi->tags = FFI_G(tags);
3506 	}
3507 
3508 	efree(code);
3509 	FFI_G(symbols) = NULL;
3510 	FFI_G(tags) = NULL;
3511 	FFI_G(persistent) = 0;
3512 
3513 	return ffi;
3514 
3515 cleanup:
3516 	efree(code);
3517 	if (FFI_G(symbols)) {
3518 		zend_hash_destroy(FFI_G(symbols));
3519 		pefree(FFI_G(symbols), preload);
3520 		FFI_G(symbols) = NULL;
3521 	}
3522 	if (FFI_G(tags)) {
3523 		zend_hash_destroy(FFI_G(tags));
3524 		pefree(FFI_G(tags), preload);
3525 		FFI_G(tags) = NULL;
3526 	}
3527 	FFI_G(persistent) = 0;
3528 	return NULL;
3529 }
3530 /* }}} */
3531 
ZEND_METHOD(FFI,load)3532 ZEND_METHOD(FFI, load) /* {{{ */
3533 {
3534 	zend_string *fn;
3535 	zend_ffi *ffi;
3536 
3537 	ZEND_FFI_VALIDATE_API_RESTRICTION();
3538 	ZEND_PARSE_PARAMETERS_START(1, 1)
3539 		Z_PARAM_STR(fn)
3540 	ZEND_PARSE_PARAMETERS_END();
3541 
3542 	if (CG(compiler_options) & ZEND_COMPILE_PRELOAD_IN_CHILD) {
3543 		zend_throw_error(zend_ffi_exception_ce, "FFI::load() doesn't work in conjunction with \"opcache.preload_user\". Use \"ffi.preload\" instead.");
3544 		RETURN_THROWS();
3545 	}
3546 
3547 	ffi = zend_ffi_load(ZSTR_VAL(fn), (CG(compiler_options) & ZEND_COMPILE_PRELOAD) != 0);
3548 
3549 	if (ffi) {
3550 		RETURN_OBJ(&ffi->std);
3551 	}
3552 }
3553 /* }}} */
3554 
ZEND_METHOD(FFI,scope)3555 ZEND_METHOD(FFI, scope) /* {{{ */
3556 {
3557 	zend_string *scope_name;
3558 	zend_ffi_scope *scope = NULL;
3559 	zend_ffi *ffi;
3560 
3561 	ZEND_FFI_VALIDATE_API_RESTRICTION();
3562 	ZEND_PARSE_PARAMETERS_START(1, 1)
3563 		Z_PARAM_STR(scope_name)
3564 	ZEND_PARSE_PARAMETERS_END();
3565 
3566 	if (FFI_G(scopes)) {
3567 		scope = zend_hash_find_ptr(FFI_G(scopes), scope_name);
3568 	}
3569 
3570 	if (!scope) {
3571 		zend_throw_error(zend_ffi_exception_ce, "Failed loading scope '%s'", ZSTR_VAL(scope_name));
3572 		RETURN_THROWS();
3573 	}
3574 
3575 	ffi = (zend_ffi*)zend_ffi_new(zend_ffi_ce);
3576 
3577 	ffi->symbols = scope->symbols;
3578 	ffi->tags = scope->tags;
3579 	ffi->persistent = 1;
3580 
3581 	RETURN_OBJ(&ffi->std);
3582 }
3583 /* }}} */
3584 
zend_ffi_cleanup_dcl(zend_ffi_dcl * dcl)3585 void zend_ffi_cleanup_dcl(zend_ffi_dcl *dcl) /* {{{ */
3586 {
3587 	if (dcl) {
3588 		zend_ffi_type_dtor(dcl->type);
3589 		dcl->type = NULL;
3590 	}
3591 }
3592 /* }}} */
3593 
zend_ffi_throw_parser_error(const char * format,...)3594 static void zend_ffi_throw_parser_error(const char *format, ...) /* {{{ */
3595 {
3596 	va_list va;
3597 	char *message = NULL;
3598 
3599 	va_start(va, format);
3600 	zend_vspprintf(&message, 0, format, va);
3601 
3602 	if (EG(current_execute_data)) {
3603 		zend_throw_exception(zend_ffi_parser_exception_ce, message, 0);
3604 	} else {
3605 		zend_error(E_WARNING, "FFI Parser: %s", message);
3606 	}
3607 
3608 	efree(message);
3609 	va_end(va);
3610 }
3611 /* }}} */
3612 
zend_ffi_validate_vla(zend_ffi_type * type)3613 static zend_result zend_ffi_validate_vla(zend_ffi_type *type) /* {{{ */
3614 {
3615 	if (!FFI_G(allow_vla) && (type->attr & ZEND_FFI_ATTR_VLA)) {
3616 		zend_ffi_throw_parser_error("\"[*]\" is not allowed in other than function prototype scope at line %d", FFI_G(line));
3617 		return FAILURE;
3618 	}
3619 	return SUCCESS;
3620 }
3621 /* }}} */
3622 
zend_ffi_validate_incomplete_type(zend_ffi_type * type,bool allow_incomplete_tag,bool allow_incomplete_array)3623 static zend_result zend_ffi_validate_incomplete_type(zend_ffi_type *type, bool allow_incomplete_tag, bool allow_incomplete_array) /* {{{ */
3624 {
3625 	if (!allow_incomplete_tag && (type->attr & ZEND_FFI_ATTR_INCOMPLETE_TAG)) {
3626 		if (FFI_G(tags)) {
3627 			zend_string *key;
3628 			zend_ffi_tag *tag;
3629 
3630 			ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(FFI_G(tags), key, tag) {
3631 				if (ZEND_FFI_TYPE(tag->type) == type) {
3632 					if (type->kind == ZEND_FFI_TYPE_ENUM) {
3633 						zend_ffi_throw_parser_error("Incomplete enum \"%s\" at line %d", ZSTR_VAL(key), FFI_G(line));
3634 					} else if (type->attr & ZEND_FFI_ATTR_UNION) {
3635 						zend_ffi_throw_parser_error("Incomplete union \"%s\" at line %d", ZSTR_VAL(key), FFI_G(line));
3636 					} else {
3637 						zend_ffi_throw_parser_error("Incomplete struct \"%s\" at line %d", ZSTR_VAL(key), FFI_G(line));
3638 					}
3639 					return FAILURE;
3640 				}
3641 			} ZEND_HASH_FOREACH_END();
3642 		}
3643 		if (FFI_G(symbols)) {
3644 			zend_string *key;
3645 			zend_ffi_symbol *sym;
3646 
3647 			ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(FFI_G(symbols), key, sym) {
3648 				if (type == ZEND_FFI_TYPE(sym->type)) {
3649 					zend_ffi_throw_parser_error("Incomplete C type %s at line %d", ZSTR_VAL(key), FFI_G(line));
3650 					return FAILURE;
3651 				}
3652 			} ZEND_HASH_FOREACH_END();
3653 		}
3654 		zend_ffi_throw_parser_error("Incomplete type at line %d", FFI_G(line));
3655 		return FAILURE;
3656 	} else if (!allow_incomplete_array && (type->attr & ZEND_FFI_ATTR_INCOMPLETE_ARRAY)) {
3657 		zend_ffi_throw_parser_error("\"[]\" is not allowed at line %d", FFI_G(line));
3658 		return FAILURE;
3659 	} else if (!FFI_G(allow_vla) && (type->attr & ZEND_FFI_ATTR_VLA)) {
3660 		zend_ffi_throw_parser_error("\"[*]\" is not allowed in other than function prototype scope at line %d", FFI_G(line));
3661 		return FAILURE;
3662 	}
3663 	return SUCCESS;
3664 }
3665 /* }}} */
3666 
zend_ffi_validate_type(zend_ffi_type * type,bool allow_incomplete_tag,bool allow_incomplete_array)3667 static zend_result zend_ffi_validate_type(zend_ffi_type *type, bool allow_incomplete_tag, bool allow_incomplete_array) /* {{{ */
3668 {
3669 	if (type->kind == ZEND_FFI_TYPE_VOID) {
3670 		zend_ffi_throw_parser_error("void type is not allowed at line %d", FFI_G(line));
3671 		return FAILURE;
3672 	}
3673 	return zend_ffi_validate_incomplete_type(type, allow_incomplete_tag, allow_incomplete_array);
3674 }
3675 /* }}} */
3676 
zend_ffi_validate_var_type(zend_ffi_type * type,bool allow_incomplete_array)3677 static zend_result zend_ffi_validate_var_type(zend_ffi_type *type, bool allow_incomplete_array) /* {{{ */
3678 {
3679 	if (type->kind == ZEND_FFI_TYPE_FUNC) {
3680 		zend_ffi_throw_parser_error("function type is not allowed at line %d", FFI_G(line));
3681 		return FAILURE;
3682 	}
3683 	return zend_ffi_validate_type(type, 0, allow_incomplete_array);
3684 }
3685 /* }}} */
3686 
zend_ffi_validate_type_name(zend_ffi_dcl * dcl)3687 void zend_ffi_validate_type_name(zend_ffi_dcl *dcl) /* {{{ */
3688 {
3689 	zend_ffi_finalize_type(dcl);
3690 	if (zend_ffi_validate_var_type(ZEND_FFI_TYPE(dcl->type), 0) == FAILURE) {
3691 		zend_ffi_cleanup_dcl(dcl);
3692 		LONGJMP(FFI_G(bailout), FAILURE);
3693 	}
3694 }
3695 /* }}} */
3696 
zend_ffi_subst_type(zend_ffi_type ** dcl,zend_ffi_type * type)3697 static bool zend_ffi_subst_type(zend_ffi_type **dcl, zend_ffi_type *type) /* {{{ */
3698 {
3699 	zend_ffi_type *dcl_type;
3700 	zend_ffi_field *field;
3701 
3702 	if (*dcl == type) {
3703 		*dcl = ZEND_FFI_TYPE_MAKE_OWNED(type);
3704 		return 1;
3705 	}
3706 	dcl_type = *dcl;
3707 	switch (dcl_type->kind) {
3708 		case ZEND_FFI_TYPE_POINTER:
3709 			return zend_ffi_subst_type(&dcl_type->pointer.type, type);
3710 		case ZEND_FFI_TYPE_ARRAY:
3711 			return zend_ffi_subst_type(&dcl_type->array.type, type);
3712 		case ZEND_FFI_TYPE_FUNC:
3713 			if (zend_ffi_subst_type(&dcl_type->func.ret_type, type)) {
3714 				return 1;
3715 			}
3716 			if (dcl_type->func.args) {
3717 				zval *zv;
3718 
3719 				ZEND_HASH_PACKED_FOREACH_VAL(dcl_type->func.args, zv) {
3720 					if (zend_ffi_subst_type((zend_ffi_type**)&Z_PTR_P(zv), type)) {
3721 						return 1;
3722 					}
3723 				} ZEND_HASH_FOREACH_END();
3724 			}
3725 			break;
3726 		case ZEND_FFI_TYPE_STRUCT:
3727 			ZEND_HASH_MAP_FOREACH_PTR(&dcl_type->record.fields, field) {
3728 				if (zend_ffi_subst_type(&field->type, type)) {
3729 					return 1;
3730 				}
3731 			} ZEND_HASH_FOREACH_END();
3732 			break;
3733 		default:
3734 			break;
3735 	}
3736 	return 0;
3737 } /* }}} */
3738 
zend_ffi_tags_cleanup(zend_ffi_dcl * dcl)3739 static void zend_ffi_tags_cleanup(zend_ffi_dcl *dcl) /* {{{ */
3740 {
3741 	zend_ffi_tag *tag;
3742 	ZEND_HASH_MAP_FOREACH_PTR(FFI_G(tags), tag) {
3743 		if (ZEND_FFI_TYPE_IS_OWNED(tag->type)) {
3744 			zend_ffi_type *type = ZEND_FFI_TYPE(tag->type);
3745 			zend_ffi_subst_type(&dcl->type, type);
3746 			tag->type = type;
3747 		}
3748 	} ZEND_HASH_FOREACH_END();
3749 	zend_hash_destroy(FFI_G(tags));
3750 	efree(FFI_G(tags));
3751 }
3752 /* }}} */
3753 
ZEND_METHOD(FFI,new)3754 ZEND_METHOD(FFI, new) /* {{{ */
3755 {
3756 	zend_string *type_def = NULL;
3757 	zend_object *type_obj = NULL;
3758 	zend_ffi_type *type, *type_ptr;
3759 	zend_ffi_cdata *cdata;
3760 	void *ptr;
3761 	bool owned = 1;
3762 	bool persistent = 0;
3763 	bool is_const = 0;
3764 	bool is_static_call = Z_TYPE(EX(This)) != IS_OBJECT;
3765 	zend_ffi_flags flags = ZEND_FFI_FLAG_OWNED;
3766 
3767 	ZEND_FFI_VALIDATE_API_RESTRICTION();
3768 	ZEND_PARSE_PARAMETERS_START(1, 3)
3769 		Z_PARAM_OBJ_OF_CLASS_OR_STR(type_obj, zend_ffi_ctype_ce, type_def)
3770 		Z_PARAM_OPTIONAL
3771 		Z_PARAM_BOOL(owned)
3772 		Z_PARAM_BOOL(persistent)
3773 	ZEND_PARSE_PARAMETERS_END();
3774 
3775 	if (is_static_call) {
3776 		zend_error(E_DEPRECATED, "Calling FFI::new() statically is deprecated");
3777 		if (EG(exception)) {
3778 			RETURN_THROWS();
3779 		}
3780 	}
3781 
3782 	if (!owned) {
3783 		flags &= ~ZEND_FFI_FLAG_OWNED;
3784 	}
3785 
3786 	if (persistent) {
3787 		flags |= ZEND_FFI_FLAG_PERSISTENT;
3788 	}
3789 
3790 	if (type_def) {
3791 		zend_ffi_dcl dcl = ZEND_FFI_ATTR_INIT;
3792 
3793 		if (!is_static_call) {
3794 			zend_ffi *ffi = (zend_ffi*)Z_OBJ(EX(This));
3795 			FFI_G(symbols) = ffi->symbols;
3796 			FFI_G(tags) = ffi->tags;
3797 		} else {
3798 			FFI_G(symbols) = NULL;
3799 			FFI_G(tags) = NULL;
3800 		}
3801 		bool clean_symbols = FFI_G(symbols) == NULL;
3802 		bool clean_tags = FFI_G(tags) == NULL;
3803 
3804 		FFI_G(default_type_attr) = 0;
3805 
3806 		if (zend_ffi_parse_type(ZSTR_VAL(type_def), ZSTR_LEN(type_def), &dcl) == FAILURE) {
3807 			zend_ffi_type_dtor(dcl.type);
3808 			if (clean_tags && FFI_G(tags)) {
3809 				zend_hash_destroy(FFI_G(tags));
3810 				efree(FFI_G(tags));
3811 				FFI_G(tags) = NULL;
3812 			}
3813 			if (clean_symbols && FFI_G(symbols)) {
3814 				zend_hash_destroy(FFI_G(symbols));
3815 				efree(FFI_G(symbols));
3816 				FFI_G(symbols) = NULL;
3817 			}
3818 			return;
3819 		}
3820 
3821 		type = ZEND_FFI_TYPE(dcl.type);
3822 		if (dcl.attr & ZEND_FFI_ATTR_CONST) {
3823 			is_const = 1;
3824 		}
3825 
3826 		if (clean_tags && FFI_G(tags)) {
3827 			zend_ffi_tags_cleanup(&dcl);
3828 		}
3829 		if (clean_symbols && FFI_G(symbols)) {
3830 			zend_hash_destroy(FFI_G(symbols));
3831 			efree(FFI_G(symbols));
3832 			FFI_G(symbols) = NULL;
3833 		}
3834 		FFI_G(symbols) = NULL;
3835 		FFI_G(tags) = NULL;
3836 
3837 		type_ptr = dcl.type;
3838 	} else {
3839 		zend_ffi_ctype *ctype = (zend_ffi_ctype*) type_obj;
3840 
3841 		type_ptr = type = ctype->type;
3842 		if (ZEND_FFI_TYPE_IS_OWNED(type)) {
3843 			type = ZEND_FFI_TYPE(type);
3844 			if (!(type->attr & ZEND_FFI_ATTR_STORED)) {
3845 				if (GC_REFCOUNT(&ctype->std) == 1) {
3846 					/* transfer type ownership */
3847 					ctype->type = type;
3848 				} else {
3849 					ctype->type = type_ptr = type = zend_ffi_remember_type(type);
3850 				}
3851 			}
3852 		}
3853 	}
3854 
3855 	if (type->size == 0) {
3856 		zend_throw_error(zend_ffi_exception_ce, "Cannot instantiate FFI\\CData of zero size");
3857 		zend_ffi_type_dtor(type_ptr);
3858 		return;
3859 	}
3860 
3861 	ptr = pemalloc(type->size, flags & ZEND_FFI_FLAG_PERSISTENT);
3862 	memset(ptr, 0, type->size);
3863 
3864 	cdata = (zend_ffi_cdata*)zend_ffi_cdata_new(zend_ffi_cdata_ce);
3865 	if (type->kind < ZEND_FFI_TYPE_POINTER) {
3866 		cdata->std.handlers = &zend_ffi_cdata_value_handlers;
3867 	}
3868 	cdata->type = type_ptr;
3869 	cdata->ptr = ptr;
3870 	cdata->flags = flags;
3871 	if (is_const) {
3872 		cdata->flags |= ZEND_FFI_FLAG_CONST;
3873 	}
3874 
3875 	RETURN_OBJ(&cdata->std);
3876 }
3877 /* }}} */
3878 
ZEND_METHOD(FFI,free)3879 ZEND_METHOD(FFI, free) /* {{{ */
3880 {
3881 	zval *zv;
3882 	zend_ffi_cdata *cdata;
3883 
3884 	ZEND_FFI_VALIDATE_API_RESTRICTION();
3885 	ZEND_PARSE_PARAMETERS_START(1, 1)
3886 		Z_PARAM_OBJECT_OF_CLASS_EX(zv, zend_ffi_cdata_ce, 0, 1);
3887 	ZEND_PARSE_PARAMETERS_END();
3888 
3889 	cdata = (zend_ffi_cdata*)Z_OBJ_P(zv);
3890 
3891 	if (ZEND_FFI_TYPE(cdata->type)->kind == ZEND_FFI_TYPE_POINTER) {
3892 		if (!cdata->ptr) {
3893 			zend_throw_error(zend_ffi_exception_ce, "NULL pointer dereference");
3894 			RETURN_THROWS();
3895 		}
3896 		if (cdata->ptr != (void*)&cdata->ptr_holder) {
3897 			pefree(*(void**)cdata->ptr, cdata->flags & ZEND_FFI_FLAG_PERSISTENT);
3898 		} else {
3899 			pefree(cdata->ptr_holder, (cdata->flags & ZEND_FFI_FLAG_PERSISTENT) || !is_zend_ptr(cdata->ptr_holder));
3900 		}
3901 		*(void**)cdata->ptr = NULL;
3902 	} else if (!(cdata->flags & ZEND_FFI_FLAG_OWNED)) {
3903 		pefree(cdata->ptr, cdata->flags & ZEND_FFI_FLAG_PERSISTENT);
3904 		cdata->ptr = NULL;
3905 		cdata->flags &= ~(ZEND_FFI_FLAG_OWNED|ZEND_FFI_FLAG_PERSISTENT);
3906 		cdata->std.handlers = &zend_ffi_cdata_free_handlers;
3907 	} else {
3908 		zend_throw_error(zend_ffi_exception_ce, "free() non a C pointer");
3909 	}
3910 }
3911 /* }}} */
3912 
ZEND_METHOD(FFI,cast)3913 ZEND_METHOD(FFI, cast) /* {{{ */
3914 {
3915 	zend_string *type_def = NULL;
3916 	zend_object *ztype = NULL;
3917 	zend_ffi_type *old_type, *type, *type_ptr;
3918 	zend_ffi_cdata *old_cdata, *cdata;
3919 	bool is_const = 0;
3920 	bool is_static_call = Z_TYPE(EX(This)) != IS_OBJECT;
3921 	zval *zv, *arg;
3922 	void *ptr;
3923 
3924 	ZEND_FFI_VALIDATE_API_RESTRICTION();
3925 	ZEND_PARSE_PARAMETERS_START(2, 2)
3926 		Z_PARAM_OBJ_OF_CLASS_OR_STR(ztype, zend_ffi_ctype_ce, type_def)
3927 		Z_PARAM_ZVAL(zv)
3928 	ZEND_PARSE_PARAMETERS_END();
3929 
3930 	if (is_static_call) {
3931 		zend_error(E_DEPRECATED, "Calling FFI::cast() statically is deprecated");
3932 		if (EG(exception)) {
3933 			RETURN_THROWS();
3934 		}
3935 	}
3936 
3937 	arg = zv;
3938 	ZVAL_DEREF(zv);
3939 
3940 	if (type_def) {
3941 		zend_ffi_dcl dcl = ZEND_FFI_ATTR_INIT;
3942 
3943 		if (!is_static_call) {
3944 			zend_ffi *ffi = (zend_ffi*)Z_OBJ(EX(This));
3945 			FFI_G(symbols) = ffi->symbols;
3946 			FFI_G(tags) = ffi->tags;
3947 		} else {
3948 			FFI_G(symbols) = NULL;
3949 			FFI_G(tags) = NULL;
3950 		}
3951 		bool clean_symbols = FFI_G(symbols) == NULL;
3952 		bool clean_tags = FFI_G(tags) == NULL;
3953 
3954 		FFI_G(default_type_attr) = 0;
3955 
3956 		if (zend_ffi_parse_type(ZSTR_VAL(type_def), ZSTR_LEN(type_def), &dcl) == FAILURE) {
3957 			zend_ffi_type_dtor(dcl.type);
3958 			if (clean_tags && FFI_G(tags)) {
3959 				zend_hash_destroy(FFI_G(tags));
3960 				efree(FFI_G(tags));
3961 				FFI_G(tags) = NULL;
3962 			}
3963 			if (clean_symbols && FFI_G(symbols)) {
3964 				zend_hash_destroy(FFI_G(symbols));
3965 				efree(FFI_G(symbols));
3966 				FFI_G(symbols) = NULL;
3967 			}
3968 			return;
3969 		}
3970 
3971 		type = ZEND_FFI_TYPE(dcl.type);
3972 		if (dcl.attr & ZEND_FFI_ATTR_CONST) {
3973 			is_const = 1;
3974 		}
3975 
3976 		if (clean_tags && FFI_G(tags)) {
3977 			zend_ffi_tags_cleanup(&dcl);
3978 		}
3979 		if (clean_symbols && FFI_G(symbols)) {
3980 			zend_hash_destroy(FFI_G(symbols));
3981 			efree(FFI_G(symbols));
3982 			FFI_G(symbols) = NULL;
3983 		}
3984 		FFI_G(symbols) = NULL;
3985 		FFI_G(tags) = NULL;
3986 
3987 		type_ptr = dcl.type;
3988 	} else {
3989 		zend_ffi_ctype *ctype = (zend_ffi_ctype*) ztype;
3990 
3991 		type_ptr = type = ctype->type;
3992 		if (ZEND_FFI_TYPE_IS_OWNED(type)) {
3993 			type = ZEND_FFI_TYPE(type);
3994 			if (!(type->attr & ZEND_FFI_ATTR_STORED)) {
3995 				if (GC_REFCOUNT(&ctype->std) == 1) {
3996 					/* transfer type ownership */
3997 					ctype->type = type;
3998 				} else {
3999 					ctype->type = type_ptr = type = zend_ffi_remember_type(type);
4000 				}
4001 			}
4002 		}
4003 	}
4004 
4005 	if (Z_TYPE_P(zv) != IS_OBJECT || Z_OBJCE_P(zv) != zend_ffi_cdata_ce) {
4006 		if (type->kind < ZEND_FFI_TYPE_POINTER && Z_TYPE_P(zv) < IS_STRING) {
4007 			/* numeric conversion */
4008 			cdata = (zend_ffi_cdata*)zend_ffi_cdata_new(zend_ffi_cdata_ce);
4009 			cdata->std.handlers = &zend_ffi_cdata_value_handlers;
4010 			cdata->type = type_ptr;
4011 			cdata->ptr = emalloc(type->size);
4012 			zend_ffi_zval_to_cdata(cdata->ptr, type, zv);
4013 			cdata->flags = ZEND_FFI_FLAG_OWNED;
4014 			if (is_const) {
4015 				cdata->flags |= ZEND_FFI_FLAG_CONST;
4016 			}
4017 			RETURN_OBJ(&cdata->std);
4018 		} else if (type->kind == ZEND_FFI_TYPE_POINTER && Z_TYPE_P(zv) == IS_LONG) {
4019 			/* number to pointer conversion */
4020 			cdata = (zend_ffi_cdata*)zend_ffi_cdata_new(zend_ffi_cdata_ce);
4021 			cdata->type = type_ptr;
4022 			cdata->ptr = &cdata->ptr_holder;
4023 			cdata->ptr_holder = (void*)(intptr_t)Z_LVAL_P(zv);
4024 			if (is_const) {
4025 				cdata->flags |= ZEND_FFI_FLAG_CONST;
4026 			}
4027 			RETURN_OBJ(&cdata->std);
4028 		} else if (type->kind == ZEND_FFI_TYPE_POINTER && Z_TYPE_P(zv) == IS_NULL) {
4029 			/* null -> pointer */
4030 			cdata = (zend_ffi_cdata*)zend_ffi_cdata_new(zend_ffi_cdata_ce);
4031 			cdata->type = type_ptr;
4032 			cdata->ptr = &cdata->ptr_holder;
4033 			cdata->ptr_holder = NULL;
4034 			if (is_const) {
4035 				cdata->flags |= ZEND_FFI_FLAG_CONST;
4036 			}
4037 			RETURN_OBJ(&cdata->std);
4038 		} else {
4039 			zend_wrong_parameter_class_error(2, "FFI\\CData", zv);
4040 			RETURN_THROWS();
4041 		}
4042 	}
4043 
4044 	old_cdata = (zend_ffi_cdata*)Z_OBJ_P(zv);
4045 	old_type = ZEND_FFI_TYPE(old_cdata->type);
4046 	ptr = old_cdata->ptr;
4047 
4048 	cdata = (zend_ffi_cdata*)zend_ffi_cdata_new(zend_ffi_cdata_ce);
4049 	if (type->kind < ZEND_FFI_TYPE_POINTER) {
4050 		cdata->std.handlers = &zend_ffi_cdata_value_handlers;
4051 	}
4052 	cdata->type = type_ptr;
4053 
4054 	if (old_type->kind == ZEND_FFI_TYPE_POINTER
4055 	 && type->kind != ZEND_FFI_TYPE_POINTER
4056 	 && ZEND_FFI_TYPE(old_type->pointer.type)->kind == ZEND_FFI_TYPE_VOID) {
4057 		/* automatically dereference void* pointers ??? */
4058 		cdata->ptr = *(void**)ptr;
4059 	} else if (old_type->kind == ZEND_FFI_TYPE_ARRAY
4060 	 && type->kind == ZEND_FFI_TYPE_POINTER
4061 	 && zend_ffi_is_compatible_type(ZEND_FFI_TYPE(old_type->array.type), ZEND_FFI_TYPE(type->pointer.type))) {		cdata->ptr = &cdata->ptr_holder;
4062  		cdata->ptr = &cdata->ptr_holder;
4063  		cdata->ptr_holder = old_cdata->ptr;
4064 	} else if (old_type->kind == ZEND_FFI_TYPE_POINTER
4065 	 && type->kind == ZEND_FFI_TYPE_ARRAY
4066 	 && zend_ffi_is_compatible_type(ZEND_FFI_TYPE(old_type->pointer.type), ZEND_FFI_TYPE(type->array.type))) {
4067 		cdata->ptr = old_cdata->ptr_holder;
4068 	} else if (type->size > old_type->size) {
4069 		zend_object_release(&cdata->std);
4070 		zend_throw_error(zend_ffi_exception_ce, "attempt to cast to larger type");
4071 		RETURN_THROWS();
4072 	} else if (ptr != &old_cdata->ptr_holder) {
4073 		cdata->ptr = ptr;
4074 	} else {
4075 		cdata->ptr = &cdata->ptr_holder;
4076 		cdata->ptr_holder = old_cdata->ptr_holder;
4077 	}
4078 	if (is_const) {
4079 		cdata->flags |= ZEND_FFI_FLAG_CONST;
4080 	}
4081 
4082 	if (old_cdata->flags & ZEND_FFI_FLAG_OWNED) {
4083 		if (GC_REFCOUNT(&old_cdata->std) == 1 && Z_REFCOUNT_P(arg) == 1) {
4084 			/* transfer ownership */
4085 			old_cdata->flags &= ~ZEND_FFI_FLAG_OWNED;
4086 			cdata->flags |= ZEND_FFI_FLAG_OWNED;
4087 		} else {
4088 			//???zend_throw_error(zend_ffi_exception_ce, "Attempt to cast owned C pointer");
4089 		}
4090 	}
4091 
4092 	RETURN_OBJ(&cdata->std);
4093 }
4094 /* }}} */
4095 
ZEND_METHOD(FFI,type)4096 ZEND_METHOD(FFI, type) /* {{{ */
4097 {
4098 	zend_ffi_ctype *ctype;
4099 	zend_ffi_dcl dcl = ZEND_FFI_ATTR_INIT;
4100 	zend_string *type_def;
4101 	bool is_static_call = Z_TYPE(EX(This)) != IS_OBJECT;
4102 
4103 	ZEND_FFI_VALIDATE_API_RESTRICTION();
4104 	ZEND_PARSE_PARAMETERS_START(1, 1)
4105 		Z_PARAM_STR(type_def);
4106 	ZEND_PARSE_PARAMETERS_END();
4107 
4108 	if (is_static_call) {
4109 		zend_error(E_DEPRECATED, "Calling FFI::type() statically is deprecated");
4110 		if (EG(exception)) {
4111 			RETURN_THROWS();
4112 		}
4113 	}
4114 
4115 	if (!is_static_call) {
4116 		zend_ffi *ffi = (zend_ffi*)Z_OBJ(EX(This));
4117 		FFI_G(symbols) = ffi->symbols;
4118 		FFI_G(tags) = ffi->tags;
4119 	} else {
4120 		FFI_G(symbols) = NULL;
4121 		FFI_G(tags) = NULL;
4122 	}
4123 	bool clean_symbols = FFI_G(symbols) == NULL;
4124 	bool clean_tags = FFI_G(tags) == NULL;
4125 
4126 	FFI_G(default_type_attr) = 0;
4127 
4128 	if (zend_ffi_parse_type(ZSTR_VAL(type_def), ZSTR_LEN(type_def), &dcl) == FAILURE) {
4129 		zend_ffi_type_dtor(dcl.type);
4130 		if (clean_tags && FFI_G(tags)) {
4131 			zend_hash_destroy(FFI_G(tags));
4132 			efree(FFI_G(tags));
4133 			FFI_G(tags) = NULL;
4134 		}
4135 		if (clean_symbols && FFI_G(symbols)) {
4136 			zend_hash_destroy(FFI_G(symbols));
4137 			efree(FFI_G(symbols));
4138 			FFI_G(symbols) = NULL;
4139 		}
4140 		return;
4141 	}
4142 
4143 	if (clean_tags && FFI_G(tags)) {
4144 		zend_ffi_tags_cleanup(&dcl);
4145 	}
4146 	if (clean_symbols && FFI_G(symbols)) {
4147 		zend_hash_destroy(FFI_G(symbols));
4148 		efree(FFI_G(symbols));
4149 		FFI_G(symbols) = NULL;
4150 	}
4151 	FFI_G(symbols) = NULL;
4152 	FFI_G(tags) = NULL;
4153 
4154 	ctype = (zend_ffi_ctype*)zend_ffi_ctype_new(zend_ffi_ctype_ce);
4155 	ctype->type = dcl.type;
4156 
4157 	RETURN_OBJ(&ctype->std);
4158 }
4159 /* }}} */
4160 
ZEND_METHOD(FFI,typeof)4161 ZEND_METHOD(FFI, typeof) /* {{{ */
4162 {
4163 	zval *zv, *arg;
4164 	zend_ffi_ctype *ctype;
4165 	zend_ffi_type *type;
4166 
4167 	ZEND_FFI_VALIDATE_API_RESTRICTION();
4168 	ZEND_PARSE_PARAMETERS_START(1, 1)
4169 		Z_PARAM_ZVAL(zv);
4170 	ZEND_PARSE_PARAMETERS_END();
4171 
4172 	arg = zv;
4173 	ZVAL_DEREF(zv);
4174 	if (Z_TYPE_P(zv) == IS_OBJECT && Z_OBJCE_P(zv) == zend_ffi_cdata_ce) {
4175 		zend_ffi_cdata *cdata = (zend_ffi_cdata*)Z_OBJ_P(zv);
4176 
4177 		type = cdata->type;
4178 		if (ZEND_FFI_TYPE_IS_OWNED(type)) {
4179 			type = ZEND_FFI_TYPE(type);
4180 			if (!(type->attr & ZEND_FFI_ATTR_STORED)) {
4181 				if (GC_REFCOUNT(&cdata->std) == 1 && Z_REFCOUNT_P(arg) == 1) {
4182 					/* transfer type ownership */
4183 					cdata->type = type;
4184 					type = ZEND_FFI_TYPE_MAKE_OWNED(type);
4185 				} else {
4186 					cdata->type = type = zend_ffi_remember_type(type);
4187 				}
4188 			}
4189 		}
4190 	} else {
4191 		zend_wrong_parameter_class_error(1, "FFI\\CData", zv);
4192 		RETURN_THROWS();
4193 	}
4194 
4195 	ctype = (zend_ffi_ctype*)zend_ffi_ctype_new(zend_ffi_ctype_ce);
4196 	ctype->type = type;
4197 
4198 	RETURN_OBJ(&ctype->std);
4199 }
4200 /* }}} */
4201 
ZEND_METHOD(FFI,arrayType)4202 ZEND_METHOD(FFI, arrayType) /* {{{ */
4203 {
4204 	zval *ztype;
4205 	zend_ffi_ctype *ctype;
4206 	zend_ffi_type *type;
4207 	HashTable *dims;
4208 	zval *val;
4209 
4210 	ZEND_FFI_VALIDATE_API_RESTRICTION();
4211 	ZEND_PARSE_PARAMETERS_START(2, 2)
4212 		Z_PARAM_OBJECT_OF_CLASS(ztype, zend_ffi_ctype_ce)
4213 		Z_PARAM_ARRAY_HT(dims)
4214 	ZEND_PARSE_PARAMETERS_END();
4215 
4216 	ctype = (zend_ffi_ctype*)Z_OBJ_P(ztype);
4217 	type = ZEND_FFI_TYPE(ctype->type);
4218 
4219 	if (type->kind == ZEND_FFI_TYPE_FUNC) {
4220 		zend_throw_error(zend_ffi_exception_ce, "Array of functions is not allowed");
4221 		RETURN_THROWS();
4222 	} else if (type->kind == ZEND_FFI_TYPE_ARRAY && (type->attr & ZEND_FFI_ATTR_INCOMPLETE_ARRAY)) {
4223 		zend_throw_error(zend_ffi_exception_ce, "Only the leftmost array can be undimensioned");
4224 		RETURN_THROWS();
4225 	} else if (type->kind == ZEND_FFI_TYPE_VOID) {
4226 		zend_throw_error(zend_ffi_exception_ce, "Array of void type is not allowed");
4227 		RETURN_THROWS();
4228 	} else if (type->attr & ZEND_FFI_ATTR_INCOMPLETE_TAG) {
4229 		zend_throw_error(zend_ffi_exception_ce, "Array of incomplete type is not allowed");
4230 		RETURN_THROWS();
4231 	}
4232 
4233 	if (ZEND_FFI_TYPE_IS_OWNED(ctype->type)) {
4234 		if (!(type->attr & ZEND_FFI_ATTR_STORED)) {
4235 			if (GC_REFCOUNT(&ctype->std) == 1) {
4236 				/* transfer type ownership */
4237 				ctype->type = type;
4238 				type = ZEND_FFI_TYPE_MAKE_OWNED(type);
4239 			} else {
4240 				ctype->type = type = zend_ffi_remember_type(type);
4241 			}
4242 		}
4243 	}
4244 
4245 	ZEND_HASH_REVERSE_FOREACH_VAL(dims, val) {
4246 		zend_long n = zval_get_long(val);
4247 		zend_ffi_type *new_type;
4248 
4249 		if (n < 0) {
4250 			zend_throw_error(zend_ffi_exception_ce, "negative array index");
4251 			zend_ffi_type_dtor(type);
4252 			RETURN_THROWS();
4253 		} else if (ZEND_FFI_TYPE(type)->kind == ZEND_FFI_TYPE_ARRAY && (ZEND_FFI_TYPE(type)->attr & ZEND_FFI_ATTR_INCOMPLETE_ARRAY)) {
4254 			zend_throw_error(zend_ffi_exception_ce, "only the leftmost array can be undimensioned");
4255 			zend_ffi_type_dtor(type);
4256 			RETURN_THROWS();
4257 		}
4258 
4259 		new_type = emalloc(sizeof(zend_ffi_type));
4260 		new_type->kind = ZEND_FFI_TYPE_ARRAY;
4261 		new_type->attr = 0;
4262 		new_type->size = n * ZEND_FFI_TYPE(type)->size;
4263 		new_type->align = ZEND_FFI_TYPE(type)->align;
4264 		new_type->array.type = type;
4265 		new_type->array.length = n;
4266 
4267 		if (n == 0) {
4268 			new_type->attr |= ZEND_FFI_ATTR_INCOMPLETE_ARRAY;
4269 		}
4270 
4271 		type = ZEND_FFI_TYPE_MAKE_OWNED(new_type);
4272 	} ZEND_HASH_FOREACH_END();
4273 
4274 	ctype = (zend_ffi_ctype*)zend_ffi_ctype_new(zend_ffi_ctype_ce);
4275 	ctype->type = type;
4276 
4277 	RETURN_OBJ(&ctype->std);
4278 }
4279 /* }}} */
4280 
ZEND_METHOD(FFI,addr)4281 ZEND_METHOD(FFI, addr) /* {{{ */
4282 {
4283 	zend_ffi_type *type, *new_type;
4284 	zend_ffi_cdata *cdata, *new_cdata;
4285 	zval *zv, *arg;
4286 
4287 	ZEND_FFI_VALIDATE_API_RESTRICTION();
4288 	ZEND_PARSE_PARAMETERS_START(1, 1)
4289 		Z_PARAM_ZVAL(zv)
4290 	ZEND_PARSE_PARAMETERS_END();
4291 
4292 	arg = zv;
4293 	ZVAL_DEREF(zv);
4294 	if (Z_TYPE_P(zv) != IS_OBJECT || Z_OBJCE_P(zv) != zend_ffi_cdata_ce) {
4295 		zend_wrong_parameter_class_error(1, "FFI\\CData", zv);
4296 		RETURN_THROWS();
4297 	}
4298 
4299 	cdata = (zend_ffi_cdata*)Z_OBJ_P(zv);
4300 	type = ZEND_FFI_TYPE(cdata->type);
4301 
4302 	if (GC_REFCOUNT(&cdata->std) == 1 && Z_REFCOUNT_P(arg) == 1 && type->kind == ZEND_FFI_TYPE_POINTER
4303 	 && cdata->ptr == &cdata->ptr_holder) {
4304 		zend_throw_error(zend_ffi_exception_ce, "FFI::addr() cannot create a reference to a temporary pointer");
4305 		RETURN_THROWS();
4306 	}
4307 
4308 	new_type = emalloc(sizeof(zend_ffi_type));
4309 	new_type->kind = ZEND_FFI_TYPE_POINTER;
4310 	new_type->attr = 0;
4311 	new_type->size = sizeof(void*);
4312 	new_type->align = _Alignof(void*);
4313 	/* life-time (source must relive the resulting pointer) ??? */
4314 	new_type->pointer.type = type;
4315 
4316 	new_cdata = (zend_ffi_cdata*)zend_ffi_cdata_new(zend_ffi_cdata_ce);
4317 	new_cdata->type = ZEND_FFI_TYPE_MAKE_OWNED(new_type);
4318 	new_cdata->ptr_holder = cdata->ptr;
4319 	new_cdata->ptr = &new_cdata->ptr_holder;
4320 
4321 	if (GC_REFCOUNT(&cdata->std) == 1 && Z_REFCOUNT_P(arg) == 1) {
4322 		if (ZEND_FFI_TYPE_IS_OWNED(cdata->type)) {
4323 			/* transfer type ownership */
4324 			cdata->type = type;
4325 			new_type->pointer.type = ZEND_FFI_TYPE_MAKE_OWNED(type);
4326 		}
4327 		if (cdata->flags & ZEND_FFI_FLAG_OWNED) {
4328 			/* transfer ownership */
4329 			cdata->flags &= ~ZEND_FFI_FLAG_OWNED;
4330 			new_cdata->flags |= ZEND_FFI_FLAG_OWNED;
4331 		}
4332 	}
4333 
4334 	RETURN_OBJ(&new_cdata->std);
4335 }
4336 /* }}} */
4337 
ZEND_METHOD(FFI,sizeof)4338 ZEND_METHOD(FFI, sizeof) /* {{{ */
4339 {
4340 	zval *zv;
4341 	zend_ffi_type *type;
4342 
4343 	ZEND_FFI_VALIDATE_API_RESTRICTION();
4344 	ZEND_PARSE_PARAMETERS_START(1, 1)
4345 		Z_PARAM_ZVAL(zv);
4346 	ZEND_PARSE_PARAMETERS_END();
4347 
4348 	ZVAL_DEREF(zv);
4349 	if (Z_TYPE_P(zv) == IS_OBJECT && Z_OBJCE_P(zv) == zend_ffi_cdata_ce) {
4350 		zend_ffi_cdata *cdata = (zend_ffi_cdata*)Z_OBJ_P(zv);
4351 		type = ZEND_FFI_TYPE(cdata->type);
4352 	} else if (Z_TYPE_P(zv) == IS_OBJECT && Z_OBJCE_P(zv) == zend_ffi_ctype_ce) {
4353 		zend_ffi_ctype *ctype = (zend_ffi_ctype*)Z_OBJ_P(zv);
4354 		type = ZEND_FFI_TYPE(ctype->type);
4355 	} else {
4356 		zend_wrong_parameter_class_error(1, "FFI\\CData or FFI\\CType", zv);
4357 		RETURN_THROWS();
4358 	}
4359 
4360 	RETURN_LONG(type->size);
4361 }
4362 /* }}} */
4363 
ZEND_METHOD(FFI,alignof)4364 ZEND_METHOD(FFI, alignof) /* {{{ */
4365 {
4366 	zval *zv;
4367 	zend_ffi_type *type;
4368 
4369 	ZEND_FFI_VALIDATE_API_RESTRICTION();
4370 	ZEND_PARSE_PARAMETERS_START(1, 1)
4371 		Z_PARAM_ZVAL(zv);
4372 	ZEND_PARSE_PARAMETERS_END();
4373 
4374 	ZVAL_DEREF(zv);
4375 	if (Z_TYPE_P(zv) == IS_OBJECT && Z_OBJCE_P(zv) == zend_ffi_cdata_ce) {
4376 		zend_ffi_cdata *cdata = (zend_ffi_cdata*)Z_OBJ_P(zv);
4377 		type = ZEND_FFI_TYPE(cdata->type);
4378 	} else if (Z_TYPE_P(zv) == IS_OBJECT && Z_OBJCE_P(zv) == zend_ffi_ctype_ce) {
4379 		zend_ffi_ctype *ctype = (zend_ffi_ctype*)Z_OBJ_P(zv);
4380 		type = ZEND_FFI_TYPE(ctype->type);
4381 	} else {
4382 		zend_wrong_parameter_class_error(1, "FFI\\CData or FFI\\CType", zv);
4383 		RETURN_THROWS();
4384 	}
4385 
4386 	RETURN_LONG(type->align);
4387 }
4388 /* }}} */
4389 
ZEND_METHOD(FFI,memcpy)4390 ZEND_METHOD(FFI, memcpy) /* {{{ */
4391 {
4392 	zval *zv1, *zv2;
4393 	zend_ffi_cdata *cdata1, *cdata2;
4394 	zend_ffi_type *type1, *type2;
4395 	void *ptr1, *ptr2;
4396 	zend_long size;
4397 
4398 	ZEND_FFI_VALIDATE_API_RESTRICTION();
4399 	ZEND_PARSE_PARAMETERS_START(3, 3)
4400 		Z_PARAM_OBJECT_OF_CLASS_EX(zv1, zend_ffi_cdata_ce, 0, 1);
4401 		Z_PARAM_ZVAL(zv2)
4402 		Z_PARAM_LONG(size)
4403 	ZEND_PARSE_PARAMETERS_END();
4404 
4405 	cdata1 = (zend_ffi_cdata*)Z_OBJ_P(zv1);
4406 	type1 = ZEND_FFI_TYPE(cdata1->type);
4407 	if (type1->kind == ZEND_FFI_TYPE_POINTER) {
4408 		ptr1 = *(void**)cdata1->ptr;
4409 	} else {
4410 		ptr1 = cdata1->ptr;
4411 		if (type1->kind != ZEND_FFI_TYPE_POINTER && size > type1->size) {
4412 			zend_throw_error(zend_ffi_exception_ce, "Attempt to write over data boundary");
4413 			RETURN_THROWS();
4414 		}
4415 	}
4416 
4417 	ZVAL_DEREF(zv2);
4418 	if (Z_TYPE_P(zv2) == IS_STRING) {
4419 		ptr2 = Z_STRVAL_P(zv2);
4420 		if (size > Z_STRLEN_P(zv2)) {
4421 			zend_throw_error(zend_ffi_exception_ce, "Attempt to read over string boundary");
4422 			RETURN_THROWS();
4423 		}
4424 	} else if (Z_TYPE_P(zv2) == IS_OBJECT && Z_OBJCE_P(zv2) == zend_ffi_cdata_ce) {
4425 		cdata2 = (zend_ffi_cdata*)Z_OBJ_P(zv2);
4426 		type2 = ZEND_FFI_TYPE(cdata2->type);
4427 		if (type2->kind == ZEND_FFI_TYPE_POINTER) {
4428 			ptr2 = *(void**)cdata2->ptr;
4429 		} else {
4430 			ptr2 = cdata2->ptr;
4431 			if (type2->kind != ZEND_FFI_TYPE_POINTER && size > type2->size) {
4432 				zend_throw_error(zend_ffi_exception_ce, "Attempt to read over data boundary");
4433 				RETURN_THROWS();
4434 			}
4435 		}
4436 	} else {
4437 		zend_wrong_parameter_class_error(2, "FFI\\CData or string", zv2);
4438 		RETURN_THROWS();
4439 	}
4440 
4441 	memcpy(ptr1, ptr2, size);
4442 }
4443 /* }}} */
4444 
ZEND_METHOD(FFI,memcmp)4445 ZEND_METHOD(FFI, memcmp) /* {{{ */
4446 {
4447 	zval *zv1, *zv2;
4448 	zend_ffi_cdata *cdata1, *cdata2;
4449 	zend_ffi_type *type1, *type2;
4450 	void *ptr1, *ptr2;
4451 	zend_long size;
4452 	int ret;
4453 
4454 	ZEND_FFI_VALIDATE_API_RESTRICTION();
4455 	ZEND_PARSE_PARAMETERS_START(3, 3)
4456 		Z_PARAM_ZVAL(zv1);
4457 		Z_PARAM_ZVAL(zv2);
4458 		Z_PARAM_LONG(size)
4459 	ZEND_PARSE_PARAMETERS_END();
4460 
4461 	ZVAL_DEREF(zv1);
4462 	if (Z_TYPE_P(zv1) == IS_STRING) {
4463 		ptr1 = Z_STRVAL_P(zv1);
4464 		if (size > Z_STRLEN_P(zv1)) {
4465 			zend_throw_error(zend_ffi_exception_ce, "attempt to read over string boundary");
4466 			RETURN_THROWS();
4467 		}
4468 	} else if (Z_TYPE_P(zv1) == IS_OBJECT && Z_OBJCE_P(zv1) == zend_ffi_cdata_ce) {
4469 		cdata1 = (zend_ffi_cdata*)Z_OBJ_P(zv1);
4470 		type1 = ZEND_FFI_TYPE(cdata1->type);
4471 		if (type1->kind == ZEND_FFI_TYPE_POINTER) {
4472 			ptr1 = *(void**)cdata1->ptr;
4473 		} else {
4474 			ptr1 = cdata1->ptr;
4475 			if (type1->kind != ZEND_FFI_TYPE_POINTER && size > type1->size) {
4476 				zend_throw_error(zend_ffi_exception_ce, "attempt to read over data boundary");
4477 				RETURN_THROWS();
4478 			}
4479 		}
4480 	} else {
4481 		zend_wrong_parameter_class_error(1, "FFI\\CData or string", zv1);
4482 		RETURN_THROWS();
4483 	}
4484 
4485 	ZVAL_DEREF(zv2);
4486 	if (Z_TYPE_P(zv2) == IS_STRING) {
4487 		ptr2 = Z_STRVAL_P(zv2);
4488 		if (size > Z_STRLEN_P(zv2)) {
4489 			zend_throw_error(zend_ffi_exception_ce, "Attempt to read over string boundary");
4490 			RETURN_THROWS();
4491 		}
4492 	} else if (Z_TYPE_P(zv2) == IS_OBJECT && Z_OBJCE_P(zv2) == zend_ffi_cdata_ce) {
4493 		cdata2 = (zend_ffi_cdata*)Z_OBJ_P(zv2);
4494 		type2 = ZEND_FFI_TYPE(cdata2->type);
4495 		if (type2->kind == ZEND_FFI_TYPE_POINTER) {
4496 			ptr2 = *(void**)cdata2->ptr;
4497 		} else {
4498 			ptr2 = cdata2->ptr;
4499 			if (type2->kind != ZEND_FFI_TYPE_POINTER && size > type2->size) {
4500 				zend_throw_error(zend_ffi_exception_ce, "Attempt to read over data boundary");
4501 				RETURN_THROWS();
4502 			}
4503 		}
4504 	} else {
4505 		zend_wrong_parameter_class_error(2, "FFI\\CData or string", zv2);
4506 		RETURN_THROWS();
4507 	}
4508 
4509 	ret = memcmp(ptr1, ptr2, size);
4510 	if (ret == 0) {
4511 		RETVAL_LONG(0);
4512 	} else if (ret < 0) {
4513 		RETVAL_LONG(-1);
4514 	} else {
4515 		RETVAL_LONG(1);
4516 	}
4517 }
4518 /* }}} */
4519 
ZEND_METHOD(FFI,memset)4520 ZEND_METHOD(FFI, memset) /* {{{ */
4521 {
4522 	zval *zv;
4523 	zend_ffi_cdata *cdata;
4524 	zend_ffi_type *type;
4525 	void *ptr;
4526 	zend_long ch, size;
4527 
4528 	ZEND_FFI_VALIDATE_API_RESTRICTION();
4529 	ZEND_PARSE_PARAMETERS_START(3, 3)
4530 		Z_PARAM_OBJECT_OF_CLASS_EX(zv, zend_ffi_cdata_ce, 0, 1);
4531 		Z_PARAM_LONG(ch)
4532 		Z_PARAM_LONG(size)
4533 	ZEND_PARSE_PARAMETERS_END();
4534 
4535 	cdata = (zend_ffi_cdata*)Z_OBJ_P(zv);
4536 	type = ZEND_FFI_TYPE(cdata->type);
4537 	if (type->kind == ZEND_FFI_TYPE_POINTER) {
4538 		ptr = *(void**)cdata->ptr;
4539 	} else {
4540 		ptr = cdata->ptr;
4541 		if (type->kind != ZEND_FFI_TYPE_POINTER && size > type->size) {
4542 			zend_throw_error(zend_ffi_exception_ce, "attempt to write over data boundary");
4543 			RETURN_THROWS();
4544 		}
4545 	}
4546 
4547 	memset(ptr, ch, size);
4548 }
4549 /* }}} */
4550 
ZEND_METHOD(FFI,string)4551 ZEND_METHOD(FFI, string) /* {{{ */
4552 {
4553 	zval *zv;
4554 	zend_ffi_cdata *cdata;
4555 	zend_ffi_type *type;
4556 	void *ptr;
4557 	zend_long size;
4558 	bool size_is_null = 1;
4559 
4560 	ZEND_FFI_VALIDATE_API_RESTRICTION();
4561 	ZEND_PARSE_PARAMETERS_START(1, 2)
4562 		Z_PARAM_OBJECT_OF_CLASS_EX(zv, zend_ffi_cdata_ce, 0, 1);
4563 		Z_PARAM_OPTIONAL
4564 		Z_PARAM_LONG_OR_NULL(size, size_is_null)
4565 	ZEND_PARSE_PARAMETERS_END();
4566 
4567 	cdata = (zend_ffi_cdata*)Z_OBJ_P(zv);
4568 	type = ZEND_FFI_TYPE(cdata->type);
4569 	if (!size_is_null) {
4570 		if (type->kind == ZEND_FFI_TYPE_POINTER) {
4571 			ptr = *(void**)cdata->ptr;
4572 		} else {
4573 			ptr = cdata->ptr;
4574 			if (type->kind != ZEND_FFI_TYPE_POINTER && size > type->size) {
4575 				zend_throw_error(zend_ffi_exception_ce, "attempt to read over data boundary");
4576 				RETURN_THROWS();
4577 			}
4578 		}
4579 		RETURN_STRINGL((char*)ptr, size);
4580 	} else {
4581 		if (type->kind == ZEND_FFI_TYPE_POINTER && ZEND_FFI_TYPE(type->pointer.type)->kind == ZEND_FFI_TYPE_CHAR) {
4582 			ptr = *(void**)cdata->ptr;
4583 		} else if (type->kind == ZEND_FFI_TYPE_ARRAY && ZEND_FFI_TYPE(type->array.type)->kind == ZEND_FFI_TYPE_CHAR) {
4584 			ptr = cdata->ptr;
4585 		} else {
4586 			zend_throw_error(zend_ffi_exception_ce, "FFI\\Cdata is not a C string");
4587 			RETURN_THROWS();
4588 		}
4589 		RETURN_STRING((char*)ptr);
4590 	}
4591 }
4592 /* }}} */
4593 
ZEND_METHOD(FFI,isNull)4594 ZEND_METHOD(FFI, isNull) /* {{{ */
4595 {
4596 	zval *zv;
4597 	zend_ffi_cdata *cdata;
4598 	zend_ffi_type *type;
4599 
4600 	ZEND_FFI_VALIDATE_API_RESTRICTION();
4601 	ZEND_PARSE_PARAMETERS_START(1, 1)
4602 		Z_PARAM_ZVAL(zv);
4603 	ZEND_PARSE_PARAMETERS_END();
4604 
4605 	ZVAL_DEREF(zv);
4606 	if (Z_TYPE_P(zv) != IS_OBJECT || Z_OBJCE_P(zv) != zend_ffi_cdata_ce) {
4607 		zend_wrong_parameter_class_error(1, "FFI\\CData", zv);
4608 		RETURN_THROWS();
4609 	}
4610 
4611 	cdata = (zend_ffi_cdata*)Z_OBJ_P(zv);
4612 	type = ZEND_FFI_TYPE(cdata->type);
4613 
4614 	if (type->kind != ZEND_FFI_TYPE_POINTER){
4615 		zend_throw_error(zend_ffi_exception_ce, "FFI\\Cdata is not a pointer");
4616 		RETURN_THROWS();
4617 	}
4618 
4619 	RETURN_BOOL(*(void**)cdata->ptr == NULL);
4620 }
4621 /* }}} */
4622 
4623 
ZEND_METHOD(FFI_CType,getName)4624 ZEND_METHOD(FFI_CType, getName) /* {{{ */
4625 {
4626 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)(Z_OBJ_P(ZEND_THIS));
4627 	if (zend_parse_parameters_none() == FAILURE) {
4628 		RETURN_THROWS();
4629 	}
4630 
4631 	zend_ffi_ctype_name_buf buf;
4632 
4633 	buf.start = buf.end = buf.buf + ((MAX_TYPE_NAME_LEN * 3) / 4);
4634 	if (!zend_ffi_ctype_name(&buf, ZEND_FFI_TYPE(ctype->type))) {
4635 		RETURN_STR_COPY(Z_OBJ_P(ZEND_THIS)->ce->name);
4636 	} else {
4637 		size_t len = buf.end - buf.start;
4638 		zend_string *res = zend_string_init(buf.start, len, 0);
4639 		RETURN_STR(res);
4640 	}
4641 }
4642 /* }}} */
4643 
ZEND_METHOD(FFI_CType,getKind)4644 ZEND_METHOD(FFI_CType, getKind) /* {{{ */
4645 {
4646 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)(Z_OBJ_P(ZEND_THIS));
4647 	zend_ffi_type *type;
4648 
4649 	if (zend_parse_parameters_none() == FAILURE) {
4650 		RETURN_THROWS();
4651 	}
4652 
4653 	type = ZEND_FFI_TYPE(ctype->type);
4654 	RETURN_LONG(type->kind);
4655 }
4656 /* }}} */
4657 
ZEND_METHOD(FFI_CType,getSize)4658 ZEND_METHOD(FFI_CType, getSize) /* {{{ */
4659 {
4660 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)(Z_OBJ_P(ZEND_THIS));
4661 	zend_ffi_type *type;
4662 
4663 	if (zend_parse_parameters_none() == FAILURE) {
4664 		RETURN_THROWS();
4665 	}
4666 
4667 	type = ZEND_FFI_TYPE(ctype->type);
4668 	RETURN_LONG(type->size);
4669 }
4670 /* }}} */
4671 
ZEND_METHOD(FFI_CType,getAlignment)4672 ZEND_METHOD(FFI_CType, getAlignment) /* {{{ */
4673 {
4674 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)(Z_OBJ_P(ZEND_THIS));
4675 	zend_ffi_type *type;
4676 
4677 	if (zend_parse_parameters_none() == FAILURE) {
4678 		RETURN_THROWS();
4679 	}
4680 
4681 	type = ZEND_FFI_TYPE(ctype->type);
4682 	RETURN_LONG(type->align);
4683 }
4684 /* }}} */
4685 
ZEND_METHOD(FFI_CType,getAttributes)4686 ZEND_METHOD(FFI_CType, getAttributes) /* {{{ */
4687 {
4688 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)(Z_OBJ_P(ZEND_THIS));
4689 	zend_ffi_type *type;
4690 
4691 	if (zend_parse_parameters_none() == FAILURE) {
4692 		RETURN_THROWS();
4693 	}
4694 
4695 	type = ZEND_FFI_TYPE(ctype->type);
4696 	RETURN_LONG(type->attr);
4697 }
4698 /* }}} */
4699 
ZEND_METHOD(FFI_CType,getEnumKind)4700 ZEND_METHOD(FFI_CType, getEnumKind) /* {{{ */
4701 {
4702 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)(Z_OBJ_P(ZEND_THIS));
4703 	zend_ffi_type *type;
4704 
4705 	if (zend_parse_parameters_none() == FAILURE) {
4706 		RETURN_THROWS();
4707 	}
4708 
4709 	type = ZEND_FFI_TYPE(ctype->type);
4710 	if (type->kind != ZEND_FFI_TYPE_ENUM) {
4711 		zend_throw_error(zend_ffi_exception_ce, "FFI\\CType is not an enumeration");
4712 		RETURN_THROWS();
4713 	}
4714 	RETURN_LONG(type->enumeration.kind);
4715 }
4716 /* }}} */
4717 
ZEND_METHOD(FFI_CType,getArrayElementType)4718 ZEND_METHOD(FFI_CType, getArrayElementType) /* {{{ */
4719 {
4720 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)(Z_OBJ_P(ZEND_THIS));
4721 	zend_ffi_type *type;
4722 	zend_ffi_ctype *ret;
4723 
4724 	if (zend_parse_parameters_none() == FAILURE) {
4725 		RETURN_THROWS();
4726 	}
4727 
4728 	type = ZEND_FFI_TYPE(ctype->type);
4729 	if (type->kind != ZEND_FFI_TYPE_ARRAY) {
4730 		zend_throw_error(zend_ffi_exception_ce, "FFI\\CType is not an array");
4731 		RETURN_THROWS();
4732 	}
4733 
4734 	ret = (zend_ffi_ctype*)zend_ffi_ctype_new(zend_ffi_ctype_ce);
4735 	ret->type = ZEND_FFI_TYPE(type->array.type);
4736 	RETURN_OBJ(&ret->std);
4737 }
4738 /* }}} */
4739 
ZEND_METHOD(FFI_CType,getArrayLength)4740 ZEND_METHOD(FFI_CType, getArrayLength) /* {{{ */
4741 {
4742 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)(Z_OBJ_P(ZEND_THIS));
4743 	zend_ffi_type *type;
4744 
4745 	if (zend_parse_parameters_none() == FAILURE) {
4746 		RETURN_THROWS();
4747 	}
4748 
4749 	type = ZEND_FFI_TYPE(ctype->type);
4750 	if (type->kind != ZEND_FFI_TYPE_ARRAY) {
4751 		zend_throw_error(zend_ffi_exception_ce, "FFI\\CType is not an array");
4752 		RETURN_THROWS();
4753 	}
4754 	RETURN_LONG(type->array.length);
4755 }
4756 /* }}} */
4757 
ZEND_METHOD(FFI_CType,getPointerType)4758 ZEND_METHOD(FFI_CType, getPointerType) /* {{{ */
4759 {
4760 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)(Z_OBJ_P(ZEND_THIS));
4761 	zend_ffi_ctype *ret;
4762 	zend_ffi_type *type;
4763 
4764 	if (zend_parse_parameters_none() == FAILURE) {
4765 		RETURN_THROWS();
4766 	}
4767 
4768 	type = ZEND_FFI_TYPE(ctype->type);
4769 	if (type->kind != ZEND_FFI_TYPE_POINTER) {
4770 		zend_throw_error(zend_ffi_exception_ce, "FFI\\CType is not a pointer");
4771 		RETURN_THROWS();
4772 	}
4773 
4774 	ret = (zend_ffi_ctype*)zend_ffi_ctype_new(zend_ffi_ctype_ce);
4775 	ret->type = ZEND_FFI_TYPE(type->pointer.type);
4776 	RETURN_OBJ(&ret->std);
4777 }
4778 /* }}} */
4779 
ZEND_METHOD(FFI_CType,getStructFieldNames)4780 ZEND_METHOD(FFI_CType, getStructFieldNames) /* {{{ */
4781 {
4782 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)(Z_OBJ_P(ZEND_THIS));
4783 	zend_ffi_type *type;
4784 	HashTable *ht;
4785 	zend_string* name;
4786 	zval zv;
4787 
4788 	if (zend_parse_parameters_none() == FAILURE) {
4789 		RETURN_THROWS();
4790 	}
4791 
4792 	type = ZEND_FFI_TYPE(ctype->type);
4793 	if (type->kind != ZEND_FFI_TYPE_STRUCT) {
4794 		zend_throw_error(zend_ffi_exception_ce, "FFI\\CType is not a structure");
4795 		RETURN_THROWS();
4796 	}
4797 
4798 	ht = zend_new_array(zend_hash_num_elements(&type->record.fields));
4799 	RETVAL_ARR(ht);
4800 	ZEND_HASH_MAP_FOREACH_STR_KEY(&type->record.fields, name) {
4801 		ZVAL_STR_COPY(&zv, name);
4802 		zend_hash_next_index_insert_new(ht, &zv);
4803 	} ZEND_HASH_FOREACH_END();
4804 }
4805 /* }}} */
4806 
ZEND_METHOD(FFI_CType,getStructFieldOffset)4807 ZEND_METHOD(FFI_CType, getStructFieldOffset) /* {{{ */
4808 {
4809 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)(Z_OBJ_P(ZEND_THIS));
4810 	zend_ffi_type *type;
4811 	zend_string *name;
4812 	zend_ffi_field *ptr;
4813 
4814 	ZEND_PARSE_PARAMETERS_START(1, 1)
4815 		Z_PARAM_STR(name)
4816 	ZEND_PARSE_PARAMETERS_END();
4817 
4818 	type = ZEND_FFI_TYPE(ctype->type);
4819 	if (type->kind != ZEND_FFI_TYPE_STRUCT) {
4820 		zend_throw_error(zend_ffi_exception_ce, "FFI\\CType is not a structure");
4821 		RETURN_THROWS();
4822 	}
4823 
4824 	ptr = zend_hash_find_ptr(&type->record.fields, name);
4825 	if (!ptr) {
4826 		zend_throw_error(zend_ffi_exception_ce, "Wrong field name");
4827 		RETURN_THROWS();
4828 	}
4829 	RETURN_LONG(ptr->offset);
4830 }
4831 /* }}} */
4832 
ZEND_METHOD(FFI_CType,getStructFieldType)4833 ZEND_METHOD(FFI_CType, getStructFieldType) /* {{{ */
4834 {
4835 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)(Z_OBJ_P(ZEND_THIS));
4836 	zend_ffi_type *type;
4837 	zend_string *name;
4838 	zend_ffi_field *ptr;
4839 	zend_ffi_ctype *ret;
4840 
4841 	ZEND_PARSE_PARAMETERS_START(1, 1)
4842 		Z_PARAM_STR(name)
4843 	ZEND_PARSE_PARAMETERS_END();
4844 
4845 	type = ZEND_FFI_TYPE(ctype->type);
4846 	if (type->kind != ZEND_FFI_TYPE_STRUCT) {
4847 		zend_throw_error(zend_ffi_exception_ce, "FFI\\CType is not a structure");
4848 		RETURN_THROWS();
4849 	}
4850 
4851 	ptr = zend_hash_find_ptr(&type->record.fields, name);
4852 	if (!ptr) {
4853 		zend_throw_error(zend_ffi_exception_ce, "Wrong field name");
4854 		RETURN_THROWS();
4855 	}
4856 
4857 	ret = (zend_ffi_ctype*)zend_ffi_ctype_new(zend_ffi_ctype_ce);
4858 	ret->type = ZEND_FFI_TYPE(ptr->type);
4859 	RETURN_OBJ(&ret->std);
4860 }
4861 /* }}} */
4862 
ZEND_METHOD(FFI_CType,getFuncABI)4863 ZEND_METHOD(FFI_CType, getFuncABI) /* {{{ */
4864 {
4865 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)(Z_OBJ_P(ZEND_THIS));
4866 	zend_ffi_type *type;
4867 
4868 	if (zend_parse_parameters_none() == FAILURE) {
4869 		RETURN_THROWS();
4870 	}
4871 
4872 	type = ZEND_FFI_TYPE(ctype->type);
4873 	if (type->kind != ZEND_FFI_TYPE_FUNC) {
4874 		zend_throw_error(zend_ffi_exception_ce, "FFI\\CType is not a function");
4875 		RETURN_THROWS();
4876 	}
4877 	RETURN_LONG(type->func.abi);
4878 }
4879 /* }}} */
4880 
ZEND_METHOD(FFI_CType,getFuncReturnType)4881 ZEND_METHOD(FFI_CType, getFuncReturnType) /* {{{ */
4882 {
4883 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)(Z_OBJ_P(ZEND_THIS));
4884 	zend_ffi_ctype *ret;
4885 	zend_ffi_type *type;
4886 
4887 	if (zend_parse_parameters_none() == FAILURE) {
4888 		RETURN_THROWS();
4889 	}
4890 
4891 	type = ZEND_FFI_TYPE(ctype->type);
4892 	if (type->kind != ZEND_FFI_TYPE_FUNC) {
4893 		zend_throw_error(zend_ffi_exception_ce, "FFI\\CType is not a function");
4894 		RETURN_THROWS();
4895 	}
4896 
4897 	ret = (zend_ffi_ctype*)zend_ffi_ctype_new(zend_ffi_ctype_ce);
4898 	ret->type = ZEND_FFI_TYPE(type->func.ret_type);
4899 	RETURN_OBJ(&ret->std);
4900 }
4901 /* }}} */
4902 
ZEND_METHOD(FFI_CType,getFuncParameterCount)4903 ZEND_METHOD(FFI_CType, getFuncParameterCount) /* {{{ */
4904 {
4905 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)(Z_OBJ_P(ZEND_THIS));
4906 	zend_ffi_type *type;
4907 
4908 	if (zend_parse_parameters_none() == FAILURE) {
4909 		RETURN_THROWS();
4910 	}
4911 
4912 	type = ZEND_FFI_TYPE(ctype->type);
4913 	if (type->kind != ZEND_FFI_TYPE_FUNC) {
4914 		zend_throw_error(zend_ffi_exception_ce, "FFI\\CType is not a function");
4915 		RETURN_THROWS();
4916 	}
4917 	RETURN_LONG(type->func.args ? zend_hash_num_elements(type->func.args) : 0);
4918 }
4919 /* }}} */
4920 
ZEND_METHOD(FFI_CType,getFuncParameterType)4921 ZEND_METHOD(FFI_CType, getFuncParameterType) /* {{{ */
4922 {
4923 	zend_ffi_ctype *ctype = (zend_ffi_ctype*)(Z_OBJ_P(ZEND_THIS));
4924 	zend_ffi_type *type, *ptr;
4925 	zend_long n;
4926 	zend_ffi_ctype *ret;
4927 
4928 	ZEND_PARSE_PARAMETERS_START(1, 1)
4929 		Z_PARAM_LONG(n)
4930 	ZEND_PARSE_PARAMETERS_END();
4931 
4932 	type = ZEND_FFI_TYPE(ctype->type);
4933 	if (type->kind != ZEND_FFI_TYPE_FUNC) {
4934 		zend_throw_error(zend_ffi_exception_ce, "FFI\\CType is not a function");
4935 		RETURN_THROWS();
4936 	}
4937 
4938 	if (!type->func.args) {
4939 		zend_throw_error(zend_ffi_exception_ce, "Wrong argument number");
4940 		RETURN_THROWS();
4941 	}
4942 
4943 	ptr = zend_hash_index_find_ptr(type->func.args, n);
4944 	if (!ptr) {
4945 		zend_throw_error(zend_ffi_exception_ce, "Wrong argument number");
4946 		RETURN_THROWS();
4947 	}
4948 
4949 	ret = (zend_ffi_ctype*)zend_ffi_ctype_new(zend_ffi_ctype_ce);
4950 	ret->type = ZEND_FFI_TYPE(ptr);
4951 	RETURN_OBJ(&ret->std);
4952 }
4953 /* }}} */
4954 
zend_ffi_parse_directives(const char * filename,char * code_pos,char ** scope_name,char ** lib,bool preload)4955 static char *zend_ffi_parse_directives(const char *filename, char *code_pos, char **scope_name, char **lib, bool preload) /* {{{ */
4956 {
4957 	char *p;
4958 
4959 	*scope_name = NULL;
4960 	*lib = NULL;
4961 	while (*code_pos == '#') {
4962 		if (strncmp(code_pos, "#define FFI_SCOPE", sizeof("#define FFI_SCOPE") - 1) == 0
4963 		 && (code_pos[sizeof("#define FFI_SCOPE") - 1] == ' '
4964 		  || code_pos[sizeof("#define FFI_SCOPE") - 1] == '\t')) {
4965 			p = code_pos + sizeof("#define FFI_SCOPE");
4966 			while (*p == ' ' || *p == '\t') {
4967 				p++;
4968 			}
4969 			if (*p != '"') {
4970 				if (preload) {
4971 					zend_error(E_WARNING, "FFI: failed pre-loading '%s', bad FFI_SCOPE define", filename);
4972 				} else {
4973 					zend_throw_error(zend_ffi_exception_ce, "Failed loading '%s', bad FFI_SCOPE define", filename);
4974 				}
4975 				return NULL;
4976 			}
4977 			p++;
4978 			if (*scope_name) {
4979 				if (preload) {
4980 					zend_error(E_WARNING, "FFI: failed pre-loading '%s', FFI_SCOPE defined twice", filename);
4981 				} else {
4982 					zend_throw_error(zend_ffi_exception_ce, "Failed loading '%s', FFI_SCOPE defined twice", filename);
4983 				}
4984 				return NULL;
4985 			}
4986 			*scope_name = p;
4987 			while (1) {
4988 				if (*p == '\"') {
4989 					*p = 0;
4990 					p++;
4991 					break;
4992 				} else if (*p <= ' ') {
4993 					if (preload) {
4994 						zend_error(E_WARNING, "FFI: failed pre-loading '%s', bad FFI_SCOPE define", filename);
4995 					} else {
4996 						zend_throw_error(zend_ffi_exception_ce, "Failed loading '%s', bad FFI_SCOPE define", filename);
4997 					}
4998 					return NULL;
4999 				}
5000 				p++;
5001 			}
5002 			while (*p == ' ' || *p == '\t') {
5003 				p++;
5004 			}
5005 			while (*p == '\r' || *p == '\n') {
5006 				p++;
5007 			}
5008 			code_pos = p;
5009 		} else if (strncmp(code_pos, "#define FFI_LIB", sizeof("#define FFI_LIB") - 1) == 0
5010 		 && (code_pos[sizeof("#define FFI_LIB") - 1] == ' '
5011 		  || code_pos[sizeof("#define FFI_LIB") - 1] == '\t')) {
5012 			p = code_pos + sizeof("#define FFI_LIB");
5013 			while (*p == ' ' || *p == '\t') {
5014 				p++;
5015 			}
5016 			if (*p != '"') {
5017 				if (preload) {
5018 					zend_error(E_WARNING, "FFI: failed pre-loading '%s', bad FFI_LIB define", filename);
5019 				} else {
5020 					zend_throw_error(zend_ffi_exception_ce, "Failed loading '%s', bad FFI_LIB define", filename);
5021 				}
5022 				return NULL;
5023 			}
5024 			p++;
5025 			if (*lib) {
5026 				if (preload) {
5027 					zend_error(E_WARNING, "FFI: failed pre-loading '%s', FFI_LIB defined twice", filename);
5028 				} else {
5029 					zend_throw_error(zend_ffi_exception_ce, "Failed loading '%s', FFI_LIB defined twice", filename);
5030 				}
5031 				return NULL;
5032 			}
5033 			*lib = p;
5034 			while (1) {
5035 				if (*p == '\"') {
5036 					*p = 0;
5037 					p++;
5038 					break;
5039 				} else if (*p <= ' ') {
5040 					if (preload) {
5041 						zend_error(E_WARNING, "FFI: failed pre-loading '%s', bad FFI_LIB define", filename);
5042 					} else {
5043 						zend_throw_error(zend_ffi_exception_ce, "Failed loading '%s', bad FFI_LIB define", filename);
5044 					}
5045 					return NULL;
5046 				}
5047 				p++;
5048 			}
5049 			while (*p == ' ' || *p == '\t') {
5050 				p++;
5051 			}
5052 			while (*p == '\r' || *p == '\n') {
5053 				p++;
5054 			}
5055 			code_pos = p;
5056 		} else {
5057 			break;
5058 		}
5059 	}
5060 	return code_pos;
5061 }
5062 /* }}} */
5063 
zend_fake_get_constructor(zend_object * object)5064 static ZEND_COLD zend_function *zend_fake_get_constructor(zend_object *object) /* {{{ */
5065 {
5066 	zend_throw_error(NULL, "Instantiation of %s is not allowed", ZSTR_VAL(object->ce->name));
5067 	return NULL;
5068 }
5069 /* }}} */
5070 
zend_bad_array_access(zend_class_entry * ce)5071 static ZEND_COLD zend_never_inline void zend_bad_array_access(zend_class_entry *ce) /* {{{ */
5072 {
5073 	zend_throw_error(NULL, "Cannot use object of type %s as array", ZSTR_VAL(ce->name));
5074 }
5075 /* }}} */
5076 
zend_fake_read_dimension(zend_object * obj,zval * offset,int type,zval * rv)5077 static ZEND_COLD zval *zend_fake_read_dimension(zend_object *obj, zval *offset, int type, zval *rv) /* {{{ */
5078 {
5079 	zend_bad_array_access(obj->ce);
5080 	return NULL;
5081 }
5082 /* }}} */
5083 
zend_fake_write_dimension(zend_object * obj,zval * offset,zval * value)5084 static ZEND_COLD void zend_fake_write_dimension(zend_object *obj, zval *offset, zval *value) /* {{{ */
5085 {
5086 	zend_bad_array_access(obj->ce);
5087 }
5088 /* }}} */
5089 
zend_fake_has_dimension(zend_object * obj,zval * offset,int check_empty)5090 static ZEND_COLD int zend_fake_has_dimension(zend_object *obj, zval *offset, int check_empty) /* {{{ */
5091 {
5092 	zend_bad_array_access(obj->ce);
5093 	return 0;
5094 }
5095 /* }}} */
5096 
zend_fake_unset_dimension(zend_object * obj,zval * offset)5097 static ZEND_COLD void zend_fake_unset_dimension(zend_object *obj, zval *offset) /* {{{ */
5098 {
5099 	zend_bad_array_access(obj->ce);
5100 }
5101 /* }}} */
5102 
zend_bad_property_access(zend_class_entry * ce)5103 static ZEND_COLD zend_never_inline void zend_bad_property_access(zend_class_entry *ce) /* {{{ */
5104 {
5105 	zend_throw_error(NULL, "Cannot access property of object of type %s", ZSTR_VAL(ce->name));
5106 }
5107 /* }}} */
5108 
zend_fake_read_property(zend_object * obj,zend_string * member,int type,void ** cache_slot,zval * rv)5109 static ZEND_COLD zval *zend_fake_read_property(zend_object *obj, zend_string *member, int type, void **cache_slot, zval *rv) /* {{{ */
5110 {
5111 	zend_bad_property_access(obj->ce);
5112 	return &EG(uninitialized_zval);
5113 }
5114 /* }}} */
5115 
zend_fake_write_property(zend_object * obj,zend_string * member,zval * value,void ** cache_slot)5116 static ZEND_COLD zval *zend_fake_write_property(zend_object *obj, zend_string *member, zval *value, void **cache_slot) /* {{{ */
5117 {
5118 	zend_bad_array_access(obj->ce);
5119 	return value;
5120 }
5121 /* }}} */
5122 
zend_fake_has_property(zend_object * obj,zend_string * member,int has_set_exists,void ** cache_slot)5123 static ZEND_COLD int zend_fake_has_property(zend_object *obj, zend_string *member, int has_set_exists, void **cache_slot) /* {{{ */
5124 {
5125 	zend_bad_array_access(obj->ce);
5126 	return 0;
5127 }
5128 /* }}} */
5129 
zend_fake_unset_property(zend_object * obj,zend_string * member,void ** cache_slot)5130 static ZEND_COLD void zend_fake_unset_property(zend_object *obj, zend_string *member, void **cache_slot) /* {{{ */
5131 {
5132 	zend_bad_array_access(obj->ce);
5133 }
5134 /* }}} */
5135 
zend_fake_get_property_ptr_ptr(zend_object * obj,zend_string * member,int type,void ** cache_slot)5136 static zval *zend_fake_get_property_ptr_ptr(zend_object *obj, zend_string *member, int type, void **cache_slot) /* {{{ */
5137 {
5138 	return NULL;
5139 }
5140 /* }}} */
5141 
zend_fake_get_method(zend_object ** obj_ptr,zend_string * method_name,const zval * key)5142 static ZEND_COLD zend_function *zend_fake_get_method(zend_object **obj_ptr, zend_string *method_name, const zval *key) /* {{{ */
5143 {
5144 	zend_class_entry *ce = (*obj_ptr)->ce;
5145 	zend_throw_error(NULL, "Object of type %s does not support method calls", ZSTR_VAL(ce->name));
5146 	return NULL;
5147 }
5148 /* }}} */
5149 
zend_fake_get_properties(zend_object * obj)5150 static HashTable *zend_fake_get_properties(zend_object *obj) /* {{{ */
5151 {
5152 	return (HashTable*)&zend_empty_array;
5153 }
5154 /* }}} */
5155 
zend_fake_get_gc(zend_object * ob,zval ** table,int * n)5156 static HashTable *zend_fake_get_gc(zend_object *ob, zval **table, int *n) /* {{{ */
5157 {
5158 	*table = NULL;
5159 	*n = 0;
5160 	return NULL;
5161 }
5162 /* }}} */
5163 
zend_fake_cast_object(zend_object * obj,zval * result,int type)5164 static zend_result zend_fake_cast_object(zend_object *obj, zval *result, int type)
5165 {
5166 	switch (type) {
5167 		case _IS_BOOL:
5168 			ZVAL_TRUE(result);
5169 			return SUCCESS;
5170 		default:
5171 			return FAILURE;
5172 	}
5173 }
5174 
zend_ffi_use_after_free(void)5175 static ZEND_COLD zend_never_inline void zend_ffi_use_after_free(void) /* {{{ */
5176 {
5177 	zend_throw_error(zend_ffi_exception_ce, "Use after free()");
5178 }
5179 /* }}} */
5180 
zend_ffi_free_clone_obj(zend_object * obj)5181 static zend_object *zend_ffi_free_clone_obj(zend_object *obj) /* {{{ */
5182 {
5183 	zend_ffi_use_after_free();
5184 	return NULL;
5185 }
5186 /* }}} */
5187 
zend_ffi_free_read_dimension(zend_object * obj,zval * offset,int type,zval * rv)5188 static ZEND_COLD zval *zend_ffi_free_read_dimension(zend_object *obj, zval *offset, int type, zval *rv) /* {{{ */
5189 {
5190 	zend_ffi_use_after_free();
5191 	return NULL;
5192 }
5193 /* }}} */
5194 
zend_ffi_free_write_dimension(zend_object * obj,zval * offset,zval * value)5195 static ZEND_COLD void zend_ffi_free_write_dimension(zend_object *obj, zval *offset, zval *value) /* {{{ */
5196 {
5197 	zend_ffi_use_after_free();
5198 }
5199 /* }}} */
5200 
zend_ffi_free_has_dimension(zend_object * obj,zval * offset,int check_empty)5201 static ZEND_COLD int zend_ffi_free_has_dimension(zend_object *obj, zval *offset, int check_empty) /* {{{ */
5202 {
5203 	zend_ffi_use_after_free();
5204 	return 0;
5205 }
5206 /* }}} */
5207 
zend_ffi_free_unset_dimension(zend_object * obj,zval * offset)5208 static ZEND_COLD void zend_ffi_free_unset_dimension(zend_object *obj, zval *offset) /* {{{ */
5209 {
5210 	zend_ffi_use_after_free();
5211 }
5212 /* }}} */
5213 
zend_ffi_free_read_property(zend_object * obj,zend_string * member,int type,void ** cache_slot,zval * rv)5214 static ZEND_COLD zval *zend_ffi_free_read_property(zend_object *obj, zend_string *member, int type, void **cache_slot, zval *rv) /* {{{ */
5215 {
5216 	zend_ffi_use_after_free();
5217 	return &EG(uninitialized_zval);
5218 }
5219 /* }}} */
5220 
zend_ffi_free_write_property(zend_object * obj,zend_string * member,zval * value,void ** cache_slot)5221 static ZEND_COLD zval *zend_ffi_free_write_property(zend_object *obj, zend_string *member, zval *value, void **cache_slot) /* {{{ */
5222 {
5223 	zend_ffi_use_after_free();
5224 	return value;
5225 }
5226 /* }}} */
5227 
zend_ffi_free_has_property(zend_object * obj,zend_string * member,int has_set_exists,void ** cache_slot)5228 static ZEND_COLD int zend_ffi_free_has_property(zend_object *obj, zend_string *member, int has_set_exists, void **cache_slot) /* {{{ */
5229 {
5230 	zend_ffi_use_after_free();
5231 	return 0;
5232 }
5233 /* }}} */
5234 
zend_ffi_free_unset_property(zend_object * obj,zend_string * member,void ** cache_slot)5235 static ZEND_COLD void zend_ffi_free_unset_property(zend_object *obj, zend_string *member, void **cache_slot) /* {{{ */
5236 {
5237 	zend_ffi_use_after_free();
5238 }
5239 /* }}} */
5240 
zend_ffi_free_get_debug_info(zend_object * obj,int * is_temp)5241 static HashTable *zend_ffi_free_get_debug_info(zend_object *obj, int *is_temp) /* {{{ */
5242 {
5243 	zend_ffi_use_after_free();
5244 	return NULL;
5245 }
5246 /* }}} */
5247 
ZEND_INI_MH(OnUpdateFFIEnable)5248 static ZEND_INI_MH(OnUpdateFFIEnable) /* {{{ */
5249 {
5250 	if (zend_string_equals_literal_ci(new_value, "preload")) {
5251 		FFI_G(restriction) = ZEND_FFI_PRELOAD;
5252 	} else {
5253 		FFI_G(restriction) = (zend_ffi_api_restriction)zend_ini_parse_bool(new_value);
5254 	}
5255 	return SUCCESS;
5256 }
5257 /* }}} */
5258 
ZEND_INI_DISP(zend_ffi_enable_displayer_cb)5259 static ZEND_INI_DISP(zend_ffi_enable_displayer_cb) /* {{{ */
5260 {
5261 	if (FFI_G(restriction) == ZEND_FFI_PRELOAD) {
5262 		ZEND_PUTS("preload");
5263 	} else if (FFI_G(restriction) == ZEND_FFI_ENABLED) {
5264 		ZEND_PUTS("On");
5265 	} else {
5266 		ZEND_PUTS("Off");
5267 	}
5268 }
5269 /* }}} */
5270 
5271 ZEND_INI_BEGIN()
5272 	ZEND_INI_ENTRY_EX("ffi.enable", "preload", ZEND_INI_SYSTEM, OnUpdateFFIEnable, zend_ffi_enable_displayer_cb)
5273 	STD_ZEND_INI_ENTRY("ffi.preload", NULL, ZEND_INI_SYSTEM, OnUpdateString, preload, zend_ffi_globals, ffi_globals)
ZEND_INI_END()5274 ZEND_INI_END()
5275 
5276 static zend_result zend_ffi_preload_glob(const char *filename) /* {{{ */
5277 {
5278 #ifdef HAVE_GLOB
5279 	glob_t globbuf;
5280 	int    ret;
5281 	unsigned int i;
5282 
5283 	memset(&globbuf, 0, sizeof(glob_t));
5284 
5285 	ret = glob(filename, 0, NULL, &globbuf);
5286 #ifdef GLOB_NOMATCH
5287 	if (ret == GLOB_NOMATCH || !globbuf.gl_pathc) {
5288 #else
5289 	if (!globbuf.gl_pathc) {
5290 #endif
5291 		/* pass */
5292 	} else {
5293 		for(i=0 ; i<globbuf.gl_pathc; i++) {
5294 			zend_ffi *ffi = zend_ffi_load(globbuf.gl_pathv[i], 1);
5295 			if (!ffi) {
5296 				globfree(&globbuf);
5297 				return FAILURE;
5298 			}
5299 			efree(ffi);
5300 		}
5301 		globfree(&globbuf);
5302 	}
5303 #else
5304 	zend_ffi *ffi = zend_ffi_load(filename, 1);
5305 	if (!ffi) {
5306 		return FAILURE;
5307 	}
5308 	efree(ffi);
5309 #endif
5310 
5311 	return SUCCESS;
5312 }
5313 /* }}} */
5314 
5315 static zend_result zend_ffi_preload(char *preload) /* {{{ */
5316 {
5317 	zend_ffi *ffi;
5318 	char *s = NULL, *e, *filename;
5319 	bool is_glob = 0;
5320 
5321 	e = preload;
5322 	while (*e) {
5323 		switch (*e) {
5324 			case ZEND_PATHS_SEPARATOR:
5325 				if (s) {
5326 					filename = estrndup(s, e-s);
5327 					s = NULL;
5328 					if (!is_glob) {
5329 						ffi = zend_ffi_load(filename, 1);
5330 						efree(filename);
5331 						if (!ffi) {
5332 							return FAILURE;
5333 						}
5334 						efree(ffi);
5335 					} else {
5336 						zend_result ret = zend_ffi_preload_glob(filename);
5337 
5338 						efree(filename);
5339 						if (ret == FAILURE) {
5340 							return FAILURE;
5341 						}
5342 						is_glob = 0;
5343 					}
5344 				}
5345 				break;
5346 			case '*':
5347 			case '?':
5348 			case '[':
5349 				is_glob = 1;
5350 				break;
5351 			default:
5352 				if (!s) {
5353 					s = e;
5354 				}
5355 				break;
5356 		}
5357 		e++;
5358 	}
5359 	if (s) {
5360 		filename = estrndup(s, e-s);
5361 		if (!is_glob) {
5362 			ffi = zend_ffi_load(filename, 1);
5363 			efree(filename);
5364 			if (!ffi) {
5365 				return FAILURE;
5366 			}
5367 			efree(ffi);
5368 		} else {
5369 			zend_result ret = zend_ffi_preload_glob(filename);
5370 			efree(filename);
5371 			if (ret == FAILURE) {
5372 				return FAILURE;
5373 			}
5374 		}
5375 	}
5376 
5377 	return SUCCESS;
5378 }
5379 /* }}} */
5380 
5381 /* The startup code for observers adds a temporary to each function for internal use.
5382  * The "new", "cast", and "type" functions in FFI are both static and non-static.
5383  * Only the static versions are in the function table and the non-static versions are not.
5384  * This means the non-static versions will be skipped by the observers startup code.
5385  * This function fixes that by incrementing the temporary count for the non-static versions.
5386  */
5387 static zend_result (*prev_zend_post_startup_cb)(void);
5388 static zend_result ffi_fixup_temporaries(void) {
5389 	if (ZEND_OBSERVER_ENABLED) {
5390 		++zend_ffi_new_fn.T;
5391 		++zend_ffi_cast_fn.T;
5392 		++zend_ffi_type_fn.T;
5393 	}
5394 	if (prev_zend_post_startup_cb) {
5395 		return prev_zend_post_startup_cb();
5396 	}
5397 	return SUCCESS;
5398 }
5399 
5400 /* {{{ ZEND_MINIT_FUNCTION */
5401 ZEND_MINIT_FUNCTION(ffi)
5402 {
5403 	REGISTER_INI_ENTRIES();
5404 
5405 	FFI_G(is_cli) = strcmp(sapi_module.name, "cli") == 0;
5406 
5407 	zend_ffi_exception_ce = register_class_FFI_Exception(zend_ce_error);
5408 
5409 	zend_ffi_parser_exception_ce = register_class_FFI_ParserException(zend_ffi_exception_ce);
5410 
5411 	zend_ffi_ce = register_class_FFI();
5412 	zend_ffi_ce->create_object = zend_ffi_new;
5413 	zend_ffi_ce->default_object_handlers = &zend_ffi_handlers;
5414 
5415 	memcpy(&zend_ffi_new_fn, zend_hash_str_find_ptr(&zend_ffi_ce->function_table, "new", sizeof("new")-1), sizeof(zend_internal_function));
5416 	zend_ffi_new_fn.fn_flags &= ~ZEND_ACC_STATIC;
5417 	memcpy(&zend_ffi_cast_fn, zend_hash_str_find_ptr(&zend_ffi_ce->function_table, "cast", sizeof("cast")-1), sizeof(zend_internal_function));
5418 	zend_ffi_cast_fn.fn_flags &= ~ZEND_ACC_STATIC;
5419 	memcpy(&zend_ffi_type_fn, zend_hash_str_find_ptr(&zend_ffi_ce->function_table, "type", sizeof("type")-1), sizeof(zend_internal_function));
5420 	zend_ffi_type_fn.fn_flags &= ~ZEND_ACC_STATIC;
5421 
5422 	prev_zend_post_startup_cb = zend_post_startup_cb;
5423 	zend_post_startup_cb = ffi_fixup_temporaries;
5424 
5425 	memcpy(&zend_ffi_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
5426 	zend_ffi_handlers.get_constructor      = zend_fake_get_constructor;
5427 	zend_ffi_handlers.free_obj             = zend_ffi_free_obj;
5428 	zend_ffi_handlers.clone_obj            = NULL;
5429 	zend_ffi_handlers.read_property        = zend_ffi_read_var;
5430 	zend_ffi_handlers.write_property       = zend_ffi_write_var;
5431 	zend_ffi_handlers.read_dimension       = zend_fake_read_dimension;
5432 	zend_ffi_handlers.write_dimension      = zend_fake_write_dimension;
5433 	zend_ffi_handlers.get_property_ptr_ptr = zend_fake_get_property_ptr_ptr;
5434 	zend_ffi_handlers.has_property         = zend_fake_has_property;
5435 	zend_ffi_handlers.unset_property       = zend_fake_unset_property;
5436 	zend_ffi_handlers.has_dimension        = zend_fake_has_dimension;
5437 	zend_ffi_handlers.unset_dimension      = zend_fake_unset_dimension;
5438 	zend_ffi_handlers.get_method           = zend_ffi_get_func;
5439 	zend_ffi_handlers.compare              = NULL;
5440 	zend_ffi_handlers.cast_object          = zend_fake_cast_object;
5441 	zend_ffi_handlers.get_debug_info       = NULL;
5442 	zend_ffi_handlers.get_closure          = NULL;
5443 	zend_ffi_handlers.get_properties       = zend_fake_get_properties;
5444 	zend_ffi_handlers.get_gc               = zend_fake_get_gc;
5445 
5446 	zend_ffi_cdata_ce = register_class_FFI_CData();
5447 	zend_ffi_cdata_ce->create_object = zend_ffi_cdata_new;
5448 	zend_ffi_cdata_ce->default_object_handlers = &zend_ffi_cdata_handlers;
5449 	zend_ffi_cdata_ce->get_iterator = zend_ffi_cdata_get_iterator;
5450 
5451 	memcpy(&zend_ffi_cdata_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
5452 	zend_ffi_cdata_handlers.get_constructor      = zend_fake_get_constructor;
5453 	zend_ffi_cdata_handlers.free_obj             = zend_ffi_cdata_free_obj;
5454 	zend_ffi_cdata_handlers.clone_obj            = zend_ffi_cdata_clone_obj;
5455 	zend_ffi_cdata_handlers.read_property        = zend_ffi_cdata_read_field;
5456 	zend_ffi_cdata_handlers.write_property       = zend_ffi_cdata_write_field;
5457 	zend_ffi_cdata_handlers.read_dimension       = zend_ffi_cdata_read_dim;
5458 	zend_ffi_cdata_handlers.write_dimension      = zend_ffi_cdata_write_dim;
5459 	zend_ffi_cdata_handlers.get_property_ptr_ptr = zend_fake_get_property_ptr_ptr;
5460 	zend_ffi_cdata_handlers.has_property         = zend_fake_has_property;
5461 	zend_ffi_cdata_handlers.unset_property       = zend_fake_unset_property;
5462 	zend_ffi_cdata_handlers.has_dimension        = zend_fake_has_dimension;
5463 	zend_ffi_cdata_handlers.unset_dimension      = zend_fake_unset_dimension;
5464 	zend_ffi_cdata_handlers.get_method           = zend_fake_get_method;
5465 	zend_ffi_cdata_handlers.get_class_name       = zend_ffi_cdata_get_class_name;
5466 	zend_ffi_cdata_handlers.do_operation         = zend_ffi_cdata_do_operation;
5467 	zend_ffi_cdata_handlers.compare              = zend_ffi_cdata_compare_objects;
5468 	zend_ffi_cdata_handlers.cast_object          = zend_ffi_cdata_cast_object;
5469 	zend_ffi_cdata_handlers.count_elements       = zend_ffi_cdata_count_elements;
5470 	zend_ffi_cdata_handlers.get_debug_info       = zend_ffi_cdata_get_debug_info;
5471 	zend_ffi_cdata_handlers.get_closure          = zend_ffi_cdata_get_closure;
5472 	zend_ffi_cdata_handlers.get_properties       = zend_fake_get_properties;
5473 	zend_ffi_cdata_handlers.get_gc               = zend_fake_get_gc;
5474 
5475 	memcpy(&zend_ffi_cdata_value_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
5476 	zend_ffi_cdata_value_handlers.get_constructor      = zend_fake_get_constructor;
5477 	zend_ffi_cdata_value_handlers.free_obj             = zend_ffi_cdata_free_obj;
5478 	zend_ffi_cdata_value_handlers.clone_obj            = zend_ffi_cdata_clone_obj;
5479 	zend_ffi_cdata_value_handlers.read_property        = zend_ffi_cdata_get;
5480 	zend_ffi_cdata_value_handlers.write_property       = zend_ffi_cdata_set;
5481 	zend_ffi_cdata_value_handlers.read_dimension       = zend_fake_read_dimension;
5482 	zend_ffi_cdata_value_handlers.write_dimension      = zend_fake_write_dimension;
5483 	zend_ffi_cdata_value_handlers.get_property_ptr_ptr = zend_fake_get_property_ptr_ptr;
5484 	zend_ffi_cdata_value_handlers.has_property         = zend_fake_has_property;
5485 	zend_ffi_cdata_value_handlers.unset_property       = zend_fake_unset_property;
5486 	zend_ffi_cdata_value_handlers.has_dimension        = zend_fake_has_dimension;
5487 	zend_ffi_cdata_value_handlers.unset_dimension      = zend_fake_unset_dimension;
5488 	zend_ffi_cdata_value_handlers.get_method           = zend_fake_get_method;
5489 	zend_ffi_cdata_value_handlers.get_class_name       = zend_ffi_cdata_get_class_name;
5490 	zend_ffi_cdata_value_handlers.compare              = zend_ffi_cdata_compare_objects;
5491 	zend_ffi_cdata_value_handlers.cast_object          = zend_ffi_cdata_cast_object;
5492 	zend_ffi_cdata_value_handlers.count_elements       = NULL;
5493 	zend_ffi_cdata_value_handlers.get_debug_info       = zend_ffi_cdata_get_debug_info;
5494 	zend_ffi_cdata_value_handlers.get_closure          = NULL;
5495 	zend_ffi_cdata_value_handlers.get_properties       = zend_fake_get_properties;
5496 	zend_ffi_cdata_value_handlers.get_gc               = zend_fake_get_gc;
5497 
5498 	memcpy(&zend_ffi_cdata_free_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
5499 	zend_ffi_cdata_free_handlers.get_constructor      = zend_fake_get_constructor;
5500 	zend_ffi_cdata_free_handlers.free_obj             = zend_ffi_cdata_free_obj;
5501 	zend_ffi_cdata_free_handlers.clone_obj            = zend_ffi_free_clone_obj;
5502 	zend_ffi_cdata_free_handlers.read_property        = zend_ffi_free_read_property;
5503 	zend_ffi_cdata_free_handlers.write_property       = zend_ffi_free_write_property;
5504 	zend_ffi_cdata_free_handlers.read_dimension       = zend_ffi_free_read_dimension;
5505 	zend_ffi_cdata_free_handlers.write_dimension      = zend_ffi_free_write_dimension;
5506 	zend_ffi_cdata_free_handlers.get_property_ptr_ptr = zend_fake_get_property_ptr_ptr;
5507 	zend_ffi_cdata_free_handlers.has_property         = zend_ffi_free_has_property;
5508 	zend_ffi_cdata_free_handlers.unset_property       = zend_ffi_free_unset_property;
5509 	zend_ffi_cdata_free_handlers.has_dimension        = zend_ffi_free_has_dimension;
5510 	zend_ffi_cdata_free_handlers.unset_dimension      = zend_ffi_free_unset_dimension;
5511 	zend_ffi_cdata_free_handlers.get_method           = zend_fake_get_method;
5512 	zend_ffi_cdata_free_handlers.get_class_name       = zend_ffi_cdata_get_class_name;
5513 	zend_ffi_cdata_free_handlers.compare              = zend_ffi_cdata_compare_objects;
5514 	zend_ffi_cdata_free_handlers.cast_object          = zend_fake_cast_object;
5515 	zend_ffi_cdata_free_handlers.count_elements       = NULL;
5516 	zend_ffi_cdata_free_handlers.get_debug_info       = zend_ffi_free_get_debug_info;
5517 	zend_ffi_cdata_free_handlers.get_closure          = NULL;
5518 	zend_ffi_cdata_free_handlers.get_properties       = zend_fake_get_properties;
5519 	zend_ffi_cdata_free_handlers.get_gc               = zend_fake_get_gc;
5520 
5521 	zend_ffi_ctype_ce = register_class_FFI_CType();
5522 	zend_ffi_ctype_ce->create_object = zend_ffi_ctype_new;
5523 	zend_ffi_ctype_ce->default_object_handlers = &zend_ffi_ctype_handlers;
5524 
5525 	memcpy(&zend_ffi_ctype_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
5526 	zend_ffi_ctype_handlers.get_constructor      = zend_fake_get_constructor;
5527 	zend_ffi_ctype_handlers.free_obj             = zend_ffi_ctype_free_obj;
5528 	zend_ffi_ctype_handlers.clone_obj            = NULL;
5529 	zend_ffi_ctype_handlers.read_property        = zend_fake_read_property;
5530 	zend_ffi_ctype_handlers.write_property       = zend_fake_write_property;
5531 	zend_ffi_ctype_handlers.read_dimension       = zend_fake_read_dimension;
5532 	zend_ffi_ctype_handlers.write_dimension      = zend_fake_write_dimension;
5533 	zend_ffi_ctype_handlers.get_property_ptr_ptr = zend_fake_get_property_ptr_ptr;
5534 	zend_ffi_ctype_handlers.has_property         = zend_fake_has_property;
5535 	zend_ffi_ctype_handlers.unset_property       = zend_fake_unset_property;
5536 	zend_ffi_ctype_handlers.has_dimension        = zend_fake_has_dimension;
5537 	zend_ffi_ctype_handlers.unset_dimension      = zend_fake_unset_dimension;
5538 	//zend_ffi_ctype_handlers.get_method           = zend_fake_get_method;
5539 	zend_ffi_ctype_handlers.get_class_name       = zend_ffi_ctype_get_class_name;
5540 	zend_ffi_ctype_handlers.compare              = zend_ffi_ctype_compare_objects;
5541 	zend_ffi_ctype_handlers.cast_object          = zend_fake_cast_object;
5542 	zend_ffi_ctype_handlers.count_elements       = NULL;
5543 	zend_ffi_ctype_handlers.get_debug_info       = zend_ffi_ctype_get_debug_info;
5544 	zend_ffi_ctype_handlers.get_closure          = NULL;
5545 	zend_ffi_ctype_handlers.get_properties       = zend_fake_get_properties;
5546 	zend_ffi_ctype_handlers.get_gc               = zend_fake_get_gc;
5547 
5548 	if (FFI_G(preload)) {
5549 		return zend_ffi_preload(FFI_G(preload));
5550 	}
5551 
5552 	return SUCCESS;
5553 }
5554 /* }}} */
5555 
5556 /* {{{ ZEND_RSHUTDOWN_FUNCTION */
5557 ZEND_RSHUTDOWN_FUNCTION(ffi)
5558 {
5559 	if (FFI_G(callbacks)) {
5560 		zend_hash_destroy(FFI_G(callbacks));
5561 		efree(FFI_G(callbacks));
5562 		FFI_G(callbacks) = NULL;
5563 	}
5564 	if (FFI_G(weak_types)) {
5565 #if 0
5566 		fprintf(stderr, "WeakTypes: %d\n", zend_hash_num_elements(FFI_G(weak_types)));
5567 #endif
5568 		zend_hash_destroy(FFI_G(weak_types));
5569 		efree(FFI_G(weak_types));
5570 		FFI_G(weak_types) = NULL;
5571 	}
5572 	return SUCCESS;
5573 }
5574 /* }}} */
5575 
5576 /* {{{ ZEND_MINFO_FUNCTION */
5577 ZEND_MINFO_FUNCTION(ffi)
5578 {
5579 	php_info_print_table_start();
5580 	php_info_print_table_row(2, "FFI support", "enabled");
5581 	php_info_print_table_end();
5582 
5583 	DISPLAY_INI_ENTRIES();
5584 }
5585 /* }}} */
5586 
5587 static const zend_ffi_type zend_ffi_type_void = {.kind=ZEND_FFI_TYPE_VOID, .size=1, .align=1};
5588 static const zend_ffi_type zend_ffi_type_char = {.kind=ZEND_FFI_TYPE_CHAR, .size=1, .align=_Alignof(char)};
5589 static const zend_ffi_type zend_ffi_type_bool = {.kind=ZEND_FFI_TYPE_BOOL, .size=1, .align=_Alignof(uint8_t)};
5590 static const zend_ffi_type zend_ffi_type_sint8 = {.kind=ZEND_FFI_TYPE_SINT8, .size=1, .align=_Alignof(int8_t)};
5591 static const zend_ffi_type zend_ffi_type_uint8 = {.kind=ZEND_FFI_TYPE_UINT8, .size=1, .align=_Alignof(uint8_t)};
5592 static const zend_ffi_type zend_ffi_type_sint16 = {.kind=ZEND_FFI_TYPE_SINT16, .size=2, .align=_Alignof(int16_t)};
5593 static const zend_ffi_type zend_ffi_type_uint16 = {.kind=ZEND_FFI_TYPE_UINT16, .size=2, .align=_Alignof(uint16_t)};
5594 static const zend_ffi_type zend_ffi_type_sint32 = {.kind=ZEND_FFI_TYPE_SINT32, .size=4, .align=_Alignof(int32_t)};
5595 static const zend_ffi_type zend_ffi_type_uint32 = {.kind=ZEND_FFI_TYPE_UINT32, .size=4, .align=_Alignof(uint32_t)};
5596 static const zend_ffi_type zend_ffi_type_sint64 = {.kind=ZEND_FFI_TYPE_SINT64, .size=8, .align=_Alignof(int64_t)};
5597 static const zend_ffi_type zend_ffi_type_uint64 = {.kind=ZEND_FFI_TYPE_UINT64, .size=8, .align=_Alignof(uint64_t)};
5598 static const zend_ffi_type zend_ffi_type_float = {.kind=ZEND_FFI_TYPE_FLOAT, .size=sizeof(float), .align=_Alignof(float)};
5599 static const zend_ffi_type zend_ffi_type_double = {.kind=ZEND_FFI_TYPE_DOUBLE, .size=sizeof(double), .align=_Alignof(double)};
5600 
5601 #ifdef HAVE_LONG_DOUBLE
5602 static const zend_ffi_type zend_ffi_type_long_double = {.kind=ZEND_FFI_TYPE_LONGDOUBLE, .size=sizeof(long double), .align=_Alignof(long double)};
5603 #endif
5604 
5605 static const zend_ffi_type zend_ffi_type_ptr = {.kind=ZEND_FFI_TYPE_POINTER, .size=sizeof(void*), .align=_Alignof(void*), .pointer.type = (zend_ffi_type*)&zend_ffi_type_void};
5606 
5607 static const struct {
5608 	const char *name;
5609 	const zend_ffi_type *type;
5610 } zend_ffi_types[] = {
5611 	{"void",        &zend_ffi_type_void},
5612 	{"char",        &zend_ffi_type_char},
5613 	{"bool",        &zend_ffi_type_bool},
5614 	{"int8_t",      &zend_ffi_type_sint8},
5615 	{"uint8_t",     &zend_ffi_type_uint8},
5616 	{"int16_t",     &zend_ffi_type_sint16},
5617 	{"uint16_t",    &zend_ffi_type_uint16},
5618 	{"int32_t",     &zend_ffi_type_sint32},
5619 	{"uint32_t",    &zend_ffi_type_uint32},
5620 	{"int64_t",     &zend_ffi_type_sint64},
5621 	{"uint64_t",    &zend_ffi_type_uint64},
5622 	{"float",       &zend_ffi_type_float},
5623 	{"double",      &zend_ffi_type_double},
5624 #ifdef HAVE_LONG_DOUBLE
5625 	{"long double", &zend_ffi_type_long_double},
5626 #endif
5627 #if SIZEOF_SIZE_T == 4
5628 	{"uintptr_t",  &zend_ffi_type_uint32},
5629 	{"intptr_t",   &zend_ffi_type_sint32},
5630 	{"size_t",     &zend_ffi_type_uint32},
5631 	{"ssize_t",    &zend_ffi_type_sint32},
5632 	{"ptrdiff_t",  &zend_ffi_type_sint32},
5633 #else
5634 	{"uintptr_t",  &zend_ffi_type_uint64},
5635 	{"intptr_t",   &zend_ffi_type_sint64},
5636 	{"size_t",     &zend_ffi_type_uint64},
5637 	{"ssize_t",    &zend_ffi_type_sint64},
5638 	{"ptrdiff_t",  &zend_ffi_type_sint64},
5639 #endif
5640 #if SIZEOF_OFF_T == 4
5641 	{"off_t",      &zend_ffi_type_sint32},
5642 #else
5643 	{"off_t",      &zend_ffi_type_sint64},
5644 #endif
5645 
5646 	{"va_list",           &zend_ffi_type_ptr},
5647 	{"__builtin_va_list", &zend_ffi_type_ptr},
5648 	{"__gnuc_va_list",    &zend_ffi_type_ptr},
5649 };
5650 
5651 /* {{{ ZEND_GINIT_FUNCTION */
5652 static ZEND_GINIT_FUNCTION(ffi)
5653 {
5654 	size_t i;
5655 
5656 #if defined(COMPILE_DL_FFI) && defined(ZTS)
5657 	ZEND_TSRMLS_CACHE_UPDATE();
5658 #endif
5659 	memset(ffi_globals, 0, sizeof(*ffi_globals));
5660 	zend_hash_init(&ffi_globals->types, 0, NULL, NULL, 1);
5661 	for (i = 0; i < sizeof(zend_ffi_types)/sizeof(zend_ffi_types[0]); i++) {
5662 		zend_hash_str_add_new_ptr(&ffi_globals->types, zend_ffi_types[i].name, strlen(zend_ffi_types[i].name), (void*)zend_ffi_types[i].type);
5663 	}
5664 }
5665 /* }}} */
5666 
5667 /* {{{ ZEND_GINIT_FUNCTION */
5668 static ZEND_GSHUTDOWN_FUNCTION(ffi)
5669 {
5670 	if (ffi_globals->scopes) {
5671 		zend_hash_destroy(ffi_globals->scopes);
5672 		free(ffi_globals->scopes);
5673 	}
5674 	zend_hash_destroy(&ffi_globals->types);
5675 }
5676 /* }}} */
5677 
5678 /* {{{ ffi_module_entry */
5679 zend_module_entry ffi_module_entry = {
5680 	STANDARD_MODULE_HEADER,
5681 	"FFI",					/* Extension name */
5682 	NULL,					/* zend_function_entry */
5683 	ZEND_MINIT(ffi),		/* ZEND_MINIT - Module initialization */
5684 	NULL,					/* ZEND_MSHUTDOWN - Module shutdown */
5685 	NULL,					/* ZEND_RINIT - Request initialization */
5686 	ZEND_RSHUTDOWN(ffi),	/* ZEND_RSHUTDOWN - Request shutdown */
5687 	ZEND_MINFO(ffi),		/* ZEND_MINFO - Module info */
5688 	PHP_VERSION,			/* Version */
5689 	ZEND_MODULE_GLOBALS(ffi),
5690 	ZEND_GINIT(ffi),
5691 	ZEND_GSHUTDOWN(ffi),
5692 	NULL,
5693 	STANDARD_MODULE_PROPERTIES_EX
5694 };
5695 /* }}} */
5696 
5697 #ifdef COMPILE_DL_FFI
5698 # ifdef ZTS
5699 ZEND_TSRMLS_CACHE_DEFINE()
5700 # endif
5701 ZEND_GET_MODULE(ffi)
5702 #endif
5703 
5704 /* parser callbacks */
5705 void zend_ffi_parser_error(const char *format, ...) /* {{{ */
5706 {
5707 	va_list va;
5708 	char *message = NULL;
5709 
5710 	va_start(va, format);
5711 	zend_vspprintf(&message, 0, format, va);
5712 
5713 	if (EG(current_execute_data)) {
5714 		zend_throw_exception(zend_ffi_parser_exception_ce, message, 0);
5715 	} else {
5716 		zend_error(E_WARNING, "FFI Parser: %s", message);
5717 	}
5718 
5719 	efree(message);
5720 	va_end(va);
5721 
5722 	LONGJMP(FFI_G(bailout), FAILURE);
5723 }
5724 /* }}} */
5725 
5726 static void zend_ffi_finalize_type(zend_ffi_dcl *dcl) /* {{{ */
5727 {
5728 	if (!dcl->type) {
5729 		switch (dcl->flags & ZEND_FFI_DCL_TYPE_SPECIFIERS) {
5730 			case ZEND_FFI_DCL_VOID:
5731 				dcl->type = (zend_ffi_type*)&zend_ffi_type_void;
5732 				break;
5733 			case ZEND_FFI_DCL_CHAR:
5734 				dcl->type = (zend_ffi_type*)&zend_ffi_type_char;
5735 				break;
5736 			case ZEND_FFI_DCL_CHAR|ZEND_FFI_DCL_SIGNED:
5737 				dcl->type = (zend_ffi_type*)&zend_ffi_type_sint8;
5738 				break;
5739 			case ZEND_FFI_DCL_CHAR|ZEND_FFI_DCL_UNSIGNED:
5740 			case ZEND_FFI_DCL_BOOL:
5741 				dcl->type = (zend_ffi_type*)&zend_ffi_type_uint8;
5742 				break;
5743 			case ZEND_FFI_DCL_SHORT:
5744 			case ZEND_FFI_DCL_SHORT|ZEND_FFI_DCL_SIGNED:
5745 			case ZEND_FFI_DCL_SHORT|ZEND_FFI_DCL_INT:
5746 			case ZEND_FFI_DCL_SHORT|ZEND_FFI_DCL_SIGNED|ZEND_FFI_DCL_INT:
5747 				dcl->type = (zend_ffi_type*)&zend_ffi_type_sint16;
5748 				break;
5749 			case ZEND_FFI_DCL_SHORT|ZEND_FFI_DCL_UNSIGNED:
5750 			case ZEND_FFI_DCL_SHORT|ZEND_FFI_DCL_UNSIGNED|ZEND_FFI_DCL_INT:
5751 				dcl->type = (zend_ffi_type*)&zend_ffi_type_uint16;
5752 				break;
5753 			case ZEND_FFI_DCL_INT:
5754 			case ZEND_FFI_DCL_SIGNED:
5755 			case ZEND_FFI_DCL_SIGNED|ZEND_FFI_DCL_INT:
5756 				dcl->type = (zend_ffi_type*)&zend_ffi_type_sint32;
5757 				break;
5758 			case ZEND_FFI_DCL_UNSIGNED:
5759 			case ZEND_FFI_DCL_UNSIGNED|ZEND_FFI_DCL_INT:
5760 				dcl->type = (zend_ffi_type*)&zend_ffi_type_uint32;
5761 				break;
5762 			case ZEND_FFI_DCL_LONG:
5763 			case ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_SIGNED:
5764 			case ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_INT:
5765 			case ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_SIGNED|ZEND_FFI_DCL_INT:
5766 				if (sizeof(long) == 4) {
5767 					dcl->type = (zend_ffi_type*)&zend_ffi_type_sint32;
5768 				} else {
5769 					dcl->type = (zend_ffi_type*)&zend_ffi_type_sint64;
5770 				}
5771 				break;
5772 			case ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_UNSIGNED:
5773 			case ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_UNSIGNED|ZEND_FFI_DCL_INT:
5774 				if (sizeof(long) == 4) {
5775 					dcl->type = (zend_ffi_type*)&zend_ffi_type_uint32;
5776 				} else {
5777 					dcl->type = (zend_ffi_type*)&zend_ffi_type_uint64;
5778 				}
5779 				break;
5780 			case ZEND_FFI_DCL_LONG_LONG|ZEND_FFI_DCL_LONG:
5781 			case ZEND_FFI_DCL_LONG_LONG|ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_SIGNED:
5782 			case ZEND_FFI_DCL_LONG_LONG|ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_INT:
5783 			case ZEND_FFI_DCL_LONG_LONG|ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_SIGNED|ZEND_FFI_DCL_INT:
5784 				dcl->type = (zend_ffi_type*)&zend_ffi_type_sint64;
5785 				break;
5786 			case ZEND_FFI_DCL_LONG_LONG|ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_UNSIGNED:
5787 			case ZEND_FFI_DCL_LONG_LONG|ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_UNSIGNED|ZEND_FFI_DCL_INT:
5788 				dcl->type = (zend_ffi_type*)&zend_ffi_type_uint64;
5789 				break;
5790 			case ZEND_FFI_DCL_FLOAT:
5791 				dcl->type = (zend_ffi_type*)&zend_ffi_type_float;
5792 				break;
5793 			case ZEND_FFI_DCL_DOUBLE:
5794 				dcl->type = (zend_ffi_type*)&zend_ffi_type_double;
5795 				break;
5796 			case ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_DOUBLE:
5797 #ifdef _WIN32
5798 				dcl->type = (zend_ffi_type*)&zend_ffi_type_double;
5799 #else
5800 				dcl->type = (zend_ffi_type*)&zend_ffi_type_long_double;
5801 #endif
5802 				break;
5803 			case ZEND_FFI_DCL_FLOAT|ZEND_FFI_DCL_COMPLEX:
5804 			case ZEND_FFI_DCL_DOUBLE|ZEND_FFI_DCL_COMPLEX:
5805 			case ZEND_FFI_DCL_DOUBLE|ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_COMPLEX:
5806 				zend_ffi_parser_error("Unsupported type _Complex at line %d", FFI_G(line));
5807 				break;
5808 			default:
5809 				zend_ffi_parser_error("Unsupported type specifier combination at line %d", FFI_G(line));
5810 				break;
5811 		}
5812 		dcl->flags &= ~ZEND_FFI_DCL_TYPE_SPECIFIERS;
5813 		dcl->flags |= ZEND_FFI_DCL_TYPEDEF_NAME;
5814 	}
5815 }
5816 /* }}} */
5817 
5818 bool zend_ffi_is_typedef_name(const char *name, size_t name_len) /* {{{ */
5819 {
5820 	zend_ffi_symbol *sym;
5821 	zend_ffi_type *type;
5822 
5823 	if (FFI_G(symbols)) {
5824 		sym = zend_hash_str_find_ptr(FFI_G(symbols), name, name_len);
5825 		if (sym) {
5826 			return (sym->kind == ZEND_FFI_SYM_TYPE);
5827 		}
5828 	}
5829 	type = zend_hash_str_find_ptr(&FFI_G(types), name, name_len);
5830 	if (type) {
5831 		return 1;
5832 	}
5833 	return 0;
5834 }
5835 /* }}} */
5836 
5837 void zend_ffi_resolve_typedef(const char *name, size_t name_len, zend_ffi_dcl *dcl) /* {{{ */
5838 {
5839 	zend_ffi_symbol *sym;
5840 	zend_ffi_type *type;
5841 
5842 	if (FFI_G(symbols)) {
5843 		sym = zend_hash_str_find_ptr(FFI_G(symbols), name, name_len);
5844 		if (sym && sym->kind == ZEND_FFI_SYM_TYPE) {
5845 			dcl->type = ZEND_FFI_TYPE(sym->type);
5846 			if (sym->is_const) {
5847 				dcl->attr |= ZEND_FFI_ATTR_CONST;
5848 			}
5849 			return;
5850 		}
5851 	}
5852 	type = zend_hash_str_find_ptr(&FFI_G(types), name, name_len);
5853 	if (type) {
5854 		dcl->type = type;
5855 		return;
5856 	}
5857 	zend_ffi_parser_error("Undefined C type \"%.*s\" at line %d", name_len, name, FFI_G(line));
5858 }
5859 /* }}} */
5860 
5861 void zend_ffi_resolve_const(const char *name, size_t name_len, zend_ffi_val *val) /* {{{ */
5862 {
5863 	zend_ffi_symbol *sym;
5864 
5865 	if (UNEXPECTED(FFI_G(attribute_parsing))) {
5866 		val->kind = ZEND_FFI_VAL_NAME;
5867 		val->str = name;
5868 		val->len = name_len;
5869 		return;
5870 	} else if (FFI_G(symbols)) {
5871 		sym = zend_hash_str_find_ptr(FFI_G(symbols), name, name_len);
5872 		if (sym && sym->kind == ZEND_FFI_SYM_CONST) {
5873 			val->i64 = sym->value;
5874 			switch (sym->type->kind) {
5875 				case ZEND_FFI_TYPE_SINT8:
5876 				case ZEND_FFI_TYPE_SINT16:
5877 				case ZEND_FFI_TYPE_SINT32:
5878 					val->kind = ZEND_FFI_VAL_INT32;
5879 					break;
5880 				case ZEND_FFI_TYPE_SINT64:
5881 					val->kind = ZEND_FFI_VAL_INT64;
5882 					break;
5883 				case ZEND_FFI_TYPE_UINT8:
5884 				case ZEND_FFI_TYPE_UINT16:
5885 				case ZEND_FFI_TYPE_UINT32:
5886 					val->kind = ZEND_FFI_VAL_UINT32;
5887 					break;
5888 				case ZEND_FFI_TYPE_UINT64:
5889 					val->kind = ZEND_FFI_VAL_UINT64;
5890 					break;
5891 				default:
5892 					ZEND_UNREACHABLE();
5893 			}
5894 			return;
5895 		}
5896 	}
5897 	val->kind = ZEND_FFI_VAL_ERROR;
5898 }
5899 /* }}} */
5900 
5901 void zend_ffi_make_enum_type(zend_ffi_dcl *dcl) /* {{{ */
5902 {
5903 	zend_ffi_type *type = pemalloc(sizeof(zend_ffi_type), FFI_G(persistent));
5904 	type->kind = ZEND_FFI_TYPE_ENUM;
5905 	type->attr = FFI_G(default_type_attr) | (dcl->attr & ZEND_FFI_ENUM_ATTRS);
5906 	type->enumeration.tag_name = NULL;
5907 	if (type->attr & ZEND_FFI_ATTR_PACKED) {
5908 		type->size = zend_ffi_type_uint8.size;
5909 		type->align = zend_ffi_type_uint8.align;
5910 		type->enumeration.kind = ZEND_FFI_TYPE_UINT8;
5911 	} else {
5912 		type->size = zend_ffi_type_uint32.size;
5913 		type->align = zend_ffi_type_uint32.align;
5914 		type->enumeration.kind = ZEND_FFI_TYPE_UINT32;
5915 	}
5916 	dcl->type = ZEND_FFI_TYPE_MAKE_OWNED(type);
5917 	dcl->attr &= ~ZEND_FFI_ENUM_ATTRS;
5918 }
5919 /* }}} */
5920 
5921 void zend_ffi_add_enum_val(zend_ffi_dcl *enum_dcl, const char *name, size_t name_len, zend_ffi_val *val, int64_t *min, int64_t *max, int64_t *last) /* {{{ */
5922 {
5923 	zend_ffi_symbol *sym;
5924 	const zend_ffi_type *sym_type;
5925 	int64_t value;
5926 	zend_ffi_type *enum_type = ZEND_FFI_TYPE(enum_dcl->type);
5927 	bool overflow = 0;
5928 	bool is_signed =
5929 		(enum_type->enumeration.kind == ZEND_FFI_TYPE_SINT8 ||
5930 		 enum_type->enumeration.kind == ZEND_FFI_TYPE_SINT16 ||
5931 		 enum_type->enumeration.kind == ZEND_FFI_TYPE_SINT32 ||
5932 		 enum_type->enumeration.kind == ZEND_FFI_TYPE_SINT64);
5933 
5934 	ZEND_ASSERT(enum_type && enum_type->kind == ZEND_FFI_TYPE_ENUM);
5935 	if (val->kind == ZEND_FFI_VAL_EMPTY) {
5936 		if (is_signed) {
5937 			if (*last == 0x7FFFFFFFFFFFFFFFLL) {
5938 				overflow = 1;
5939 			}
5940 		} else {
5941 			if ((*min != 0 || *max != 0)
5942 			 && (uint64_t)*last == 0xFFFFFFFFFFFFFFFFULL) {
5943 				overflow = 1;
5944 			}
5945 		}
5946 		value = *last + 1;
5947 	} else if (val->kind == ZEND_FFI_VAL_CHAR) {
5948 		if (!is_signed && val->ch < 0) {
5949 			if ((uint64_t)*max > 0x7FFFFFFFFFFFFFFFULL) {
5950 				overflow = 1;
5951 			} else {
5952 				is_signed = 1;
5953 			}
5954 		}
5955 		value = val->ch;
5956 	} else if (val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_INT64) {
5957 		if (!is_signed && val->i64 < 0) {
5958 			if ((uint64_t)*max > 0x7FFFFFFFFFFFFFFFULL) {
5959 				overflow = 1;
5960 			} else {
5961 				is_signed = 1;
5962 			}
5963 		}
5964 		value = val->i64;
5965 	} else if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_UINT64) {
5966 		if (is_signed && val->u64 > 0x7FFFFFFFFFFFFFFFULL) {
5967 			overflow = 1;
5968 		}
5969 		value = val->u64;
5970 	} else {
5971 		zend_ffi_parser_error("Enumerator value \"%.*s\" must be an integer at line %d", name_len, name, FFI_G(line));
5972 		return;
5973 	}
5974 
5975 	if (overflow) {
5976 		zend_ffi_parser_error("Overflow in enumeration values \"%.*s\" at line %d", name_len, name, FFI_G(line));
5977 		return;
5978 	}
5979 
5980 	if (is_signed) {
5981 		*min = MIN(*min, value);
5982 		*max = MAX(*max, value);
5983 		if ((enum_type->attr & ZEND_FFI_ATTR_PACKED)
5984 		 && *min >= -0x7FLL-1 && *max <= 0x7FLL) {
5985 			sym_type = &zend_ffi_type_sint8;
5986 		} else if ((enum_type->attr & ZEND_FFI_ATTR_PACKED)
5987 		 && *min >= -0x7FFFLL-1 && *max <= 0x7FFFLL) {
5988 			sym_type = &zend_ffi_type_sint16;
5989 		} else if (*min >= -0x7FFFFFFFLL-1 && *max <= 0x7FFFFFFFLL) {
5990 			sym_type = &zend_ffi_type_sint32;
5991 		} else {
5992 			sym_type = &zend_ffi_type_sint64;
5993 		}
5994 	} else {
5995 		*min = MIN((uint64_t)*min, (uint64_t)value);
5996 		*max = MAX((uint64_t)*max, (uint64_t)value);
5997 		if ((enum_type->attr & ZEND_FFI_ATTR_PACKED)
5998 		 && (uint64_t)*max <= 0xFFULL) {
5999 			sym_type = &zend_ffi_type_uint8;
6000 		} else if ((enum_type->attr & ZEND_FFI_ATTR_PACKED)
6001 		 && (uint64_t)*max <= 0xFFFFULL) {
6002 			sym_type = &zend_ffi_type_uint16;
6003 		} else if ((uint64_t)*max <= 0xFFFFFFFFULL) {
6004 			sym_type = &zend_ffi_type_uint32;
6005 		} else {
6006 			sym_type = &zend_ffi_type_uint64;
6007 		}
6008 	}
6009 	enum_type->enumeration.kind = sym_type->kind;
6010 	enum_type->size = sym_type->size;
6011 	enum_type->align = sym_type->align;
6012 	*last = value;
6013 
6014 	if (!FFI_G(symbols)) {
6015 		FFI_G(symbols) = pemalloc(sizeof(HashTable), FFI_G(persistent));
6016 		zend_hash_init(FFI_G(symbols), 0, NULL, FFI_G(persistent) ? zend_ffi_symbol_hash_persistent_dtor : zend_ffi_symbol_hash_dtor, FFI_G(persistent));
6017 	}
6018 	sym = zend_hash_str_find_ptr(FFI_G(symbols), name, name_len);
6019 	if (sym) {
6020 		zend_ffi_parser_error("Redeclaration of \"%.*s\" at line %d", name_len, name, FFI_G(line));
6021 	} else {
6022 		sym = pemalloc(sizeof(zend_ffi_symbol), FFI_G(persistent));
6023 		sym->kind  = ZEND_FFI_SYM_CONST;
6024 		sym->type  = (zend_ffi_type*)sym_type;
6025 		sym->value = value;
6026 		zend_hash_str_add_new_ptr(FFI_G(symbols), name, name_len, sym);
6027 	}
6028 }
6029 /* }}} */
6030 
6031 void zend_ffi_make_struct_type(zend_ffi_dcl *dcl) /* {{{ */
6032 {
6033 	zend_ffi_type *type = pemalloc(sizeof(zend_ffi_type), FFI_G(persistent));
6034 	type->kind = ZEND_FFI_TYPE_STRUCT;
6035 	type->attr = FFI_G(default_type_attr) | (dcl->attr & ZEND_FFI_STRUCT_ATTRS);
6036 	type->size = 0;
6037 	type->align = dcl->align > 1 ? dcl->align : 1;
6038 	if (dcl->flags & ZEND_FFI_DCL_UNION) {
6039 		type->attr |= ZEND_FFI_ATTR_UNION;
6040 	}
6041 	dcl->type = ZEND_FFI_TYPE_MAKE_OWNED(type);
6042 	type->record.tag_name = NULL;
6043 	zend_hash_init(&type->record.fields, 0, NULL, FFI_G(persistent) ? zend_ffi_field_hash_persistent_dtor :zend_ffi_field_hash_dtor, FFI_G(persistent));
6044 	dcl->attr &= ~ZEND_FFI_STRUCT_ATTRS;
6045 	dcl->align = 0;
6046 }
6047 /* }}} */
6048 
6049 static zend_result zend_ffi_validate_prev_field_type(zend_ffi_type *struct_type) /* {{{ */
6050 {
6051 	if (zend_hash_num_elements(&struct_type->record.fields) > 0) {
6052 		zend_ffi_field *field = NULL;
6053 
6054 		ZEND_HASH_MAP_REVERSE_FOREACH_PTR(&struct_type->record.fields, field) {
6055 			break;
6056 		} ZEND_HASH_FOREACH_END();
6057 		if (ZEND_FFI_TYPE(field->type)->attr & ZEND_FFI_ATTR_INCOMPLETE_ARRAY) {
6058 			zend_ffi_throw_parser_error("Flexible array member not at end of struct at line %d", FFI_G(line));
6059 			return FAILURE;
6060 		}
6061 	}
6062 	return SUCCESS;
6063 }
6064 /* }}} */
6065 
6066 static zend_result zend_ffi_validate_field_type(zend_ffi_type *type, zend_ffi_type *struct_type) /* {{{ */
6067 {
6068 	if (type == struct_type) {
6069 		zend_ffi_throw_parser_error("Struct/union can't contain an instance of itself at line %d", FFI_G(line));
6070 		return FAILURE;
6071 	} else if (zend_ffi_validate_var_type(type, 1) == FAILURE) {
6072 		return FAILURE;
6073 	} else if (struct_type->attr & ZEND_FFI_ATTR_UNION) {
6074 		if (type->attr & ZEND_FFI_ATTR_INCOMPLETE_ARRAY) {
6075 			zend_ffi_throw_parser_error("Flexible array member in union at line %d", FFI_G(line));
6076 			return FAILURE;
6077 		}
6078 	}
6079 	return zend_ffi_validate_prev_field_type(struct_type);
6080 }
6081 /* }}} */
6082 
6083 void zend_ffi_add_field(zend_ffi_dcl *struct_dcl, const char *name, size_t name_len, zend_ffi_dcl *field_dcl) /* {{{ */
6084 {
6085 	zend_ffi_field *field;
6086 	zend_ffi_type *struct_type = ZEND_FFI_TYPE(struct_dcl->type);
6087 	zend_ffi_type *field_type;
6088 
6089 	ZEND_ASSERT(struct_type && struct_type->kind == ZEND_FFI_TYPE_STRUCT);
6090 	zend_ffi_finalize_type(field_dcl);
6091 	field_type = ZEND_FFI_TYPE(field_dcl->type);
6092 	if (zend_ffi_validate_field_type(field_type, struct_type) == FAILURE) {
6093 		zend_ffi_cleanup_dcl(field_dcl);
6094 		LONGJMP(FFI_G(bailout), FAILURE);
6095 	}
6096 
6097 	field = pemalloc(sizeof(zend_ffi_field), FFI_G(persistent));
6098 	if (!(struct_type->attr & ZEND_FFI_ATTR_PACKED) && !(field_dcl->attr & ZEND_FFI_ATTR_PACKED)) {
6099 		struct_type->align = MAX(struct_type->align, MAX(field_type->align, field_dcl->align));
6100 	}
6101 	if (struct_type->attr & ZEND_FFI_ATTR_UNION) {
6102 		field->offset = 0;
6103 		struct_type->size = MAX(struct_type->size, field_type->size);
6104 	} else {
6105 		if (!(struct_type->attr & ZEND_FFI_ATTR_PACKED) && !(field_dcl->attr & ZEND_FFI_ATTR_PACKED)) {
6106 			uint32_t field_align = MAX(field_type->align, field_dcl->align);
6107 			struct_type->size = ((struct_type->size + (field_align - 1)) / field_align) * field_align;
6108 		}
6109 		field->offset = struct_type->size;
6110 		struct_type->size += field_type->size;
6111 	}
6112 	field->type = field_dcl->type;
6113 	field->is_const = (bool)(field_dcl->attr & ZEND_FFI_ATTR_CONST);
6114 	field->is_nested = 0;
6115 	field->first_bit = 0;
6116 	field->bits = 0;
6117 	field_dcl->type = field_type; /* reset "owned" flag */
6118 
6119 	if (!zend_hash_str_add_ptr(&struct_type->record.fields, name, name_len, field)) {
6120 		zend_ffi_type_dtor(field->type);
6121 		pefree(field, FFI_G(persistent));
6122 		zend_ffi_parser_error("Duplicate field name \"%.*s\" at line %d", name_len, name, FFI_G(line));
6123 	}
6124 }
6125 /* }}} */
6126 
6127 void zend_ffi_add_anonymous_field(zend_ffi_dcl *struct_dcl, zend_ffi_dcl *field_dcl) /* {{{ */
6128 {
6129 	zend_ffi_type *struct_type = ZEND_FFI_TYPE(struct_dcl->type);
6130 	zend_ffi_type *field_type;
6131 	zend_ffi_field *field;
6132 	zend_string *key;
6133 
6134 	ZEND_ASSERT(struct_type && struct_type->kind == ZEND_FFI_TYPE_STRUCT);
6135 	zend_ffi_finalize_type(field_dcl);
6136 	field_type = ZEND_FFI_TYPE(field_dcl->type);
6137 	if (field_type->kind != ZEND_FFI_TYPE_STRUCT) {
6138 		zend_ffi_cleanup_dcl(field_dcl);
6139 		zend_ffi_parser_error("Declaration does not declare anything at line %d", FFI_G(line));
6140 		return;
6141 	}
6142 
6143 	if (!(struct_type->attr & ZEND_FFI_ATTR_PACKED) && !(field_dcl->attr & ZEND_FFI_ATTR_PACKED)) {
6144 		struct_type->align = MAX(struct_type->align, MAX(field_type->align, field_dcl->align));
6145 	}
6146 	if (!(struct_type->attr & ZEND_FFI_ATTR_UNION)) {
6147 		if (zend_ffi_validate_prev_field_type(struct_type) == FAILURE) {
6148 			zend_ffi_cleanup_dcl(field_dcl);
6149 			LONGJMP(FFI_G(bailout), FAILURE);
6150 		}
6151 		if (!(struct_type->attr & ZEND_FFI_ATTR_PACKED) && !(field_dcl->attr & ZEND_FFI_ATTR_PACKED)) {
6152 			uint32_t field_align = MAX(field_type->align, field_dcl->align);
6153 			struct_type->size = ((struct_type->size + (field_align - 1)) / field_align) * field_align;
6154 		}
6155 	}
6156 
6157 	ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(&field_type->record.fields, key, field) {
6158 		zend_ffi_field *new_field = pemalloc(sizeof(zend_ffi_field), FFI_G(persistent));
6159 
6160 		if (struct_type->attr & ZEND_FFI_ATTR_UNION) {
6161 			new_field->offset = field->offset;
6162 		} else {
6163 			new_field->offset = struct_type->size + field->offset;
6164 		}
6165 		new_field->type = field->type;
6166 		new_field->is_const = field->is_const;
6167 		new_field->is_nested = 1;
6168 		new_field->first_bit = field->first_bit;
6169 		new_field->bits = field->bits;
6170 		field->type = ZEND_FFI_TYPE(field->type); /* reset "owned" flag */
6171 
6172 		if (key) {
6173 			if (!zend_hash_add_ptr(&struct_type->record.fields, key, new_field)) {
6174 				zend_ffi_type_dtor(new_field->type);
6175 				pefree(new_field, FFI_G(persistent));
6176 				zend_ffi_parser_error("Duplicate field name \"%s\" at line %d", ZSTR_VAL(key), FFI_G(line));
6177 				return;
6178 			}
6179 		} else {
6180 			zend_hash_next_index_insert_ptr(&struct_type->record.fields, field);
6181 		}
6182 	} ZEND_HASH_FOREACH_END();
6183 
6184 	if (struct_type->attr & ZEND_FFI_ATTR_UNION) {
6185 		struct_type->size = MAX(struct_type->size, field_type->size);
6186 	} else {
6187 		struct_type->size += field_type->size;
6188 	}
6189 
6190 	zend_ffi_type_dtor(field_dcl->type);
6191 	field_dcl->type = NULL;
6192 }
6193 /* }}} */
6194 
6195 void zend_ffi_add_bit_field(zend_ffi_dcl *struct_dcl, const char *name, size_t name_len, zend_ffi_dcl *field_dcl, zend_ffi_val *bits) /* {{{ */
6196 {
6197 	zend_ffi_type *struct_type = ZEND_FFI_TYPE(struct_dcl->type);
6198 	zend_ffi_type *field_type;
6199 	zend_ffi_field *field;
6200 
6201 	ZEND_ASSERT(struct_type && struct_type->kind == ZEND_FFI_TYPE_STRUCT);
6202 	zend_ffi_finalize_type(field_dcl);
6203 	field_type = ZEND_FFI_TYPE(field_dcl->type);
6204 	if (zend_ffi_validate_field_type(field_type, struct_type) == FAILURE) {
6205 		zend_ffi_cleanup_dcl(field_dcl);
6206 		LONGJMP(FFI_G(bailout), FAILURE);
6207 	}
6208 
6209 	if (field_type->kind < ZEND_FFI_TYPE_UINT8 || field_type->kind > ZEND_FFI_TYPE_BOOL) {
6210 		zend_ffi_cleanup_dcl(field_dcl);
6211 		zend_ffi_parser_error("Wrong type of bit field \"%.*s\" at line %d", name ? name_len : sizeof("<anonymous>")-1, name ? name : "<anonymous>", FFI_G(line));
6212 	}
6213 
6214 	if (bits->kind == ZEND_FFI_VAL_INT32 || bits->kind == ZEND_FFI_VAL_INT64) {
6215 		if (bits->i64 < 0) {
6216 			zend_ffi_cleanup_dcl(field_dcl);
6217 			zend_ffi_parser_error("Negative width in bit-field \"%.*s\" at line %d", name ? name_len : sizeof("<anonymous>")-1, name ? name : "<anonymous>", FFI_G(line));
6218 		} else if (bits->i64 == 0) {
6219 			zend_ffi_cleanup_dcl(field_dcl);
6220 			if (name) {
6221 				zend_ffi_parser_error("Zero width in bit-field \"%.*s\" at line %d", name ? name_len : sizeof("<anonymous>")-1, name ? name : "<anonymous>", FFI_G(line));
6222 			}
6223 			return;
6224 		} else if (bits->i64 > field_type->size * 8) {
6225 			zend_ffi_cleanup_dcl(field_dcl);
6226 			zend_ffi_parser_error("Width of \"%.*s\" exceeds its type at line %d", name ? name_len : sizeof("<anonymous>")-1, name ? name : "<anonymous>", FFI_G(line));
6227 		}
6228 	} else if (bits->kind == ZEND_FFI_VAL_UINT32 || bits->kind == ZEND_FFI_VAL_UINT64) {
6229 		if (bits->u64 == 0) {
6230 			zend_ffi_cleanup_dcl(field_dcl);
6231 			if (name) {
6232 				zend_ffi_parser_error("Zero width in bit-field \"%.*s\" at line %d", name ? name_len : sizeof("<anonymous>")-1, name ? name : "<anonymous>", FFI_G(line));
6233 			}
6234 			return;
6235 		} else if (bits->u64 > field_type->size * 8) {
6236 			zend_ffi_cleanup_dcl(field_dcl);
6237 			zend_ffi_parser_error("Width of \"%.*s\" exceeds its type at line %d", name ? name_len : sizeof("<anonymous>")-1, name ? name : "<anonymous>", FFI_G(line));
6238 		}
6239 	} else {
6240 		zend_ffi_cleanup_dcl(field_dcl);
6241 		zend_ffi_parser_error("Bit field \"%.*s\" width not an integer constant at line %d", name ? name_len : sizeof("<anonymous>")-1, name ? name : "<anonymous>", FFI_G(line));
6242 	}
6243 
6244 	field = pemalloc(sizeof(zend_ffi_field), FFI_G(persistent));
6245 	if (!(struct_type->attr & ZEND_FFI_ATTR_PACKED)) {
6246 		struct_type->align = MAX(struct_type->align, sizeof(uint32_t));
6247 	}
6248 	if (struct_type->attr & ZEND_FFI_ATTR_UNION) {
6249 		field->offset = 0;
6250 		field->first_bit = 0;
6251 		field->bits = bits->u64;
6252 		if (struct_type->attr & ZEND_FFI_ATTR_PACKED) {
6253 			struct_type->size = MAX(struct_type->size, (bits->u64 + 7) / 8);
6254 		} else {
6255 			struct_type->size = MAX(struct_type->size, ((bits->u64 + 31) / 32) * 4);
6256 		}
6257 	} else {
6258 		zend_ffi_field *prev_field = NULL;
6259 
6260 		if (zend_hash_num_elements(&struct_type->record.fields) > 0) {
6261 			ZEND_HASH_MAP_REVERSE_FOREACH_PTR(&struct_type->record.fields, prev_field) {
6262 				break;
6263 			} ZEND_HASH_FOREACH_END();
6264 		}
6265 		if (prev_field && prev_field->bits) {
6266 			field->offset = prev_field->offset;
6267 			field->first_bit = prev_field->first_bit + prev_field->bits;
6268 			field->bits = bits->u64;
6269 		} else {
6270 			field->offset = struct_type->size;
6271 			field->first_bit = 0;
6272 			field->bits = bits->u64;
6273 		}
6274 		if (struct_type->attr & ZEND_FFI_ATTR_PACKED) {
6275 			struct_type->size = field->offset + ((field->first_bit + field->bits) + 7) / 8;
6276 		} else {
6277 			struct_type->size = field->offset + (((field->first_bit + field->bits) + 31) / 32) * 4;
6278 		}
6279 	}
6280 	field->type = field_dcl->type;
6281 	field->is_const = (bool)(field_dcl->attr & ZEND_FFI_ATTR_CONST);
6282 	field->is_nested = 0;
6283 	field_dcl->type = field_type; /* reset "owned" flag */
6284 
6285 	if (name) {
6286 		if (!zend_hash_str_add_ptr(&struct_type->record.fields, name, name_len, field)) {
6287 			zend_ffi_type_dtor(field->type);
6288 			pefree(field, FFI_G(persistent));
6289 			zend_ffi_parser_error("Duplicate field name \"%.*s\" at line %d", name_len, name, FFI_G(line));
6290 		}
6291 	} else {
6292 		zend_hash_next_index_insert_ptr(&struct_type->record.fields, field);
6293 	}
6294 }
6295 /* }}} */
6296 
6297 void zend_ffi_adjust_struct_size(zend_ffi_dcl *dcl) /* {{{ */
6298 {
6299 	zend_ffi_type *struct_type = ZEND_FFI_TYPE(dcl->type);
6300 
6301 	ZEND_ASSERT(struct_type->kind == ZEND_FFI_TYPE_STRUCT);
6302 	if (dcl->align > struct_type->align) {
6303 		struct_type->align = dcl->align;
6304 	}
6305 	if (!(struct_type->attr & ZEND_FFI_ATTR_PACKED)) {
6306 		struct_type->size = ((struct_type->size + (struct_type->align - 1)) / struct_type->align) * struct_type->align;
6307 	}
6308 	dcl->align = 0;
6309 }
6310 /* }}} */
6311 
6312 void zend_ffi_make_pointer_type(zend_ffi_dcl *dcl) /* {{{ */
6313 {
6314 	zend_ffi_type *type = pemalloc(sizeof(zend_ffi_type), FFI_G(persistent));
6315 	type->kind = ZEND_FFI_TYPE_POINTER;
6316 	type->attr = FFI_G(default_type_attr) | (dcl->attr & ZEND_FFI_POINTER_ATTRS);
6317 	type->size = sizeof(void*);
6318 	type->align = _Alignof(void*);
6319 	zend_ffi_finalize_type(dcl);
6320 	if (zend_ffi_validate_vla(ZEND_FFI_TYPE(dcl->type)) == FAILURE) {
6321 		zend_ffi_cleanup_dcl(dcl);
6322 		LONGJMP(FFI_G(bailout), FAILURE);
6323 	}
6324 	type->pointer.type = dcl->type;
6325 	dcl->type = ZEND_FFI_TYPE_MAKE_OWNED(type);
6326 	dcl->flags &= ~ZEND_FFI_DCL_TYPE_QUALIFIERS;
6327 	dcl->attr &= ~ZEND_FFI_POINTER_ATTRS;
6328 	dcl->align = 0;
6329 }
6330 /* }}} */
6331 
6332 static zend_result zend_ffi_validate_array_element_type(zend_ffi_type *type) /* {{{ */
6333 {
6334 	if (type->kind == ZEND_FFI_TYPE_FUNC) {
6335 		zend_ffi_throw_parser_error("Array of functions is not allowed at line %d", FFI_G(line));
6336 		return FAILURE;
6337 	} else if (type->kind == ZEND_FFI_TYPE_ARRAY && (type->attr & ZEND_FFI_ATTR_INCOMPLETE_ARRAY)) {
6338 		zend_ffi_throw_parser_error("Only the leftmost array can be undimensioned at line %d", FFI_G(line));
6339 		return FAILURE;
6340 	}
6341 	return zend_ffi_validate_type(type, 0, 1);
6342 }
6343 /* }}} */
6344 
6345 void zend_ffi_make_array_type(zend_ffi_dcl *dcl, zend_ffi_val *len) /* {{{ */
6346 {
6347 	int length = 0;
6348 	zend_ffi_type *element_type;
6349 	zend_ffi_type *type;
6350 
6351 	zend_ffi_finalize_type(dcl);
6352 	element_type = ZEND_FFI_TYPE(dcl->type);
6353 
6354 	if (len->kind == ZEND_FFI_VAL_EMPTY) {
6355 		length = 0;
6356 	} else if (len->kind == ZEND_FFI_VAL_UINT32 || len->kind == ZEND_FFI_VAL_UINT64) {
6357 		length = len->u64;
6358 	} else if (len->kind == ZEND_FFI_VAL_INT32 || len->kind == ZEND_FFI_VAL_INT64) {
6359 		length = len->i64;
6360 	} else if (len->kind == ZEND_FFI_VAL_CHAR) {
6361 		length = len->ch;
6362 	} else {
6363 		zend_ffi_cleanup_dcl(dcl);
6364 		zend_ffi_parser_error("Unsupported array index type at line %d", FFI_G(line));
6365 		return;
6366 	}
6367 	if (length < 0) {
6368 		zend_ffi_cleanup_dcl(dcl);
6369 		zend_ffi_parser_error("Negative array index at line %d", FFI_G(line));
6370 		return;
6371 	}
6372 
6373 	if (zend_ffi_validate_array_element_type(element_type) == FAILURE) {
6374 		zend_ffi_cleanup_dcl(dcl);
6375 		LONGJMP(FFI_G(bailout), FAILURE);
6376 	}
6377 
6378 	type = pemalloc(sizeof(zend_ffi_type), FFI_G(persistent));
6379 	type->kind = ZEND_FFI_TYPE_ARRAY;
6380 	type->attr = FFI_G(default_type_attr) | (dcl->attr & ZEND_FFI_ARRAY_ATTRS);
6381 	type->size = length * element_type->size;
6382 	type->align = element_type->align;
6383 	type->array.type = dcl->type;
6384 	type->array.length = length;
6385 	dcl->type = ZEND_FFI_TYPE_MAKE_OWNED(type);
6386 	dcl->flags &= ~ZEND_FFI_DCL_TYPE_QUALIFIERS;
6387 	dcl->attr &= ~ZEND_FFI_ARRAY_ATTRS;
6388 	dcl->align = 0;
6389 }
6390 /* }}} */
6391 
6392 static zend_result zend_ffi_validate_func_ret_type(zend_ffi_type *type) /* {{{ */
6393 {
6394 	if (type->kind == ZEND_FFI_TYPE_FUNC) {
6395 		zend_ffi_throw_parser_error("Function returning function is not allowed at line %d", FFI_G(line));
6396 		return FAILURE;
6397 	 } else if (type->kind == ZEND_FFI_TYPE_ARRAY) {
6398 		zend_ffi_throw_parser_error("Function returning array is not allowed at line %d", FFI_G(line));
6399 		return FAILURE;
6400 	}
6401 	return zend_ffi_validate_incomplete_type(type, 1, 0);
6402 }
6403 /* }}} */
6404 
6405 void zend_ffi_make_func_type(zend_ffi_dcl *dcl, HashTable *args, zend_ffi_dcl *nested_dcl) /* {{{ */
6406 {
6407 	zend_ffi_type *type;
6408 	zend_ffi_type *ret_type;
6409 
6410 	zend_ffi_finalize_type(dcl);
6411 	ret_type = ZEND_FFI_TYPE(dcl->type);
6412 
6413 	if (args) {
6414 		int no_args = 0;
6415 		zend_ffi_type *arg_type;
6416 
6417 		ZEND_HASH_PACKED_FOREACH_PTR(args, arg_type) {
6418 			arg_type = ZEND_FFI_TYPE(arg_type);
6419 			if (arg_type->kind == ZEND_FFI_TYPE_VOID) {
6420 				if (zend_hash_num_elements(args) != 1) {
6421 					zend_ffi_cleanup_dcl(nested_dcl);
6422 					zend_ffi_cleanup_dcl(dcl);
6423 					zend_hash_destroy(args);
6424 					pefree(args, FFI_G(persistent));
6425 					zend_ffi_parser_error("void type is not allowed at line %d", FFI_G(line));
6426 					return;
6427 				} else {
6428 					no_args = 1;
6429 				}
6430 			}
6431 		} ZEND_HASH_FOREACH_END();
6432 		if (no_args) {
6433 			zend_hash_destroy(args);
6434 			pefree(args, FFI_G(persistent));
6435 			args = NULL;
6436 		}
6437 	}
6438 
6439 #ifdef HAVE_FFI_VECTORCALL_PARTIAL
6440 	if (dcl->abi == ZEND_FFI_ABI_VECTORCALL && args) {
6441 		zend_ulong i;
6442 		zend_ffi_type *arg_type;
6443 
6444 		ZEND_HASH_PACKED_FOREACH_KEY_PTR(args, i, arg_type) {
6445 			arg_type = ZEND_FFI_TYPE(arg_type);
6446 # ifdef _WIN64
6447 			if (i >= 4 && i <= 5 && (arg_type->kind == ZEND_FFI_TYPE_FLOAT || arg_type->kind == ZEND_FFI_TYPE_DOUBLE)) {
6448 # else
6449 			if (i < 6 && (arg_type->kind == ZEND_FFI_TYPE_FLOAT || arg_type->kind == ZEND_FFI_TYPE_DOUBLE)) {
6450 # endif
6451 				zend_ffi_cleanup_dcl(nested_dcl);
6452 				zend_ffi_cleanup_dcl(dcl);
6453 				zend_hash_destroy(args);
6454 				pefree(args, FFI_G(persistent));
6455 				zend_ffi_parser_error("Type float/double is not allowed at position " ZEND_ULONG_FMT " with __vectorcall at line %d", i+1, FFI_G(line));
6456 				return;
6457 			}
6458 		} ZEND_HASH_FOREACH_END();
6459 	}
6460 #endif
6461 
6462 	if (zend_ffi_validate_func_ret_type(ret_type) == FAILURE) {
6463 		zend_ffi_cleanup_dcl(nested_dcl);
6464 		zend_ffi_cleanup_dcl(dcl);
6465 		if (args) {
6466 			zend_hash_destroy(args);
6467 			pefree(args, FFI_G(persistent));
6468 		}
6469 		LONGJMP(FFI_G(bailout), FAILURE);
6470 	}
6471 
6472 	type = pemalloc(sizeof(zend_ffi_type), FFI_G(persistent));
6473 	type->kind = ZEND_FFI_TYPE_FUNC;
6474 	type->attr = FFI_G(default_type_attr) | (dcl->attr & ZEND_FFI_FUNC_ATTRS);
6475 	type->size = sizeof(void*);
6476 	type->align = 1;
6477 	type->func.ret_type = dcl->type;
6478 	switch (dcl->abi) {
6479 		case ZEND_FFI_ABI_DEFAULT:
6480 		case ZEND_FFI_ABI_CDECL:
6481 			type->func.abi = FFI_DEFAULT_ABI;
6482 			break;
6483 #ifdef HAVE_FFI_FASTCALL
6484 		case ZEND_FFI_ABI_FASTCALL:
6485 			type->func.abi = FFI_FASTCALL;
6486 			break;
6487 #endif
6488 #ifdef HAVE_FFI_THISCALL
6489 		case ZEND_FFI_ABI_THISCALL:
6490 			type->func.abi = FFI_THISCALL;
6491 			break;
6492 #endif
6493 #ifdef HAVE_FFI_STDCALL
6494 		case ZEND_FFI_ABI_STDCALL:
6495 			type->func.abi = FFI_STDCALL;
6496 			break;
6497 #endif
6498 #ifdef HAVE_FFI_PASCAL
6499 		case ZEND_FFI_ABI_PASCAL:
6500 			type->func.abi = FFI_PASCAL;
6501 			break;
6502 #endif
6503 #ifdef HAVE_FFI_REGISTER
6504 		case ZEND_FFI_ABI_REGISTER:
6505 			type->func.abi = FFI_REGISTER;
6506 			break;
6507 #endif
6508 #ifdef HAVE_FFI_MS_CDECL
6509 		case ZEND_FFI_ABI_MS:
6510 			type->func.abi = FFI_MS_CDECL;
6511 			break;
6512 #endif
6513 #ifdef HAVE_FFI_SYSV
6514 		case ZEND_FFI_ABI_SYSV:
6515 			type->func.abi = FFI_SYSV;
6516 			break;
6517 #endif
6518 #ifdef HAVE_FFI_VECTORCALL_PARTIAL
6519 		case ZEND_FFI_ABI_VECTORCALL:
6520 			type->func.abi = FFI_VECTORCALL_PARTIAL;
6521 			break;
6522 #endif
6523 		default:
6524 			type->func.abi = FFI_DEFAULT_ABI;
6525 			zend_ffi_cleanup_dcl(nested_dcl);
6526 			if (args) {
6527 				zend_hash_destroy(args);
6528 				pefree(args, FFI_G(persistent));
6529 			}
6530 			type->func.args = NULL;
6531 			_zend_ffi_type_dtor(type);
6532 			zend_ffi_parser_error("Unsupported calling convention line %d", FFI_G(line));
6533 			break;
6534 	}
6535 	type->func.args = args;
6536 	dcl->type = ZEND_FFI_TYPE_MAKE_OWNED(type);
6537 	dcl->attr &= ~ZEND_FFI_FUNC_ATTRS;
6538 	dcl->align = 0;
6539 	dcl->abi = 0;
6540 }
6541 /* }}} */
6542 
6543 void zend_ffi_add_arg(HashTable **args, const char *name, size_t name_len, zend_ffi_dcl *arg_dcl) /* {{{ */
6544 {
6545 	zend_ffi_type *type;
6546 
6547 	if (!*args) {
6548 		*args = pemalloc(sizeof(HashTable), FFI_G(persistent));
6549 		zend_hash_init(*args, 0, NULL, zend_ffi_type_hash_dtor, FFI_G(persistent));
6550 	}
6551 	zend_ffi_finalize_type(arg_dcl);
6552 	type = ZEND_FFI_TYPE(arg_dcl->type);
6553 	if (type->kind == ZEND_FFI_TYPE_ARRAY) {
6554 		if (ZEND_FFI_TYPE_IS_OWNED(arg_dcl->type)) {
6555 			type->kind = ZEND_FFI_TYPE_POINTER;
6556 			type->size = sizeof(void*);
6557 		} else {
6558 			zend_ffi_type *new_type = pemalloc(sizeof(zend_ffi_type), FFI_G(persistent));
6559 			new_type->kind = ZEND_FFI_TYPE_POINTER;
6560 			new_type->attr = FFI_G(default_type_attr) | (type->attr & ZEND_FFI_POINTER_ATTRS);
6561 			new_type->size = sizeof(void*);
6562 			new_type->align = _Alignof(void*);
6563 			new_type->pointer.type = ZEND_FFI_TYPE(type->array.type);
6564 			arg_dcl->type = ZEND_FFI_TYPE_MAKE_OWNED(new_type);
6565 		}
6566 	} else if (type->kind == ZEND_FFI_TYPE_FUNC) {
6567 		zend_ffi_type *new_type = pemalloc(sizeof(zend_ffi_type), FFI_G(persistent));
6568 		new_type->kind = ZEND_FFI_TYPE_POINTER;
6569 		new_type->attr = FFI_G(default_type_attr);
6570 		new_type->size = sizeof(void*);
6571 		new_type->align = _Alignof(void*);
6572 		new_type->pointer.type = arg_dcl->type;
6573 		arg_dcl->type = ZEND_FFI_TYPE_MAKE_OWNED(new_type);
6574 	}
6575 	if (zend_ffi_validate_incomplete_type(type, 1, 1) == FAILURE) {
6576 		zend_ffi_cleanup_dcl(arg_dcl);
6577 		zend_hash_destroy(*args);
6578 		pefree(*args, FFI_G(persistent));
6579 		*args = NULL;
6580 		LONGJMP(FFI_G(bailout), FAILURE);
6581 	}
6582 	zend_hash_next_index_insert_ptr(*args, (void*)arg_dcl->type);
6583 }
6584 /* }}} */
6585 
6586 void zend_ffi_declare(const char *name, size_t name_len, zend_ffi_dcl *dcl) /* {{{ */
6587 {
6588 	zend_ffi_symbol *sym;
6589 
6590 	if (!FFI_G(symbols)) {
6591 		FFI_G(symbols) = pemalloc(sizeof(HashTable), FFI_G(persistent));
6592 		zend_hash_init(FFI_G(symbols), 0, NULL, FFI_G(persistent) ? zend_ffi_symbol_hash_persistent_dtor : zend_ffi_symbol_hash_dtor, FFI_G(persistent));
6593 	}
6594 	zend_ffi_finalize_type(dcl);
6595 	sym = zend_hash_str_find_ptr(FFI_G(symbols), name, name_len);
6596 	if (sym) {
6597 		if ((dcl->flags & ZEND_FFI_DCL_STORAGE_CLASS) == ZEND_FFI_DCL_TYPEDEF
6598 		 && sym->kind == ZEND_FFI_SYM_TYPE
6599 		 && zend_ffi_is_same_type(ZEND_FFI_TYPE(sym->type), ZEND_FFI_TYPE(dcl->type))
6600 		 && sym->is_const == (bool)(dcl->attr & ZEND_FFI_ATTR_CONST)) {
6601 			/* allowed redeclaration */
6602 			zend_ffi_type_dtor(dcl->type);
6603 			return;
6604 		} else if ((dcl->flags & ZEND_FFI_DCL_STORAGE_CLASS) == 0
6605 		 || (dcl->flags & ZEND_FFI_DCL_STORAGE_CLASS) == ZEND_FFI_DCL_EXTERN) {
6606 			zend_ffi_type *type = ZEND_FFI_TYPE(dcl->type);
6607 
6608 			if (type->kind == ZEND_FFI_TYPE_FUNC) {
6609 				if (sym->kind == ZEND_FFI_SYM_FUNC
6610 				 && zend_ffi_same_types(ZEND_FFI_TYPE(sym->type), type)) {
6611 					/* allowed redeclaration */
6612 					zend_ffi_type_dtor(dcl->type);
6613 					return;
6614 				}
6615 			} else {
6616 				if (sym->kind == ZEND_FFI_SYM_VAR
6617 				 && zend_ffi_is_same_type(ZEND_FFI_TYPE(sym->type), type)
6618 				 && sym->is_const == (bool)(dcl->attr & ZEND_FFI_ATTR_CONST)) {
6619 					/* allowed redeclaration */
6620 					zend_ffi_type_dtor(dcl->type);
6621 					return;
6622 				}
6623 			}
6624 		}
6625 		zend_ffi_parser_error("Redeclaration of \"%.*s\" at line %d", name_len, name, FFI_G(line));
6626 	} else {
6627 		if ((dcl->flags & ZEND_FFI_DCL_STORAGE_CLASS) == ZEND_FFI_DCL_TYPEDEF) {
6628 			if (zend_ffi_validate_vla(ZEND_FFI_TYPE(dcl->type)) == FAILURE) {
6629 				zend_ffi_cleanup_dcl(dcl);
6630 				LONGJMP(FFI_G(bailout), FAILURE);
6631 			}
6632 			if (dcl->align && dcl->align > ZEND_FFI_TYPE(dcl->type)->align) {
6633 				if (ZEND_FFI_TYPE_IS_OWNED(dcl->type)) {
6634 					ZEND_FFI_TYPE(dcl->type)->align = dcl->align;
6635 				} else {
6636 					zend_ffi_type *type = pemalloc(sizeof(zend_ffi_type), FFI_G(persistent));
6637 
6638 					memcpy(type, ZEND_FFI_TYPE(dcl->type), sizeof(zend_ffi_type));
6639 					type->attr |= FFI_G(default_type_attr);
6640 					type->align = dcl->align;
6641 					dcl->type = ZEND_FFI_TYPE_MAKE_OWNED(type);
6642 				}
6643 			}
6644 			sym = pemalloc(sizeof(zend_ffi_symbol), FFI_G(persistent));
6645 			sym->kind = ZEND_FFI_SYM_TYPE;
6646 			sym->type = dcl->type;
6647 			sym->is_const = (bool)(dcl->attr & ZEND_FFI_ATTR_CONST);
6648 			dcl->type = ZEND_FFI_TYPE(dcl->type); /* reset "owned" flag */
6649 			zend_hash_str_add_new_ptr(FFI_G(symbols), name, name_len, sym);
6650 		} else {
6651 			zend_ffi_type *type;
6652 
6653 			type = ZEND_FFI_TYPE(dcl->type);
6654 			if (zend_ffi_validate_type(type, (dcl->flags & ZEND_FFI_DCL_STORAGE_CLASS) == ZEND_FFI_DCL_EXTERN, 1) == FAILURE) {
6655 				zend_ffi_cleanup_dcl(dcl);
6656 				LONGJMP(FFI_G(bailout), FAILURE);
6657 			}
6658 			if ((dcl->flags & ZEND_FFI_DCL_STORAGE_CLASS) == 0 ||
6659 			    (dcl->flags & ZEND_FFI_DCL_STORAGE_CLASS) == ZEND_FFI_DCL_EXTERN) {
6660 				sym = pemalloc(sizeof(zend_ffi_symbol), FFI_G(persistent));
6661 				sym->kind = (type->kind == ZEND_FFI_TYPE_FUNC) ? ZEND_FFI_SYM_FUNC : ZEND_FFI_SYM_VAR;
6662 				sym->type = dcl->type;
6663 				sym->is_const = (bool)(dcl->attr & ZEND_FFI_ATTR_CONST);
6664 				dcl->type = type; /* reset "owned" flag */
6665 				zend_hash_str_add_new_ptr(FFI_G(symbols), name, name_len, sym);
6666 			} else {
6667 				/* useless declaration */
6668 				zend_ffi_type_dtor(dcl->type);
6669 			}
6670 		}
6671 	}
6672 }
6673 /* }}} */
6674 
6675 void zend_ffi_declare_tag(const char *name, size_t name_len, zend_ffi_dcl *dcl, bool incomplete) /* {{{ */
6676 {
6677 	zend_ffi_tag *tag;
6678 	zend_ffi_type *type;
6679 
6680 	if (!FFI_G(tags)) {
6681 		FFI_G(tags) = pemalloc(sizeof(HashTable), FFI_G(persistent));
6682 		zend_hash_init(FFI_G(tags), 0, NULL, FFI_G(persistent) ? zend_ffi_tag_hash_persistent_dtor : zend_ffi_tag_hash_dtor, FFI_G(persistent));
6683 	}
6684 	tag = zend_hash_str_find_ptr(FFI_G(tags), name, name_len);
6685 	if (tag) {
6686 		zend_ffi_type *type = ZEND_FFI_TYPE(tag->type);
6687 
6688 		if (dcl->flags & ZEND_FFI_DCL_STRUCT) {
6689 			if (tag->kind != ZEND_FFI_TAG_STRUCT) {
6690 				zend_ffi_parser_error("\"%.*s\" defined as wrong kind of tag at line %d", name_len, name, FFI_G(line));
6691 				return;
6692 			} else if (!incomplete && !(type->attr & ZEND_FFI_ATTR_INCOMPLETE_TAG)) {
6693 				zend_ffi_parser_error("Redefinition of \"struct %.*s\" at line %d", name_len, name, FFI_G(line));
6694 				return;
6695 			}
6696 		} else if (dcl->flags & ZEND_FFI_DCL_UNION) {
6697 			if (tag->kind != ZEND_FFI_TAG_UNION) {
6698 				zend_ffi_parser_error("\"%.*s\" defined as wrong kind of tag at line %d", name_len, name, FFI_G(line));
6699 				return;
6700 			} else if (!incomplete && !(type->attr & ZEND_FFI_ATTR_INCOMPLETE_TAG)) {
6701 				zend_ffi_parser_error("Redefinition of \"union %.*s\" at line %d", name_len, name, FFI_G(line));
6702 				return;
6703 			}
6704 		} else if (dcl->flags & ZEND_FFI_DCL_ENUM) {
6705 			if (tag->kind != ZEND_FFI_TAG_ENUM) {
6706 				zend_ffi_parser_error("\"%.*s\" defined as wrong kind of tag at line %d", name_len, name, FFI_G(line));
6707 				return;
6708 			} else if (!incomplete && !(type->attr & ZEND_FFI_ATTR_INCOMPLETE_TAG)) {
6709 				zend_ffi_parser_error("Redefinition of \"enum %.*s\" at line %d", name_len, name, FFI_G(line));
6710 				return;
6711 			}
6712 		} else {
6713 			ZEND_UNREACHABLE();
6714 			return;
6715 		}
6716 		dcl->type = type;
6717 		if (!incomplete) {
6718 			type->attr &= ~ZEND_FFI_ATTR_INCOMPLETE_TAG;
6719 		}
6720 	} else {
6721 		zend_ffi_tag *tag = pemalloc(sizeof(zend_ffi_tag), FFI_G(persistent));
6722 		zend_string *tag_name = zend_string_init(name, name_len, FFI_G(persistent));
6723 
6724 		if (dcl->flags & ZEND_FFI_DCL_STRUCT) {
6725 			tag->kind = ZEND_FFI_TAG_STRUCT;
6726 			zend_ffi_make_struct_type(dcl);
6727 			type = ZEND_FFI_TYPE(dcl->type);
6728 			type->record.tag_name = zend_string_copy(tag_name);
6729 		} else if (dcl->flags & ZEND_FFI_DCL_UNION) {
6730 			tag->kind = ZEND_FFI_TAG_UNION;
6731 			zend_ffi_make_struct_type(dcl);
6732 			type = ZEND_FFI_TYPE(dcl->type);
6733 			type->record.tag_name = zend_string_copy(tag_name);
6734 		} else if (dcl->flags & ZEND_FFI_DCL_ENUM) {
6735 			tag->kind = ZEND_FFI_TAG_ENUM;
6736 			zend_ffi_make_enum_type(dcl);
6737 			type = ZEND_FFI_TYPE(dcl->type);
6738 			type->enumeration.tag_name = zend_string_copy(tag_name);
6739 		} else {
6740 			ZEND_UNREACHABLE();
6741 		}
6742 		tag->type = ZEND_FFI_TYPE_MAKE_OWNED(dcl->type);
6743 		dcl->type = ZEND_FFI_TYPE(dcl->type);
6744 		if (incomplete) {
6745 			dcl->type->attr |= ZEND_FFI_ATTR_INCOMPLETE_TAG;
6746 		}
6747 		zend_hash_add_new_ptr(FFI_G(tags), tag_name, tag);
6748 		zend_string_release(tag_name);
6749 	}
6750 }
6751 /* }}} */
6752 
6753 void zend_ffi_set_abi(zend_ffi_dcl *dcl, uint16_t abi) /* {{{ */
6754 {
6755 	if (dcl->abi != ZEND_FFI_ABI_DEFAULT) {
6756 		zend_ffi_parser_error("Multiple calling convention specifiers at line %d", FFI_G(line));
6757 	} else {
6758 		dcl->abi = abi;
6759 	}
6760 }
6761 /* }}} */
6762 
6763 #define SIMPLE_ATTRIBUTES(_) \
6764 	_(cdecl) \
6765 	_(fastcall) \
6766 	_(thiscall) \
6767 	_(stdcall) \
6768 	_(ms_abi) \
6769 	_(sysv_abi) \
6770 	_(vectorcall) \
6771 	_(aligned) \
6772 	_(packed) \
6773 	_(ms_struct) \
6774 	_(gcc_struct) \
6775 	_(const) \
6776 	_(malloc) \
6777 	_(deprecated) \
6778 	_(nothrow) \
6779 	_(leaf) \
6780 	_(pure) \
6781 	_(noreturn) \
6782 	_(warn_unused_result)
6783 
6784 #define ATTR_ID(name)   attr_ ## name,
6785 #define ATTR_NAME(name) {sizeof(#name)-1, #name},
6786 
6787 void zend_ffi_add_attribute(zend_ffi_dcl *dcl, const char *name, size_t name_len) /* {{{ */
6788 {
6789 	enum {
6790 		SIMPLE_ATTRIBUTES(ATTR_ID)
6791 		attr_unsupported
6792 	};
6793 	static const struct {
6794 		size_t len;
6795 		const char * const name;
6796 	} names[] = {
6797 		SIMPLE_ATTRIBUTES(ATTR_NAME)
6798 		{0, NULL}
6799 	};
6800 	int id;
6801 
6802 	if (name_len > 4
6803 	 && name[0] == '_'
6804 	 && name[1] == '_'
6805 	 && name[name_len-2] == '_'
6806 	 && name[name_len-1] == '_') {
6807 		name += 2;
6808 		name_len -= 4;
6809 	}
6810 	for (id = 0; names[id].len != 0; id++) {
6811 		if (name_len == names[id].len) {
6812 			if (memcmp(name, names[id].name, name_len) == 0) {
6813 				break;
6814 			}
6815 		}
6816 	}
6817 	switch (id) {
6818 		case attr_cdecl:
6819 			zend_ffi_set_abi(dcl, ZEND_FFI_ABI_CDECL);
6820 			break;
6821 		case attr_fastcall:
6822 			zend_ffi_set_abi(dcl, ZEND_FFI_ABI_FASTCALL);
6823 			break;
6824 		case attr_thiscall:
6825 			zend_ffi_set_abi(dcl, ZEND_FFI_ABI_THISCALL);
6826 			break;
6827 		case attr_stdcall:
6828 			zend_ffi_set_abi(dcl, ZEND_FFI_ABI_STDCALL);
6829 			break;
6830 		case attr_ms_abi:
6831 			zend_ffi_set_abi(dcl, ZEND_FFI_ABI_MS);
6832 			break;
6833 		case attr_sysv_abi:
6834 			zend_ffi_set_abi(dcl, ZEND_FFI_ABI_SYSV);
6835 			break;
6836 		case attr_vectorcall:
6837 			zend_ffi_set_abi(dcl, ZEND_FFI_ABI_VECTORCALL);
6838 			break;
6839 		case attr_aligned:
6840 			dcl->align = __BIGGEST_ALIGNMENT__;
6841 			break;
6842 		case attr_packed:
6843 			dcl->attr |= ZEND_FFI_ATTR_PACKED;
6844 			break;
6845 		case attr_ms_struct:
6846 			dcl->attr |= ZEND_FFI_ATTR_MS_STRUCT;
6847 			break;
6848 		case attr_gcc_struct:
6849 			dcl->attr |= ZEND_FFI_ATTR_GCC_STRUCT;
6850 			break;
6851 		case attr_unsupported:
6852 			zend_ffi_parser_error("Unsupported attribute \"%.*s\" at line %d", name_len, name, FFI_G(line));
6853 			break;
6854 		default:
6855 			/* ignore */
6856 			break;
6857 	}
6858 }
6859 /* }}} */
6860 
6861 #define VALUE_ATTRIBUTES(_) \
6862 	_(regparam) \
6863 	_(aligned) \
6864 	_(mode) \
6865 	_(nonnull) \
6866 	_(alloc_size) \
6867 	_(format) \
6868 	_(deprecated)
6869 
6870 void zend_ffi_add_attribute_value(zend_ffi_dcl *dcl, const char *name, size_t name_len, int n, zend_ffi_val *val) /* {{{ */
6871 {
6872 	enum {
6873 		VALUE_ATTRIBUTES(ATTR_ID)
6874 		attr_unsupported
6875 	};
6876 	static const struct {
6877 		size_t len;
6878 		const char * const name;
6879 	} names[] = {
6880 		VALUE_ATTRIBUTES(ATTR_NAME)
6881 		{0, NULL}
6882 	};
6883 	int id;
6884 
6885 	if (name_len > 4
6886 	 && name[0] == '_'
6887 	 && name[1] == '_'
6888 	 && name[name_len-2] == '_'
6889 	 && name[name_len-1] == '_') {
6890 		name += 2;
6891 		name_len -= 4;
6892 	}
6893 	for (id = 0; names[id].len != 0; id++) {
6894 		if (name_len == names[id].len) {
6895 			if (memcmp(name, names[id].name, name_len) == 0) {
6896 				break;
6897 			}
6898 		}
6899 	}
6900 	switch (id) {
6901 		case attr_regparam:
6902 			if (n == 0
6903 			 && (val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_INT64 || val->kind == ZEND_FFI_VAL_UINT64)
6904 			 && val->i64 == 3) {
6905 				zend_ffi_set_abi(dcl, ZEND_FFI_ABI_REGISTER);
6906 			} else {
6907 				zend_ffi_parser_error("Incorrect \"regparam\" value at line %d", FFI_G(line));
6908 			}
6909 			break;
6910 		case attr_aligned:
6911 			if (n == 0
6912 			 && (val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_INT64 || val->kind == ZEND_FFI_VAL_UINT64)
6913 			 && val->i64 > 0 && val->i64 <= 0x80000000 && (val->i64 & (val->i64 - 1)) == 0) {
6914 				dcl->align = val->i64;
6915 			} else {
6916 				zend_ffi_parser_error("Incorrect \"alignment\" value at line %d", FFI_G(line));
6917 			}
6918 			break;
6919 		case attr_mode:
6920 			if (n == 0
6921 			 && (val->kind == ZEND_FFI_VAL_NAME)) {
6922 				const char *str = val->str;
6923 				size_t len = val->len;
6924 				if (len > 4
6925 				 && str[0] == '_'
6926 				 && str[1] == '_'
6927 				 && str[len-2] == '_'
6928 				 && str[len-1] == '_') {
6929 					str += 2;
6930 					len -= 4;
6931 				}
6932 				// TODO: Add support for vector type 'VnXX' ???
6933 				if (len == 2) {
6934 					if (str[1] == 'I') {
6935 						if (dcl->flags & (ZEND_FFI_DCL_TYPE_SPECIFIERS-(ZEND_FFI_DCL_CHAR|ZEND_FFI_DCL_SHORT|ZEND_FFI_DCL_INT|ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_LONG_LONG|ZEND_FFI_DCL_SIGNED|ZEND_FFI_DCL_UNSIGNED))) {
6936 							/* inappropriate type */
6937 						} else if (str[0] == 'Q') {
6938 							dcl->flags &= ~(ZEND_FFI_DCL_CHAR|ZEND_FFI_DCL_SHORT|ZEND_FFI_DCL_INT|ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_LONG_LONG);
6939 							dcl->flags |= ZEND_FFI_DCL_CHAR;
6940 							break;
6941 						} else if (str[0] == 'H') {
6942 							dcl->flags &= ~(ZEND_FFI_DCL_CHAR|ZEND_FFI_DCL_SHORT|ZEND_FFI_DCL_INT|ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_LONG_LONG);
6943 							dcl->flags |= ZEND_FFI_DCL_SHORT;
6944 							break;
6945 						} else if (str[0] == 'S') {
6946 							dcl->flags &= ~(ZEND_FFI_DCL_CHAR|ZEND_FFI_DCL_SHORT|ZEND_FFI_DCL_INT|ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_LONG_LONG);
6947 							dcl->flags |= ZEND_FFI_DCL_INT;
6948 							break;
6949 						} else if (str[0] == 'D') {
6950 							dcl->flags &= ~(ZEND_FFI_DCL_CHAR|ZEND_FFI_DCL_SHORT|ZEND_FFI_DCL_INT|ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_LONG_LONG);
6951 							if (sizeof(long) == 8) {
6952 								dcl->flags |= ZEND_FFI_DCL_LONG;
6953 							} else {
6954 								dcl->flags |= ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_LONG_LONG;
6955 							}
6956 							break;
6957 						}
6958 					} else if (str[1] == 'F') {
6959 						if (dcl->flags & (ZEND_FFI_DCL_TYPE_SPECIFIERS-(ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_FLOAT|ZEND_FFI_DCL_DOUBLE))) {
6960 							/* inappropriate type */
6961 						} else if (str[0] == 'S') {
6962 							dcl->flags &= ~(ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_FLOAT|ZEND_FFI_DCL_DOUBLE);
6963 							dcl->flags |= ZEND_FFI_DCL_FLOAT;
6964 							break;
6965 						} else if (str[0] == 'D') {
6966 							dcl->flags &= ~(ZEND_FFI_DCL_LONG|ZEND_FFI_DCL_FLOAT|ZEND_FFI_DCL_DOUBLE);
6967 							dcl->flags |= ZEND_FFI_DCL_DOUBLE;
6968 							break;
6969 						}
6970 					}
6971 				}
6972 			}
6973 			zend_ffi_parser_error("Unsupported \"mode\" value at line %d", FFI_G(line));
6974 			// TODO: ???
6975 		case attr_unsupported:
6976 			zend_ffi_parser_error("Unsupported attribute \"%.*s\" at line %d", name_len, name, FFI_G(line));
6977 			break;
6978 		default:
6979 			/* ignore */
6980 			break;
6981 	}
6982 }
6983 /* }}} */
6984 
6985 void zend_ffi_add_msvc_attribute_value(zend_ffi_dcl *dcl, const char *name, size_t name_len, zend_ffi_val *val) /* {{{ */
6986 {
6987 	if (name_len == sizeof("align")-1 && memcmp(name, "align", sizeof("align")-1) == 0) {
6988 		if ((val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_INT64 || val->kind == ZEND_FFI_VAL_UINT64)
6989 		 && val->i64 > 0 && val->i64 <= 0x80000000 && (val->i64 & (val->i64 - 1)) == 0) {
6990 			dcl->align = val->i64;
6991 		} else {
6992 			zend_ffi_parser_error("Incorrect \"alignment\" value at line %d", FFI_G(line));
6993 		}
6994 	} else {
6995 		/* ignore */
6996 	}
6997 }
6998 /* }}} */
6999 
7000 static zend_result zend_ffi_nested_type(zend_ffi_type *type, zend_ffi_type *nested_type) /* {{{ */
7001 {
7002 	nested_type = ZEND_FFI_TYPE(nested_type);
7003 	switch (nested_type->kind) {
7004 		case ZEND_FFI_TYPE_POINTER:
7005 			/* "char" is used as a terminator of nested declaration */
7006 			if (nested_type->pointer.type == &zend_ffi_type_char) {
7007 				nested_type->pointer.type = type;
7008 				return zend_ffi_validate_vla(ZEND_FFI_TYPE(type));
7009 			} else {
7010 				return zend_ffi_nested_type(type, nested_type->pointer.type);
7011 			}
7012 			break;
7013 		case ZEND_FFI_TYPE_ARRAY:
7014 			/* "char" is used as a terminator of nested declaration */
7015 			if (nested_type->array.type == &zend_ffi_type_char) {
7016 				nested_type->array.type = type;
7017 				if (zend_ffi_validate_array_element_type(ZEND_FFI_TYPE(type)) == FAILURE) {
7018 					return FAILURE;
7019 				}
7020 			} else {
7021 				if (zend_ffi_nested_type(type, nested_type->array.type) != SUCCESS) {
7022 					return FAILURE;
7023 				}
7024 			}
7025 			nested_type->size = nested_type->array.length * ZEND_FFI_TYPE(nested_type->array.type)->size;
7026 			nested_type->align = ZEND_FFI_TYPE(nested_type->array.type)->align;
7027 			return SUCCESS;
7028 			break;
7029 		case ZEND_FFI_TYPE_FUNC:
7030 			/* "char" is used as a terminator of nested declaration */
7031 			if (nested_type->func.ret_type == &zend_ffi_type_char) {
7032 				nested_type->func.ret_type = type;
7033 				return zend_ffi_validate_func_ret_type(ZEND_FFI_TYPE(type));
7034 			} else {
7035 				return zend_ffi_nested_type(type, nested_type->func.ret_type);
7036 			}
7037 			break;
7038 		default:
7039 			ZEND_UNREACHABLE();
7040 	}
7041 }
7042 /* }}} */
7043 
7044 void zend_ffi_nested_declaration(zend_ffi_dcl *dcl, zend_ffi_dcl *nested_dcl) /* {{{ */
7045 {
7046 	/* "char" is used as a terminator of nested declaration */
7047 	zend_ffi_finalize_type(dcl);
7048 	if (!nested_dcl->type || nested_dcl->type == &zend_ffi_type_char) {
7049 		nested_dcl->type = dcl->type;
7050 	} else {
7051 		if (zend_ffi_nested_type(dcl->type, nested_dcl->type) == FAILURE) {
7052 			zend_ffi_cleanup_dcl(nested_dcl);
7053 			LONGJMP(FFI_G(bailout), FAILURE);
7054 		}
7055 	}
7056 	dcl->type = nested_dcl->type;
7057 }
7058 /* }}} */
7059 
7060 void zend_ffi_align_as_type(zend_ffi_dcl *dcl, zend_ffi_dcl *align_dcl) /* {{{ */
7061 {
7062 	zend_ffi_finalize_type(align_dcl);
7063 	dcl->align = MAX(align_dcl->align, ZEND_FFI_TYPE(align_dcl->type)->align);
7064 }
7065 /* }}} */
7066 
7067 void zend_ffi_align_as_val(zend_ffi_dcl *dcl, zend_ffi_val *align_val) /* {{{ */
7068 {
7069 	switch (align_val->kind) {
7070 		case ZEND_FFI_VAL_INT32:
7071 		case ZEND_FFI_VAL_UINT32:
7072 			dcl->align = zend_ffi_type_uint32.align;
7073 			break;
7074 		case ZEND_FFI_VAL_INT64:
7075 		case ZEND_FFI_VAL_UINT64:
7076 			dcl->align = zend_ffi_type_uint64.align;
7077 			break;
7078 		case ZEND_FFI_VAL_FLOAT:
7079 			dcl->align = zend_ffi_type_float.align;
7080 			break;
7081 		case ZEND_FFI_VAL_DOUBLE:
7082 			dcl->align = zend_ffi_type_double.align;
7083 			break;
7084 #ifdef HAVE_LONG_DOUBLE
7085 		case ZEND_FFI_VAL_LONG_DOUBLE:
7086 			dcl->align = zend_ffi_type_long_double.align;
7087 			break;
7088 #endif
7089 		case ZEND_FFI_VAL_CHAR:
7090 		case ZEND_FFI_VAL_STRING:
7091 			dcl->align = zend_ffi_type_char.align;
7092 			break;
7093 		default:
7094 			break;
7095 	}
7096 }
7097 /* }}} */
7098 
7099 #define zend_ffi_expr_bool(val) do { \
7100 	if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_UINT64) { \
7101 		val->kind = ZEND_FFI_VAL_INT32; \
7102 		val->i64 = !!val->u64; \
7103 	} else if (val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_INT64) { \
7104 		val->kind = ZEND_FFI_VAL_INT32; \
7105 		val->i64 = !!val->i64; \
7106 	} else if (val->kind == ZEND_FFI_VAL_FLOAT || val->kind == ZEND_FFI_VAL_DOUBLE || val->kind == ZEND_FFI_VAL_LONG_DOUBLE) { \
7107 		val->kind = ZEND_FFI_VAL_INT32; \
7108 		val->i64 = !!val->d; \
7109 	} else if (val->kind == ZEND_FFI_VAL_CHAR) { \
7110 		val->kind = ZEND_FFI_VAL_INT32; \
7111 		val->i64 = !!val->ch; \
7112 	} else { \
7113 		val->kind = ZEND_FFI_VAL_ERROR; \
7114 	} \
7115 } while (0)
7116 
7117 #define zend_ffi_expr_math(val, op2, OP) do { \
7118 	if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_UINT64) { \
7119 		if (op2->kind == ZEND_FFI_VAL_UINT32 || op2->kind == ZEND_FFI_VAL_UINT64) { \
7120 			val->kind = MAX(val->kind, op2->kind); \
7121 			val->u64 = val->u64 OP op2->u64; \
7122 		} else if (op2->kind == ZEND_FFI_VAL_INT32) { \
7123 			val->u64 = val->u64 OP op2->i64; \
7124 		} else if (op2->kind == ZEND_FFI_VAL_INT64) { \
7125 			val->u64 = val->u64 OP op2->i64; \
7126 		} else if (op2->kind == ZEND_FFI_VAL_FLOAT || op2->kind == ZEND_FFI_VAL_DOUBLE || op2->kind == ZEND_FFI_VAL_LONG_DOUBLE) { \
7127 			val->kind = op2->kind; \
7128 			val->d = (zend_ffi_double)val->u64 OP op2->d; \
7129 		} else if (op2->kind == ZEND_FFI_VAL_CHAR) { \
7130 			val->u64 = val->u64 OP op2->ch; \
7131 		} else { \
7132 			val->kind = ZEND_FFI_VAL_ERROR; \
7133 		} \
7134 	} else if (val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_INT64) { \
7135 		if (op2->kind == ZEND_FFI_VAL_UINT32) { \
7136 			val->i64 = val->i64 OP op2->u64; \
7137 		} else if (op2->kind == ZEND_FFI_VAL_UINT64) { \
7138 			val->i64 = val->i64 OP op2->u64; \
7139 		} else if (op2->kind == ZEND_FFI_VAL_INT32 || op2->kind == ZEND_FFI_VAL_INT64) { \
7140 			val->kind = MAX(val->kind, op2->kind); \
7141 			val->i64 = val->i64 OP op2->i64; \
7142 		} else if (op2->kind == ZEND_FFI_VAL_FLOAT || op2->kind == ZEND_FFI_VAL_DOUBLE || op2->kind == ZEND_FFI_VAL_LONG_DOUBLE) { \
7143 			val->kind = op2->kind; \
7144 			val->d = (zend_ffi_double)val->i64 OP op2->d; \
7145 		} else if (op2->kind == ZEND_FFI_VAL_CHAR) { \
7146 			val->i64 = val->i64 OP op2->ch; \
7147 		} else { \
7148 			val->kind = ZEND_FFI_VAL_ERROR; \
7149 		} \
7150 	} else if (val->kind == ZEND_FFI_VAL_FLOAT || val->kind == ZEND_FFI_VAL_DOUBLE || val->kind == ZEND_FFI_VAL_LONG_DOUBLE) { \
7151 		if (op2->kind == ZEND_FFI_VAL_UINT32 || op2->kind == ZEND_FFI_VAL_UINT64) { \
7152 			val->d = val->d OP (zend_ffi_double)op2->u64; \
7153 		} else if (op2->kind == ZEND_FFI_VAL_INT32 ||op2->kind == ZEND_FFI_VAL_INT64) { \
7154 			val->d = val->d OP (zend_ffi_double)op2->i64; \
7155 		} else if (op2->kind == ZEND_FFI_VAL_FLOAT || op2->kind == ZEND_FFI_VAL_DOUBLE || op2->kind == ZEND_FFI_VAL_LONG_DOUBLE) { \
7156 			val->kind = MAX(val->kind, op2->kind); \
7157 			val->d = val->d OP op2->d; \
7158 		} else if (op2->kind == ZEND_FFI_VAL_CHAR) { \
7159 			val->d = val->d OP (zend_ffi_double)op2->ch; \
7160 		} else { \
7161 			val->kind = ZEND_FFI_VAL_ERROR; \
7162 		} \
7163 	} else if (val->kind == ZEND_FFI_VAL_CHAR) { \
7164 		if (op2->kind == ZEND_FFI_VAL_UINT32 || op2->kind == ZEND_FFI_VAL_UINT64) { \
7165 			val->kind = op2->kind; \
7166 			val->u64 = val->ch OP op2->u64; \
7167 		} else if (op2->kind == ZEND_FFI_VAL_INT32 || op2->kind == ZEND_FFI_VAL_INT64) { \
7168 			val->kind = ZEND_FFI_VAL_INT64; \
7169 			val->i64 = val->ch OP op2->i64; \
7170 		} else if (op2->kind == ZEND_FFI_VAL_FLOAT || op2->kind == ZEND_FFI_VAL_DOUBLE || op2->kind == ZEND_FFI_VAL_LONG_DOUBLE) { \
7171 			val->kind = op2->kind; \
7172 			val->d = (zend_ffi_double)val->ch OP op2->d; \
7173 		} else if (op2->kind == ZEND_FFI_VAL_CHAR) { \
7174 			val->ch = val->ch OP op2->ch; \
7175 		} else { \
7176 			val->kind = ZEND_FFI_VAL_ERROR; \
7177 		} \
7178 	} else { \
7179 		val->kind = ZEND_FFI_VAL_ERROR; \
7180 	} \
7181 } while (0)
7182 
7183 #define zend_ffi_expr_int_math(val, op2, OP) do { \
7184 	if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_UINT64) { \
7185 		if (op2->kind == ZEND_FFI_VAL_UINT32 || op2->kind == ZEND_FFI_VAL_UINT64) { \
7186 			val->kind = MAX(val->kind, op2->kind); \
7187 			val->u64 = val->u64 OP op2->u64; \
7188 		} else if (op2->kind == ZEND_FFI_VAL_INT32) { \
7189 			val->u64 = val->u64 OP op2->i64; \
7190 		} else if (op2->kind == ZEND_FFI_VAL_INT64) { \
7191 			val->u64 = val->u64 OP op2->i64; \
7192 		} else if (op2->kind == ZEND_FFI_VAL_FLOAT || op2->kind == ZEND_FFI_VAL_DOUBLE || op2->kind == ZEND_FFI_VAL_LONG_DOUBLE) { \
7193 			val->u64 = val->u64 OP (uint64_t)op2->d; \
7194 		} else if (op2->kind == ZEND_FFI_VAL_CHAR) { \
7195 			val->u64 = val->u64 OP op2->ch; \
7196 		} else { \
7197 			val->kind = ZEND_FFI_VAL_ERROR; \
7198 		} \
7199 	} else if (val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_INT64) { \
7200 		if (op2->kind == ZEND_FFI_VAL_UINT32) { \
7201 			val->i64 = val->i64 OP op2->u64; \
7202 		} else if (op2->kind == ZEND_FFI_VAL_UINT64) { \
7203 			val->i64 = val->i64 OP op2->u64; \
7204 		} else if (op2->kind == ZEND_FFI_VAL_INT32 || op2->kind == ZEND_FFI_VAL_INT64) { \
7205 			val->kind = MAX(val->kind, op2->kind); \
7206 			val->i64 = val->i64 OP op2->i64; \
7207 		} else if (op2->kind == ZEND_FFI_VAL_FLOAT || op2->kind == ZEND_FFI_VAL_DOUBLE || op2->kind == ZEND_FFI_VAL_LONG_DOUBLE) { \
7208 			val->u64 = val->u64 OP (int64_t)op2->d; \
7209 		} else if (op2->kind == ZEND_FFI_VAL_CHAR) { \
7210 			val->i64 = val->i64 OP op2->ch; \
7211 		} else { \
7212 			val->kind = ZEND_FFI_VAL_ERROR; \
7213 		} \
7214 	} else if (val->kind == ZEND_FFI_VAL_FLOAT || val->kind == ZEND_FFI_VAL_DOUBLE || val->kind == ZEND_FFI_VAL_LONG_DOUBLE) { \
7215 		if (op2->kind == ZEND_FFI_VAL_UINT32 || op2->kind == ZEND_FFI_VAL_UINT64) { \
7216 			val->kind = op2->kind; \
7217 			val->u64 = (uint64_t)val->d OP op2->u64; \
7218 		} else if (op2->kind == ZEND_FFI_VAL_INT32 || op2->kind == ZEND_FFI_VAL_INT64) { \
7219 			val->kind = op2->kind; \
7220 			val->i64 = (int64_t)val->d OP op2->i64; \
7221 		} else { \
7222 			val->kind = ZEND_FFI_VAL_ERROR; \
7223 		} \
7224 	} else if (val->kind == ZEND_FFI_VAL_CHAR) { \
7225 		if (op2->kind == ZEND_FFI_VAL_UINT32 || op2->kind == ZEND_FFI_VAL_UINT64) { \
7226 			val->kind = op2->kind; \
7227 			val->u64 = (uint64_t)val->ch OP op2->u64; \
7228 		} else if (op2->kind == ZEND_FFI_VAL_INT32 || op2->kind == ZEND_FFI_VAL_INT64) { \
7229 			val->kind = op2->kind; \
7230 			val->i64 = (int64_t)val->ch OP op2->u64; \
7231 		} else if (op2->kind == ZEND_FFI_VAL_CHAR) { \
7232 			val->ch = val->ch OP op2->ch; \
7233 		} else { \
7234 			val->kind = ZEND_FFI_VAL_ERROR; \
7235 		} \
7236 	} else { \
7237 		val->kind = ZEND_FFI_VAL_ERROR; \
7238 	} \
7239 } while (0)
7240 
7241 #define zend_ffi_expr_cmp(val, op2, OP) do { \
7242 	if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_UINT64) { \
7243 		if (op2->kind == ZEND_FFI_VAL_UINT32 || op2->kind == ZEND_FFI_VAL_UINT64) { \
7244 			val->kind = ZEND_FFI_VAL_INT32; \
7245 			val->i64 = val->u64 OP op2->u64; \
7246 		} else if (op2->kind == ZEND_FFI_VAL_INT32 || op2->kind == ZEND_FFI_VAL_INT64) { \
7247 			val->kind = ZEND_FFI_VAL_INT32; \
7248 			val->i64 = val->u64 OP op2->u64; /*signed/unsigned */ \
7249 		} else if (op2->kind == ZEND_FFI_VAL_FLOAT || op2->kind == ZEND_FFI_VAL_DOUBLE || op2->kind == ZEND_FFI_VAL_LONG_DOUBLE) { \
7250 			val->kind = ZEND_FFI_VAL_INT32; \
7251 			val->i64 = (zend_ffi_double)val->u64 OP op2->d; \
7252 		} else if (op2->kind == ZEND_FFI_VAL_CHAR) { \
7253 			val->kind = ZEND_FFI_VAL_INT32; \
7254 			val->i64 = val->u64 OP op2->d; \
7255 		} else { \
7256 			val->kind = ZEND_FFI_VAL_ERROR; \
7257 		} \
7258 	} else if (val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_INT64) { \
7259 		if (op2->kind == ZEND_FFI_VAL_UINT32 || op2->kind == ZEND_FFI_VAL_UINT64) { \
7260 			val->kind = ZEND_FFI_VAL_INT32; \
7261 			val->i64 = val->i64 OP op2->i64; /* signed/unsigned */ \
7262 		} else if (op2->kind == ZEND_FFI_VAL_INT32 || op2->kind == ZEND_FFI_VAL_INT64) { \
7263 			val->kind = ZEND_FFI_VAL_INT32; \
7264 			val->i64 = val->i64 OP op2->i64; \
7265 		} else if (op2->kind == ZEND_FFI_VAL_FLOAT || op2->kind == ZEND_FFI_VAL_DOUBLE || op2->kind == ZEND_FFI_VAL_LONG_DOUBLE) { \
7266 			val->kind = ZEND_FFI_VAL_INT32; \
7267 			val->i64 = (zend_ffi_double)val->i64 OP op2->d; \
7268 		} else if (op2->kind == ZEND_FFI_VAL_CHAR) { \
7269 			val->kind = ZEND_FFI_VAL_INT32; \
7270 			val->i64 = val->i64 OP op2->ch; \
7271 		} else { \
7272 			val->kind = ZEND_FFI_VAL_ERROR; \
7273 		} \
7274 	} else if (val->kind == ZEND_FFI_VAL_FLOAT || val->kind == ZEND_FFI_VAL_DOUBLE || val->kind == ZEND_FFI_VAL_LONG_DOUBLE) { \
7275 		if (op2->kind == ZEND_FFI_VAL_UINT32 || op2->kind == ZEND_FFI_VAL_UINT64) { \
7276 			val->kind = ZEND_FFI_VAL_INT32; \
7277 			val->i64 = val->d OP (zend_ffi_double)op2->u64; \
7278 		} else if (op2->kind == ZEND_FFI_VAL_INT32 ||op2->kind == ZEND_FFI_VAL_INT64) { \
7279 			val->kind = ZEND_FFI_VAL_INT32; \
7280 			val->i64 = val->d OP (zend_ffi_double)op2->i64; \
7281 		} else if (op2->kind == ZEND_FFI_VAL_FLOAT || op2->kind == ZEND_FFI_VAL_DOUBLE || op2->kind == ZEND_FFI_VAL_LONG_DOUBLE) { \
7282 			val->kind = ZEND_FFI_VAL_INT32; \
7283 			val->i64 = val->d OP op2->d; \
7284 		} else if (op2->kind == ZEND_FFI_VAL_CHAR) { \
7285 			val->kind = ZEND_FFI_VAL_INT32; \
7286 			val->i64 = val->d OP (zend_ffi_double)op2->ch; \
7287 		} else { \
7288 			val->kind = ZEND_FFI_VAL_ERROR; \
7289 		} \
7290 	} else if (val->kind == ZEND_FFI_VAL_CHAR) { \
7291 		if (op2->kind == ZEND_FFI_VAL_UINT32 || op2->kind == ZEND_FFI_VAL_UINT64) { \
7292 			val->kind = ZEND_FFI_VAL_INT32; \
7293 			val->i64 = val->ch OP op2->i64; /* signed/unsigned */ \
7294 		} else if (op2->kind == ZEND_FFI_VAL_INT32 || op2->kind == ZEND_FFI_VAL_INT64) { \
7295 			val->kind = ZEND_FFI_VAL_INT32; \
7296 			val->i64 = val->ch OP op2->i64; \
7297 		} else if (op2->kind == ZEND_FFI_VAL_FLOAT || op2->kind == ZEND_FFI_VAL_DOUBLE || op2->kind == ZEND_FFI_VAL_LONG_DOUBLE) { \
7298 			val->kind = ZEND_FFI_VAL_INT32; \
7299 			val->i64 = (zend_ffi_double)val->ch OP op2->d; \
7300 		} else if (op2->kind == ZEND_FFI_VAL_CHAR) { \
7301 			val->kind = ZEND_FFI_VAL_INT32; \
7302 			val->i64 = val->ch OP op2->ch; \
7303 		} else { \
7304 			val->kind = ZEND_FFI_VAL_ERROR; \
7305 		} \
7306 	} else { \
7307 		val->kind = ZEND_FFI_VAL_ERROR; \
7308 	} \
7309 } while (0)
7310 
7311 void zend_ffi_expr_conditional(zend_ffi_val *val, zend_ffi_val *op2, zend_ffi_val *op3) /* {{{ */
7312 {
7313 	zend_ffi_expr_bool(val);
7314 	if (val->kind == ZEND_FFI_VAL_INT32) {
7315 		if (val->i64) {
7316 			*val = *op2;
7317 		} else {
7318 			*val = *op3;
7319 		}
7320 	}
7321 }
7322 /* }}} */
7323 
7324 void zend_ffi_expr_bool_or(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7325 {
7326 	zend_ffi_expr_bool(val);
7327 	zend_ffi_expr_bool(op2);
7328 	if (val->kind == ZEND_FFI_VAL_INT32 && op2->kind == ZEND_FFI_VAL_INT32) {
7329 		val->i64 = val->i64 || op2->i64;
7330 	} else {
7331 		val->kind = ZEND_FFI_VAL_ERROR;
7332 	}
7333 }
7334 /* }}} */
7335 
7336 void zend_ffi_expr_bool_and(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7337 {
7338 	zend_ffi_expr_bool(val);
7339 	zend_ffi_expr_bool(op2);
7340 	if (val->kind == ZEND_FFI_VAL_INT32 && op2->kind == ZEND_FFI_VAL_INT32) {
7341 		val->i64 = val->i64 && op2->i64;
7342 	} else {
7343 		val->kind = ZEND_FFI_VAL_ERROR;
7344 	}
7345 }
7346 /* }}} */
7347 
7348 void zend_ffi_expr_bw_or(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7349 {
7350 	zend_ffi_expr_int_math(val, op2, |);
7351 }
7352 /* }}} */
7353 
7354 void zend_ffi_expr_bw_xor(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7355 {
7356 	zend_ffi_expr_int_math(val, op2, ^);
7357 }
7358 /* }}} */
7359 
7360 void zend_ffi_expr_bw_and(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7361 {
7362 	zend_ffi_expr_int_math(val, op2, &);
7363 }
7364 /* }}} */
7365 
7366 void zend_ffi_expr_is_equal(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7367 {
7368 	zend_ffi_expr_cmp(val, op2, ==);
7369 }
7370 /* }}} */
7371 
7372 void zend_ffi_expr_is_not_equal(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7373 {
7374 	zend_ffi_expr_cmp(val, op2, !=);
7375 }
7376 /* }}} */
7377 
7378 void zend_ffi_expr_is_less(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7379 {
7380 	zend_ffi_expr_cmp(val, op2, <);
7381 }
7382 /* }}} */
7383 
7384 void zend_ffi_expr_is_greater(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7385 {
7386 	zend_ffi_expr_cmp(val, op2, >);
7387 }
7388 /* }}} */
7389 
7390 void zend_ffi_expr_is_less_or_equal(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7391 {
7392 	zend_ffi_expr_cmp(val, op2, <=);
7393 }
7394 /* }}} */
7395 
7396 void zend_ffi_expr_is_greater_or_equal(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7397 {
7398 	zend_ffi_expr_cmp(val, op2, >=);
7399 }
7400 /* }}} */
7401 
7402 void zend_ffi_expr_shift_left(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7403 {
7404 	zend_ffi_expr_int_math(val, op2, <<);
7405 }
7406 /* }}} */
7407 
7408 void zend_ffi_expr_shift_right(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7409 {
7410 	zend_ffi_expr_int_math(val, op2, >>);
7411 }
7412 /* }}} */
7413 
7414 void zend_ffi_expr_add(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7415 {
7416 	zend_ffi_expr_math(val, op2, +);
7417 }
7418 /* }}} */
7419 
7420 void zend_ffi_expr_sub(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7421 {
7422 	zend_ffi_expr_math(val, op2, -);
7423 }
7424 /* }}} */
7425 
7426 void zend_ffi_expr_mul(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7427 {
7428 	zend_ffi_expr_math(val, op2, *);
7429 }
7430 /* }}} */
7431 
7432 void zend_ffi_expr_div(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7433 {
7434 	zend_ffi_expr_math(val, op2, /);
7435 }
7436 /* }}} */
7437 
7438 void zend_ffi_expr_mod(zend_ffi_val *val, zend_ffi_val *op2) /* {{{ */
7439 {
7440 	zend_ffi_expr_int_math(val, op2, %); // ???
7441 }
7442 /* }}} */
7443 
7444 void zend_ffi_expr_cast(zend_ffi_val *val, zend_ffi_dcl *dcl) /* {{{ */
7445 {
7446 	zend_ffi_finalize_type(dcl);
7447 	switch (ZEND_FFI_TYPE(dcl->type)->kind) {
7448 		case ZEND_FFI_TYPE_FLOAT:
7449 			if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_UINT64) {
7450 				val->kind = ZEND_FFI_VAL_FLOAT;
7451 				val->d = val->u64;
7452 			} else if (val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_INT64) {
7453 				val->kind = ZEND_FFI_VAL_FLOAT;
7454 				val->d = val->i64;
7455 			} else if (val->kind == ZEND_FFI_VAL_FLOAT || val->kind == ZEND_FFI_VAL_DOUBLE || val->kind == ZEND_FFI_VAL_LONG_DOUBLE) {
7456 				val->kind = ZEND_FFI_VAL_FLOAT;
7457 			} else if (val->kind == ZEND_FFI_VAL_CHAR) {
7458 				val->kind = ZEND_FFI_VAL_FLOAT;
7459 				val->d = val->ch;
7460 			} else {
7461 				val->kind = ZEND_FFI_VAL_ERROR;
7462 			}
7463 			break;
7464 		case ZEND_FFI_TYPE_DOUBLE:
7465 			if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_UINT64) {
7466 				val->kind = ZEND_FFI_VAL_DOUBLE;
7467 				val->d = val->u64;
7468 			} else if (val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_INT64) {
7469 				val->kind = ZEND_FFI_VAL_DOUBLE;
7470 				val->d = val->i64;
7471 			} else if (val->kind == ZEND_FFI_VAL_FLOAT || val->kind == ZEND_FFI_VAL_DOUBLE || val->kind == ZEND_FFI_VAL_LONG_DOUBLE) {
7472 				val->kind = ZEND_FFI_VAL_DOUBLE;
7473 			} else if (val->kind == ZEND_FFI_VAL_CHAR) {
7474 				val->kind = ZEND_FFI_VAL_DOUBLE;
7475 				val->d = val->ch;
7476 			} else {
7477 				val->kind = ZEND_FFI_VAL_ERROR;
7478 			}
7479 			break;
7480 #ifdef HAVE_LONG_DOUBLE
7481 		case ZEND_FFI_TYPE_LONGDOUBLE:
7482 			if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_UINT64) {
7483 				val->kind = ZEND_FFI_VAL_LONG_DOUBLE;
7484 				val->d = val->u64;
7485 			} else if (val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_INT64) {
7486 				val->kind = ZEND_FFI_VAL_LONG_DOUBLE;
7487 				val->d = val->i64;
7488 			} else if (val->kind == ZEND_FFI_VAL_FLOAT || val->kind == ZEND_FFI_VAL_DOUBLE || val->kind == ZEND_FFI_VAL_LONG_DOUBLE) {
7489 				val->kind = ZEND_FFI_VAL_LONG_DOUBLE;
7490 			} else if (val->kind == ZEND_FFI_VAL_CHAR) {
7491 				val->kind = ZEND_FFI_VAL_LONG_DOUBLE;
7492 				val->d = val->ch;
7493 			} else {
7494 				val->kind = ZEND_FFI_VAL_ERROR;
7495 			}
7496 			break;
7497 #endif
7498 		case ZEND_FFI_TYPE_UINT8:
7499 		case ZEND_FFI_TYPE_UINT16:
7500 		case ZEND_FFI_TYPE_UINT32:
7501 		case ZEND_FFI_TYPE_BOOL:
7502 			if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_UINT64 || val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_INT64) {
7503 				val->kind = ZEND_FFI_VAL_UINT32;
7504 			} else if (val->kind == ZEND_FFI_VAL_FLOAT || val->kind == ZEND_FFI_VAL_DOUBLE || val->kind == ZEND_FFI_VAL_LONG_DOUBLE) {
7505 				val->kind = ZEND_FFI_VAL_UINT32;
7506 				val->u64 = val->d;
7507 			} else if (val->kind == ZEND_FFI_VAL_CHAR) {
7508 				val->kind = ZEND_FFI_VAL_UINT32;
7509 				val->u64 = val->ch;
7510 			} else {
7511 				val->kind = ZEND_FFI_VAL_ERROR;
7512 			}
7513 			break;
7514 		case ZEND_FFI_TYPE_SINT8:
7515 		case ZEND_FFI_TYPE_SINT16:
7516 		case ZEND_FFI_TYPE_SINT32:
7517 			if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_UINT64 || val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_INT64) {
7518 				val->kind = ZEND_FFI_VAL_INT32;
7519 			} else if (val->kind == ZEND_FFI_VAL_FLOAT || val->kind == ZEND_FFI_VAL_DOUBLE || val->kind == ZEND_FFI_VAL_LONG_DOUBLE) {
7520 				val->kind = ZEND_FFI_VAL_INT32;
7521 				val->i64 = val->d;
7522 			} else if (val->kind == ZEND_FFI_VAL_CHAR) {
7523 				val->kind = ZEND_FFI_VAL_INT32;
7524 				val->i64 = val->ch;
7525 			} else {
7526 				val->kind = ZEND_FFI_VAL_ERROR;
7527 			}
7528 			break;
7529 		case ZEND_FFI_TYPE_UINT64:
7530 			if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_UINT64 || val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_INT64) {
7531 				val->kind = ZEND_FFI_VAL_UINT64;
7532 			} else if (val->kind == ZEND_FFI_VAL_FLOAT || val->kind == ZEND_FFI_VAL_DOUBLE || val->kind == ZEND_FFI_VAL_LONG_DOUBLE) {
7533 				val->kind = ZEND_FFI_VAL_UINT64;
7534 				val->u64 = val->d;
7535 			} else if (val->kind == ZEND_FFI_VAL_CHAR) {
7536 				val->kind = ZEND_FFI_VAL_UINT64;
7537 				val->u64 = val->ch;
7538 			} else {
7539 				val->kind = ZEND_FFI_VAL_ERROR;
7540 			}
7541 			break;
7542 		case ZEND_FFI_TYPE_SINT64:
7543 			if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_UINT64) {
7544 				val->kind = ZEND_FFI_VAL_CHAR;
7545 				val->ch = val->u64;
7546 			} else if (val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_INT64) {
7547 				val->kind = ZEND_FFI_VAL_CHAR;
7548 				val->ch = val->i64;
7549 			} else if (val->kind == ZEND_FFI_VAL_FLOAT || val->kind == ZEND_FFI_VAL_DOUBLE || val->kind == ZEND_FFI_VAL_LONG_DOUBLE) {
7550 				val->kind = ZEND_FFI_VAL_CHAR;
7551 				val->ch = val->d;
7552 			} else if (val->kind == ZEND_FFI_VAL_CHAR) {
7553 			} else {
7554 				val->kind = ZEND_FFI_VAL_ERROR;
7555 			}
7556 			break;
7557 		case ZEND_FFI_TYPE_CHAR:
7558 			if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_UINT64 || val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_INT64) {
7559 				val->kind = ZEND_FFI_VAL_UINT32;
7560 			} else if (val->kind == ZEND_FFI_VAL_FLOAT || val->kind == ZEND_FFI_VAL_DOUBLE || val->kind == ZEND_FFI_VAL_LONG_DOUBLE) {
7561 				val->kind = ZEND_FFI_VAL_UINT32;
7562 				val->u64 = val->d;
7563 			} else if (val->kind == ZEND_FFI_VAL_CHAR) {
7564 				val->kind = ZEND_FFI_VAL_UINT32;
7565 				val->u64 = val->ch;
7566 			} else {
7567 				val->kind = ZEND_FFI_VAL_ERROR;
7568 			}
7569 			break;
7570 		default:
7571 			val->kind = ZEND_FFI_VAL_ERROR;
7572 			break;
7573 	}
7574 	zend_ffi_type_dtor(dcl->type);
7575 }
7576 /* }}} */
7577 
7578 void zend_ffi_expr_plus(zend_ffi_val *val) /* {{{ */
7579 {
7580 	if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_UINT64) {
7581 	} else if (val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_INT64) {
7582 	} else if (val->kind == ZEND_FFI_VAL_FLOAT || val->kind == ZEND_FFI_VAL_DOUBLE || val->kind == ZEND_FFI_VAL_LONG_DOUBLE) {
7583 	} else if (val->kind == ZEND_FFI_VAL_CHAR) {
7584 	} else {
7585 		val->kind = ZEND_FFI_VAL_ERROR;
7586 	}
7587 }
7588 /* }}} */
7589 
7590 void zend_ffi_expr_neg(zend_ffi_val *val) /* {{{ */
7591 {
7592 	if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_UINT64) {
7593 		val->u64 = -val->u64;
7594 	} else if (val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_INT64) {
7595 		val->i64 = -val->i64;
7596 	} else if (val->kind == ZEND_FFI_VAL_FLOAT || val->kind == ZEND_FFI_VAL_DOUBLE || val->kind == ZEND_FFI_VAL_LONG_DOUBLE) {
7597 		val->d = -val->d;
7598 	} else if (val->kind == ZEND_FFI_VAL_CHAR) {
7599 		val->ch = -val->ch;
7600 	} else {
7601 		val->kind = ZEND_FFI_VAL_ERROR;
7602 	}
7603 }
7604 /* }}} */
7605 
7606 void zend_ffi_expr_bw_not(zend_ffi_val *val) /* {{{ */
7607 {
7608 	if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_UINT64) {
7609 		val->u64 = ~val->u64;
7610 	} else if (val->kind == ZEND_FFI_VAL_INT32 || val->kind == ZEND_FFI_VAL_INT64) {
7611 		val->i64 = ~val->i64;
7612 	} else if (val->kind == ZEND_FFI_VAL_CHAR) {
7613 		val->ch = ~val->ch;
7614 	} else {
7615 		val->kind = ZEND_FFI_VAL_ERROR;
7616 	}
7617 }
7618 /* }}} */
7619 
7620 void zend_ffi_expr_bool_not(zend_ffi_val *val) /* {{{ */
7621 {
7622 	zend_ffi_expr_bool(val);
7623 	if (val->kind == ZEND_FFI_VAL_INT32) {
7624 		val->i64 = !val->i64;
7625 	}
7626 }
7627 /* }}} */
7628 
7629 void zend_ffi_expr_sizeof_val(zend_ffi_val *val) /* {{{ */
7630 {
7631 	if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_INT32) {
7632 		val->kind = ZEND_FFI_VAL_UINT32;
7633 		val->u64 = zend_ffi_type_uint32.size;
7634 	} else if (val->kind == ZEND_FFI_VAL_UINT64 || val->kind == ZEND_FFI_VAL_INT64) {
7635 		val->kind = ZEND_FFI_VAL_UINT32;
7636 		val->u64 = zend_ffi_type_uint64.size;
7637 	} else if (val->kind == ZEND_FFI_VAL_FLOAT) {
7638 		val->kind = ZEND_FFI_VAL_UINT32;
7639 		val->u64 = zend_ffi_type_float.size;
7640 	} else if (val->kind == ZEND_FFI_VAL_DOUBLE) {
7641 		val->kind = ZEND_FFI_VAL_UINT32;
7642 		val->u64 = zend_ffi_type_double.size;
7643 	} else if (val->kind == ZEND_FFI_VAL_LONG_DOUBLE) {
7644 		val->kind = ZEND_FFI_VAL_UINT32;
7645 #ifdef _WIN32
7646 		val->u64 = zend_ffi_type_double.size;
7647 #else
7648 		val->u64 = zend_ffi_type_long_double.size;
7649 #endif
7650 	} else if (val->kind == ZEND_FFI_VAL_CHAR) {
7651 		val->kind = ZEND_FFI_VAL_UINT32;
7652 		val->u64 = zend_ffi_type_char.size;
7653 	} else if (val->kind == ZEND_FFI_VAL_STRING) {
7654 		if (memchr(val->str, '\\', val->len)) {
7655 			// TODO: support for escape sequences ???
7656 			val->kind = ZEND_FFI_VAL_ERROR;
7657 		} else {
7658 			val->kind = ZEND_FFI_VAL_UINT32;
7659 			val->u64 = val->len + 1;
7660 		}
7661 	} else {
7662 		val->kind = ZEND_FFI_VAL_ERROR;
7663 	}
7664 }
7665 /* }}} */
7666 
7667 void zend_ffi_expr_sizeof_type(zend_ffi_val *val, zend_ffi_dcl *dcl) /* {{{ */
7668 {
7669 	zend_ffi_type *type;
7670 
7671 	zend_ffi_finalize_type(dcl);
7672 	type = ZEND_FFI_TYPE(dcl->type);
7673 	val->kind = (type->size > 0xffffffff) ? ZEND_FFI_VAL_UINT64 : ZEND_FFI_VAL_UINT32;
7674 	val->u64 = type->size;
7675 	zend_ffi_type_dtor(dcl->type);
7676 }
7677 /* }}} */
7678 
7679 void zend_ffi_expr_alignof_val(zend_ffi_val *val) /* {{{ */
7680 {
7681 	if (val->kind == ZEND_FFI_VAL_UINT32 || val->kind == ZEND_FFI_VAL_INT32) {
7682 		val->kind = ZEND_FFI_VAL_UINT32;
7683 		val->u64 = zend_ffi_type_uint32.align;
7684 	} else if (val->kind == ZEND_FFI_VAL_UINT64 || val->kind == ZEND_FFI_VAL_INT64) {
7685 		val->kind = ZEND_FFI_VAL_UINT32;
7686 		val->u64 = zend_ffi_type_uint64.align;
7687 	} else if (val->kind == ZEND_FFI_VAL_FLOAT) {
7688 		val->kind = ZEND_FFI_VAL_UINT32;
7689 		val->u64 = zend_ffi_type_float.align;
7690 	} else if (val->kind == ZEND_FFI_VAL_DOUBLE) {
7691 		val->kind = ZEND_FFI_VAL_UINT32;
7692 		val->u64 = zend_ffi_type_double.align;
7693 #ifdef HAVE_LONG_DOUBLE
7694 	} else if (val->kind == ZEND_FFI_VAL_LONG_DOUBLE) {
7695 		val->kind = ZEND_FFI_VAL_UINT32;
7696 		val->u64 = zend_ffi_type_long_double.align;
7697 #endif
7698 	} else if (val->kind == ZEND_FFI_VAL_CHAR) {
7699 		val->kind = ZEND_FFI_VAL_UINT32;
7700 		val->u64 = zend_ffi_type_char.size;
7701 	} else if (val->kind == ZEND_FFI_VAL_STRING) {
7702 		val->kind = ZEND_FFI_VAL_UINT32;
7703 		val->u64 = _Alignof(char*);
7704 	} else {
7705 		val->kind = ZEND_FFI_VAL_ERROR;
7706 	}
7707 }
7708 /* }}} */
7709 
7710 void zend_ffi_expr_alignof_type(zend_ffi_val *val, zend_ffi_dcl *dcl) /* {{{ */
7711 {
7712 	zend_ffi_finalize_type(dcl);
7713 	val->kind = ZEND_FFI_VAL_UINT32;
7714 	val->u64 = ZEND_FFI_TYPE(dcl->type)->align;
7715 	zend_ffi_type_dtor(dcl->type);
7716 }
7717 /* }}} */
7718 
7719 void zend_ffi_val_number(zend_ffi_val *val, int base, const char *str, size_t str_len) /* {{{ */
7720 {
7721 	int u = 0;
7722 	int l = 0;
7723 
7724 	if (str[str_len-1] == 'u' || str[str_len-1] == 'U') {
7725 		u = 1;
7726 		if (str[str_len-2] == 'l' || str[str_len-2] == 'L') {
7727 			l = 1;
7728 			if (str[str_len-3] == 'l' || str[str_len-3] == 'L') {
7729 				l = 2;
7730 			}
7731 		}
7732 	} else if (str[str_len-1] == 'l' || str[str_len-1] == 'L') {
7733 		l = 1;
7734 		if (str[str_len-2] == 'l' || str[str_len-2] == 'L') {
7735 			l = 2;
7736 			if (str[str_len-3] == 'u' || str[str_len-3] == 'U') {
7737 				u = 1;
7738 			}
7739 		} else if (str[str_len-2] == 'u' || str[str_len-2] == 'U') {
7740 			u = 1;
7741 		}
7742 	}
7743 	if (u) {
7744 		val->u64 = strtoull(str, NULL, base);
7745 		if (l == 0) {
7746 			val->kind = ZEND_FFI_VAL_UINT32;
7747 		} else if (l == 1) {
7748 			val->kind = (sizeof(long) == 4) ? ZEND_FFI_VAL_UINT32 : ZEND_FFI_VAL_UINT64;
7749 		} else if (l == 2) {
7750 			val->kind = ZEND_FFI_VAL_UINT64;
7751 		}
7752 	} else {
7753 		val->i64 = strtoll(str, NULL, base);
7754 		if (l == 0) {
7755 			val->kind = ZEND_FFI_VAL_INT32;
7756 		} else if (l == 1) {
7757 			val->kind = (sizeof(long) == 4) ? ZEND_FFI_VAL_INT32 : ZEND_FFI_VAL_INT64;
7758 		} else if (l == 2) {
7759 			val->kind = ZEND_FFI_VAL_INT64;
7760 		}
7761 	}
7762 }
7763 /* }}} */
7764 
7765 void zend_ffi_val_float_number(zend_ffi_val *val, const char *str, size_t str_len) /* {{{ */
7766 {
7767 	val->d = strtold(str, NULL);
7768 	if (str[str_len-1] == 'f' || str[str_len-1] == 'F') {
7769 		val->kind = ZEND_FFI_VAL_FLOAT;
7770 	} else if (str[str_len-1] == 'l' || str[str_len-1] == 'L') {
7771 		val->kind = ZEND_FFI_VAL_LONG_DOUBLE;
7772 	} else {
7773 		val->kind = ZEND_FFI_VAL_DOUBLE;
7774 	}
7775 }
7776 /* }}} */
7777 
7778 void zend_ffi_val_string(zend_ffi_val *val, const char *str, size_t str_len) /* {{{ */
7779 {
7780 	if (str[0] != '\"') {
7781 		val->kind = ZEND_FFI_VAL_ERROR;
7782 	} else {
7783 		val->kind = ZEND_FFI_VAL_STRING;
7784 		val->str = str + 1;
7785 		val->len = str_len - 2;
7786 	}
7787 }
7788 /* }}} */
7789 
7790 void zend_ffi_val_character(zend_ffi_val *val, const char *str, size_t str_len) /* {{{ */
7791 {
7792 	int n;
7793 
7794 	if (str[0] != '\'') {
7795 		val->kind = ZEND_FFI_VAL_ERROR;
7796 	} else {
7797 		val->kind = ZEND_FFI_VAL_CHAR;
7798 		if (str_len == 3) {
7799 			val->ch = str[1];
7800 		} else if (str[1] == '\\') {
7801 			if (str[2] == 'a') {
7802 			} else if (str[2] == 'b' && str_len == 4) {
7803 				val->ch = '\b';
7804 			} else if (str[2] == 'f' && str_len == 4) {
7805 				val->ch = '\f';
7806 			} else if (str[2] == 'n' && str_len == 4) {
7807 				val->ch = '\n';
7808 			} else if (str[2] == 'r' && str_len == 4) {
7809 				val->ch = '\r';
7810 			} else if (str[2] == 't' && str_len == 4) {
7811 				val->ch = '\t';
7812 			} else if (str[2] == 'v' && str_len == 4) {
7813 				val->ch = '\v';
7814 			} else if (str[2] >= '0' && str[2] <= '7') {
7815 				n = str[2] - '0';
7816 				if (str[3] >= '0' && str[3] <= '7') {
7817 					n = n * 8 + (str[3] - '0');
7818 					if ((str[4] >= '0' && str[4] <= '7') && str_len == 6) {
7819 						n = n * 8 + (str[4] - '0');
7820 					} else if (str_len != 5) {
7821 						val->kind = ZEND_FFI_VAL_ERROR;
7822 					}
7823 				} else if (str_len != 4) {
7824 					val->kind = ZEND_FFI_VAL_ERROR;
7825 				}
7826 				if (n <= 0xff) {
7827 					val->ch = n;
7828 				} else {
7829 					val->kind = ZEND_FFI_VAL_ERROR;
7830 				}
7831 			} else if (str[2] == 'x') {
7832 				if (str[3] >= '0' && str[3] <= '9') {
7833 					n = str[3] - '0';
7834 				} else if (str[3] >= 'A' && str[3] <= 'F') {
7835 					n = str[3] - 'A';
7836 				} else if (str[3] >= 'a' && str[3] <= 'f') {
7837 					n = str[3] - 'a';
7838 				} else {
7839 					val->kind = ZEND_FFI_VAL_ERROR;
7840 					return;
7841 				}
7842 				if ((str[4] >= '0' && str[4] <= '9') && str_len == 6) {
7843 					n = n * 16 + (str[4] - '0');
7844 				} else if ((str[4] >= 'A' && str[4] <= 'F') && str_len == 6) {
7845 					n = n * 16 + (str[4] - 'A');
7846 				} else if ((str[4] >= 'a' && str[4] <= 'f') && str_len == 6) {
7847 					n = n * 16 + (str[4] - 'a');
7848 				} else if (str_len != 5) {
7849 					val->kind = ZEND_FFI_VAL_ERROR;
7850 					return;
7851 				}
7852 				val->ch = n;
7853 			} else if (str_len == 4) {
7854 				val->ch = str[2];
7855 			} else {
7856 				val->kind = ZEND_FFI_VAL_ERROR;
7857 			}
7858 		} else {
7859 			val->kind = ZEND_FFI_VAL_ERROR;
7860 		}
7861 	}
7862 }
7863 /* }}} */
7864