xref: /PHP-5.3/Zend/zend_vm_gen.php (revision 831fbcf3)
1<?php
2/*
3   +----------------------------------------------------------------------+
4   | Zend Engine                                                          |
5   +----------------------------------------------------------------------+
6   | Copyright (c) 1998-2013 Zend Technologies Ltd. (http://www.zend.com) |
7   +----------------------------------------------------------------------+
8   | This source file is subject to version 2.00 of the Zend license,     |
9   | that is bundled with this package in the file LICENSE, and is        |
10   | available through the world-wide-web at the following url:           |
11   | http://www.zend.com/license/2_00.txt.                                |
12   | If you did not receive a copy of the Zend license and are unable to  |
13   | obtain it through the world-wide-web, please send a note to          |
14   | license@zend.com so we can mail you a copy immediately.              |
15   +----------------------------------------------------------------------+
16   | Authors: Dmitry Stogov <dmitry@zend.com>                             |
17   +----------------------------------------------------------------------+
18
19	 $Id$
20*/
21
22$header_text = <<< DATA
23/*
24   +----------------------------------------------------------------------+
25   | Zend Engine                                                          |
26   +----------------------------------------------------------------------+
27   | Copyright (c) 1998-2013 Zend Technologies Ltd. (http://www.zend.com) |
28   +----------------------------------------------------------------------+
29   | This source file is subject to version 2.00 of the Zend license,     |
30   | that is bundled with this package in the file LICENSE, and is        |
31   | available through the world-wide-web at the following url:           |
32   | http://www.zend.com/license/2_00.txt.                                |
33   | If you did not receive a copy of the Zend license and are unable to  |
34   | obtain it through the world-wide-web, please send a note to          |
35   | license@zend.com so we can mail you a copy immediately.              |
36   +----------------------------------------------------------------------+
37   | Authors: Andi Gutmans <andi@zend.com>                                |
38   |          Zeev Suraski <zeev@zend.com>                                |
39   |          Dmitry Stogov <dmitry@zend.com>                             |
40   +----------------------------------------------------------------------+
41*/
42
43
44DATA;
45
46/*
47	This script creates zend_vm_execute.h and zend_vm_opcodes.h
48	from existing zend_vm_def.h and zend_vm_execute.skl
49*/
50
51error_reporting(E_ALL);
52
53define("ZEND_VM_KIND_CALL",   1);
54define("ZEND_VM_KIND_SWITCH", 2);
55define("ZEND_VM_KIND_GOTO",   3);
56
57$op_types = array(
58	"ANY",
59	"CONST",
60	"TMP",
61	"VAR",
62	"UNUSED",
63	"CV"
64);
65
66$prefix = array(
67	"ANY"    => "",
68	"TMP"    => "_TMP",
69	"VAR"    => "_VAR",
70	"CONST"  => "_CONST",
71	"UNUSED" => "_UNUSED",
72	"CV"     => "_CV",
73);
74
75$typecode = array(
76	"ANY"    => 0,
77	"TMP"    => 1,
78	"VAR"    => 2,
79	"CONST"  => 0,
80	"UNUSED" => 3,
81	"CV"     => 4,
82);
83
84$op1_type = array(
85	"ANY"    => "opline->op1.op_type",
86	"TMP"    => "IS_TMP_VAR",
87	"VAR"    => "IS_VAR",
88	"CONST"  => "IS_CONST",
89	"UNUSED" => "IS_UNUSED",
90	"CV"     => "IS_CV",
91);
92
93$op2_type = array(
94	"ANY"    => "opline->op2.op_type",
95	"TMP"    => "IS_TMP_VAR",
96	"VAR"    => "IS_VAR",
97	"CONST"  => "IS_CONST",
98	"UNUSED" => "IS_UNUSED",
99	"CV"     => "IS_CV",
100);
101
102$op1_free = array(
103	"ANY"    => "(free_op1.var != NULL)",
104	"TMP"    => "1",
105	"VAR"    => "(free_op1.var != NULL)",
106	"CONST"  => "0",
107	"UNUSED" => "0",
108	"CV"     => "0",
109);
110
111$op2_free = array(
112	"ANY"    => "(free_op2.var != NULL)",
113	"TMP"    => "1",
114	"VAR"    => "(free_op2.var != NULL)",
115	"CONST"  => "0",
116	"UNUSED" => "0",
117	"CV"     => "0",
118);
119
120$op1_get_zval_ptr = array(
121	"ANY"    => "get_zval_ptr(&opline->op1, EX(Ts), &free_op1, \\1)",
122	"TMP"    => "_get_zval_ptr_tmp(&opline->op1, EX(Ts), &free_op1 TSRMLS_CC)",
123	"VAR"    => "_get_zval_ptr_var(&opline->op1, EX(Ts), &free_op1 TSRMLS_CC)",
124	"CONST"  => "&opline->op1.u.constant",
125	"UNUSED" => "NULL",
126	"CV"     => "_get_zval_ptr_cv(&opline->op1, EX(Ts), \\1 TSRMLS_CC)",
127);
128
129$op2_get_zval_ptr = array(
130	"ANY"    => "get_zval_ptr(&opline->op2, EX(Ts), &free_op2, \\1)",
131	"TMP"    => "_get_zval_ptr_tmp(&opline->op2, EX(Ts), &free_op2 TSRMLS_CC)",
132	"VAR"    => "_get_zval_ptr_var(&opline->op2, EX(Ts), &free_op2 TSRMLS_CC)",
133	"CONST"  => "&opline->op2.u.constant",
134	"UNUSED" => "NULL",
135	"CV"     => "_get_zval_ptr_cv(&opline->op2, EX(Ts), \\1 TSRMLS_CC)",
136);
137
138$op1_get_zval_ptr_ptr = array(
139	"ANY"    => "get_zval_ptr_ptr(&opline->op1, EX(Ts), &free_op1, \\1)",
140	"TMP"    => "NULL",
141	"VAR"    => "_get_zval_ptr_ptr_var(&opline->op1, EX(Ts), &free_op1 TSRMLS_CC)",
142	"CONST"  => "NULL",
143	"UNUSED" => "NULL",
144	"CV"     => "_get_zval_ptr_ptr_cv(&opline->op1, EX(Ts), \\1 TSRMLS_CC)",
145);
146
147$op2_get_zval_ptr_ptr = array(
148	"ANY"    => "get_zval_ptr_ptr(&opline->op2, EX(Ts), &free_op2, \\1)",
149	"TMP"    => "NULL",
150	"VAR"    => "_get_zval_ptr_ptr_var(&opline->op2, EX(Ts), &free_op2 TSRMLS_CC)",
151	"CONST"  => "NULL",
152	"UNUSED" => "NULL",
153	"CV"     => "_get_zval_ptr_ptr_cv(&opline->op2, EX(Ts), \\1 TSRMLS_CC)",
154);
155
156$op1_get_obj_zval_ptr = array(
157	"ANY"    => "get_obj_zval_ptr(&opline->op1, EX(Ts), &free_op1, \\1)",
158	"TMP"    => "_get_zval_ptr_tmp(&opline->op1, EX(Ts), &free_op1 TSRMLS_CC)",
159	"VAR"    => "_get_zval_ptr_var(&opline->op1, EX(Ts), &free_op1 TSRMLS_CC)",
160	"CONST"  => "&opline->op1.u.constant",
161	"UNUSED" => "_get_obj_zval_ptr_unused(TSRMLS_C)",
162	"CV"     => "_get_zval_ptr_cv(&opline->op1, EX(Ts), \\1 TSRMLS_CC)",
163);
164
165$op2_get_obj_zval_ptr = array(
166	"ANY"    => "get_obj_zval_ptr(&opline->op2, EX(Ts), &free_op2, \\1)",
167	"TMP"    => "_get_zval_ptr_tmp(&opline->op2, EX(Ts), &free_op2 TSRMLS_CC)",
168	"VAR"    => "_get_zval_ptr_var(&opline->op2, EX(Ts), &free_op2 TSRMLS_CC)",
169	"CONST"  => "&opline->op2.u.constant",
170	"UNUSED" => "_get_obj_zval_ptr_unused(TSRMLS_C)",
171	"CV"     => "_get_zval_ptr_cv(&opline->op2, EX(Ts), \\1 TSRMLS_CC)",
172);
173
174$op1_get_obj_zval_ptr_ptr = array(
175	"ANY"    => "get_obj_zval_ptr_ptr(&opline->op1, EX(Ts), &free_op1, \\1)",
176	"TMP"    => "NULL",
177	"VAR"    => "_get_zval_ptr_ptr_var(&opline->op1, EX(Ts), &free_op1 TSRMLS_CC)",
178	"CONST"  => "NULL",
179	"UNUSED" => "_get_obj_zval_ptr_ptr_unused(TSRMLS_C)",
180	"CV"     => "_get_zval_ptr_ptr_cv(&opline->op1, EX(Ts), \\1 TSRMLS_CC)",
181);
182
183$op2_get_obj_zval_ptr_ptr = array(
184	"ANY"    => "get_obj_zval_ptr_ptr(&opline->op2, EX(Ts), &free_op2, \\1)",
185	"TMP"    => "NULL",
186	"VAR"    => "_get_zval_ptr_ptr_var(&opline->op2, EX(Ts), &free_op2 TSRMLS_CC)",
187	"CONST"  => "NULL",
188	"UNUSED" => "_get_obj_zval_ptr_ptr_unused(TSRMLS_C)",
189	"CV"     => "_get_zval_ptr_ptr_cv(&opline->op2, EX(Ts), \\1 TSRMLS_CC)",
190);
191
192$op1_is_tmp_free = array(
193	"ANY"    => "IS_TMP_FREE(free_op1)",
194	"TMP"    => "1",
195	"VAR"    => "0",
196	"CONST"  => "0",
197	"UNUSED" => "0",
198	"CV"     => "0",
199);
200
201$op2_is_tmp_free = array(
202	"ANY"    => "IS_TMP_FREE(free_op2)",
203	"TMP"    => "1",
204	"VAR"    => "0",
205	"CONST"  => "0",
206	"UNUSED" => "0",
207	"CV"     => "0",
208);
209
210$op1_free_op = array(
211	"ANY"    => "FREE_OP(free_op1)",
212	"TMP"    => "zval_dtor(free_op1.var)",
213	"VAR"    => "if (free_op1.var) {zval_ptr_dtor(&free_op1.var);}",
214	"CONST"  => "",
215	"UNUSED" => "",
216	"CV"     => "",
217);
218
219$op2_free_op = array(
220	"ANY"    => "FREE_OP(free_op2)",
221	"TMP"    => "zval_dtor(free_op2.var)",
222	"VAR"    => "if (free_op2.var) {zval_ptr_dtor(&free_op2.var);}",
223	"CONST"  => "",
224	"UNUSED" => "",
225	"CV"     => "",
226);
227
228$op1_free_op_if_var = array(
229	"ANY"    => "FREE_OP_IF_VAR(free_op1)",
230	"TMP"    => "",
231	"VAR"    => "if (free_op1.var) {zval_ptr_dtor(&free_op1.var);}",
232	"CONST"  => "",
233	"UNUSED" => "",
234	"CV"     => "",
235);
236
237$op2_free_op_if_var = array(
238	"ANY"    => "FREE_OP_IF_VAR(free_op2)",
239	"TMP"    => "",
240	"VAR"    => "if (free_op2.var) {zval_ptr_dtor(&free_op2.var);}",
241	"CONST"  => "",
242	"UNUSED" => "",
243	"CV"     => "",
244);
245
246$op1_free_op_var_ptr = array(
247	"ANY"    => "if (free_op1.var) {zval_ptr_dtor(&free_op1.var);}",
248	"TMP"    => "",
249	"VAR"    => "if (free_op1.var) {zval_ptr_dtor(&free_op1.var);}",
250	"CONST"  => "",
251	"UNUSED" => "",
252	"CV"     => "",
253);
254
255$op2_free_op_var_ptr = array(
256	"ANY"    => "if (free_op2.var) {zval_ptr_dtor(&free_op2.var);}",
257	"TMP"    => "",
258	"VAR"    => "if (free_op2.var) {zval_ptr_dtor(&free_op2.var);}",
259	"CONST"  => "",
260	"UNUSED" => "",
261	"CV"     => "",
262);
263
264$list    = array(); // list of opcode handlers and helpers in original order
265$opcodes = array(); // opcode handlers by code
266$helpers = array(); // opcode helpers by name
267$params  = array(); // parameters of helpers
268$opnames = array(); // opcode name to code mapping
269$line_no = 1;
270
271// Writes $s into resulting executor
272function out($f, $s) {
273	global $line_no;
274
275	fputs($f,$s);
276	$line_no += substr_count($s, "\n");
277}
278
279// Resets #line directives in resulting executor
280function out_line($f) {
281	global $line_no, $executor_file;
282
283	fputs($f,"#line ".($line_no+1)." \"".$executor_file."\"\n");
284	++$line_no;
285}
286
287// Returns name of specialized helper
288function helper_name($name, $spec, $op1, $op2) {
289	global $prefix, $helpers;
290
291	if (isset($helpers[$name])) {
292		// If we haven't helper with specified spicialized operands then
293		// using unspecialized helper
294		if (!isset($helpers[$name]["op1"][$op1]) &&
295		    isset($helpers[$name]["op1"]["ANY"])) {
296			$op1 = "ANY";
297		}
298		if (!isset($helpers[$name]["op2"][$op2]) &&
299		    isset($helpers[$name]["op2"]["ANY"])) {
300			$op2 = "ANY";
301		}
302	}
303	return $name.($spec?"_SPEC":"").$prefix[$op1].$prefix[$op2];
304}
305
306// Generates code for opcode handler or helper
307function gen_code($f, $spec, $kind, $export, $code, $op1, $op2, $name) {
308	global $op1_type, $op2_type, $op1_get_zval_ptr, $op2_get_zval_ptr,
309		$op1_get_zval_ptr_ptr, $op2_get_zval_ptr_ptr,
310		$op1_get_obj_zval_ptr, $op2_get_obj_zval_ptr,
311		$op1_get_obj_zval_ptr_ptr, $op2_get_obj_zval_ptr_ptr,
312		$op1_is_tmp_free, $op2_is_tmp_free, $op1_free, $op2_free,
313		$op1_free_op, $op2_free_op, $op1_free_op_if_var, $op2_free_op_if_var,
314		$op1_free_op_var_ptr, $op2_free_op_var_ptr, $prefix;
315
316	// Specializing
317	$code = preg_replace(
318		array(
319			"/OP1_TYPE/",
320			"/OP2_TYPE/",
321			"/OP1_FREE/",
322			"/OP2_FREE/",
323			"/GET_OP1_ZVAL_PTR\(([^)]*)\)/",
324			"/GET_OP2_ZVAL_PTR\(([^)]*)\)/",
325			"/GET_OP1_ZVAL_PTR_PTR\(([^)]*)\)/",
326			"/GET_OP2_ZVAL_PTR_PTR\(([^)]*)\)/",
327			"/GET_OP1_OBJ_ZVAL_PTR\(([^)]*)\)/",
328			"/GET_OP2_OBJ_ZVAL_PTR\(([^)]*)\)/",
329			"/GET_OP1_OBJ_ZVAL_PTR_PTR\(([^)]*)\)/",
330			"/GET_OP2_OBJ_ZVAL_PTR_PTR\(([^)]*)\)/",
331			"/IS_OP1_TMP_FREE\(\)/",
332			"/IS_OP2_TMP_FREE\(\)/",
333			"/FREE_OP1\(\)/",
334			"/FREE_OP2\(\)/",
335			"/FREE_OP1_IF_VAR\(\)/",
336			"/FREE_OP2_IF_VAR\(\)/",
337			"/FREE_OP1_VAR_PTR\(\)/",
338			"/FREE_OP2_VAR_PTR\(\)/",
339			"/^#ifdef\s+ZEND_VM_SPEC\s*\n/m",
340			"/^#ifndef\s+ZEND_VM_SPEC\s*\n/m",
341			"/\!defined\(ZEND_VM_SPEC\)/m",
342			"/defined\(ZEND_VM_SPEC\)/m",
343			"/ZEND_VM_C_LABEL\(\s*([A-Za-z_]*)\s*\)/m",
344			"/ZEND_VM_C_GOTO\(\s*([A-Za-z_]*)\s*\)/m",
345			"/^#if\s+1\s*\\|\\|.*[^\\\\]$/m",
346			"/^#if\s+0\s*&&.*[^\\\\]$/m",
347			"/^#ifdef\s+ZEND_VM_EXPORT\s*\n/m",
348			"/^#ifndef\s+ZEND_VM_EXPORT\s*\n/m"
349		),
350		array(
351			$op1_type[$op1],
352			$op2_type[$op2],
353			$op1_free[$op1],
354			$op2_free[$op2],
355			$op1_get_zval_ptr[$op1],
356			$op2_get_zval_ptr[$op2],
357			$op1_get_zval_ptr_ptr[$op1],
358			$op2_get_zval_ptr_ptr[$op2],
359			$op1_get_obj_zval_ptr[$op1],
360			$op2_get_obj_zval_ptr[$op2],
361			$op1_get_obj_zval_ptr_ptr[$op1],
362			$op2_get_obj_zval_ptr_ptr[$op2],
363			$op1_is_tmp_free[$op1],
364			$op2_is_tmp_free[$op2],
365			$op1_free_op[$op1],
366			$op2_free_op[$op2],
367			$op1_free_op_if_var[$op1],
368			$op2_free_op_if_var[$op2],
369			$op1_free_op_var_ptr[$op1],
370			$op2_free_op_var_ptr[$op2],
371			($op1!="ANY"||$op2!="ANY")?"#if 1\n":"#if 0\n",
372			($op1!="ANY"||$op2!="ANY")?"#if 0\n":"#if 1\n",
373			($op1!="ANY"||$op2!="ANY")?"0":"1",
374			($op1!="ANY"||$op2!="ANY")?"1":"0",
375			"\\1".(($spec && $kind != ZEND_VM_KIND_CALL)?("_SPEC".$prefix[$op1].$prefix[$op2]):""),
376			"goto \\1".(($spec && $kind != ZEND_VM_KIND_CALL)?("_SPEC".$prefix[$op1].$prefix[$op2]):""),
377			"#if 1",
378			"#if 0",
379			$export?"#if 1\n":"#if 0\n",
380			$export?"#if 0\n":"#if 1\n"
381		),
382		$code);
383
384	if (0 && strpos($code, '{') === 0) {
385		$code = "{\n\tfprintf(stderr, \"$name\\n\");\n" . substr($code, 1);
386	}
387	// Updating code according to selected threading model
388	switch($kind) {
389		case ZEND_VM_KIND_CALL:
390			$code = preg_replace(
391				array(
392					"/EXECUTE_DATA/m",
393					"/ZEND_VM_DISPATCH_TO_HANDLER\(\s*([A-Z_]*)\s*\)/m",
394					"/ZEND_VM_DISPATCH_TO_HELPER\(\s*([A-Za-z_]*)\s*\)/me",
395					"/ZEND_VM_DISPATCH_TO_HELPER_EX\(\s*([A-Za-z_]*)\s*,\s*[A-Za-z_]*\s*,\s*(.*)\s*\);/me",
396				),
397				array(
398					"execute_data",
399					"return \\1".($spec?"_SPEC":"").$prefix[$op1].$prefix[$op2]."_HANDLER(ZEND_OPCODE_HANDLER_ARGS_PASSTHRU)",
400					"'return '.helper_name('\\1',$spec,'$op1','$op2').'(ZEND_OPCODE_HANDLER_ARGS_PASSTHRU)'",
401					"'return '.helper_name('\\1',$spec,'$op1','$op2').'(\\2, ZEND_OPCODE_HANDLER_ARGS_PASSTHRU);'",
402				),
403				$code);
404			break;
405		case ZEND_VM_KIND_SWITCH:
406			$code = preg_replace(
407				array(
408					"/EXECUTE_DATA/m",
409					"/ZEND_VM_DISPATCH_TO_HANDLER\(\s*([A-Z_]*)\s*\)/m",
410					"/ZEND_VM_DISPATCH_TO_HELPER\(\s*([A-Za-z_]*)\s*\)/me",
411					"/ZEND_VM_DISPATCH_TO_HELPER_EX\(\s*([A-Za-z_]*)\s*,\s*([A-Za-z_]*)\s*,\s*(.*)\s*\);/me",
412				),
413				array(
414					"execute_data",
415					"goto \\1".($spec?"_SPEC":"").$prefix[$op1].$prefix[$op2]."_LABEL",
416					"'goto '.helper_name('\\1',$spec,'$op1','$op2')",
417					"'\\2 = \\3; goto '.helper_name('\\1',$spec,'$op1','$op2').';'",
418				),
419				$code);
420			break;
421		case ZEND_VM_KIND_GOTO:
422			$code = preg_replace(
423				array(
424					"/EXECUTE_DATA/m",
425					"/ZEND_VM_DISPATCH_TO_HANDLER\(\s*([A-Z_]*)\s*\)/m",
426					"/ZEND_VM_DISPATCH_TO_HELPER\(\s*([A-Za-z_]*)\s*\)/me",
427					"/ZEND_VM_DISPATCH_TO_HELPER_EX\(\s*([A-Za-z_]*)\s*,\s*([A-Za-z_]*)\s*,\s*(.*)\s*\);/me",
428				),
429				array(
430					"execute_data",
431					"goto \\1".($spec?"_SPEC":"").$prefix[$op1].$prefix[$op2]."_HANDLER",
432					"'goto '.helper_name('\\1',$spec,'$op1','$op2')",
433					"'\\2 = \\3; goto '.helper_name('\\1',$spec,'$op1','$op2').';'",
434				),
435				$code);
436			break;
437	}
438
439	/* Remove unused free_op1 and free_op2 declarations */
440	if ($spec && preg_match_all('/^\s*zend_free_op\s+[^;]+;\s*$/me', $code, $matches, PREG_SET_ORDER)) {
441		$n = 0;
442		foreach ($matches as $match) {
443		  $code = preg_replace('/'.preg_quote($match[0],'/').'/', "\$D$n", $code);
444		  ++$n;
445		}
446		$del_free_op1 = (strpos($code, "free_op1") === false);
447		$del_free_op2 = (strpos($code, "free_op2") === false);
448		$n = 0;
449		foreach ($matches as $match) {
450			$dcl = $match[0];
451			$changed = 0;
452			if ($del_free_op1 && strpos($dcl, "free_op1") !== false) {
453				$dcl = preg_replace("/free_op1\s*,\s*/", "", $dcl);
454				$dcl = preg_replace("/free_op1\s*;/", ";", $dcl);
455				$changed = 1;
456			}
457			if ($del_free_op2 && strpos($dcl, "free_op2") !== false) {
458				$dcl = preg_replace("/free_op2\s*,\s*/", "", $dcl);
459				$dcl = preg_replace("/free_op2\s*;/", ";", $dcl);
460				$changed = 1;
461			}
462			if ($changed) {
463				$dcl = preg_replace("/,\s*;/", ";", $dcl);
464				$dcl = preg_replace("/zend_free_op\s*;/", "", $dcl);
465			}
466		  $code = preg_replace("/\\\$D$n/", $dcl, $code);
467		  ++$n;
468		}
469	}
470
471	/* Remove unnecessary ';' */
472	$code = preg_replace('/^\s*;\s*$/m', '', $code);
473
474	/* Remove WS */
475	$code = preg_replace('/[ \t]+\n/m', "\n", $code);
476
477	out($f, $code);
478}
479
480// Generates opcode handler
481function gen_handler($f, $spec, $kind, $name, $op1, $op2, $use, $code, $lineno) {
482	global $definition_file, $prefix, $typecode, $opnames;
483
484	if (ZEND_VM_LINES) {
485		out($f, "#line $lineno \"$definition_file\"\n");
486	}
487
488	// Generate opcode handler's entry point according to selected threading model
489	switch($kind) {
490		case ZEND_VM_KIND_CALL:
491			out($f,"static int ZEND_FASTCALL  ".$name.($spec?"_SPEC":"").$prefix[$op1].$prefix[$op2]."_HANDLER(ZEND_OPCODE_HANDLER_ARGS)\n");
492			break;
493		case ZEND_VM_KIND_SWITCH:
494			if ($spec) {
495				out($f,"case ".((string)($opnames[$name]*25+($typecode[$op1]*5)+$typecode[$op2])).": /*".$name."_SPEC".$prefix[$op1].$prefix[$op2]."_HANDLER*/");
496			} else {
497				out($f,"case ".$name.":");
498			}
499			if ($use) {
500				// This handler is used by other handlers. We will add label to call it.
501				out($f," ".$name.($spec?"_SPEC":"").$prefix[$op1].$prefix[$op2]."_LABEL:\n");
502			} else {
503				out($f,"\n");
504			}
505			break;
506		case ZEND_VM_KIND_GOTO:
507			out($f,$name.($spec?"_SPEC":"").$prefix[$op1].$prefix[$op2]."_HANDLER:\n");
508			break;
509	}
510
511	// Generate opcode handler's code
512	gen_code($f, $spec, $kind, 0, $code, $op1, $op2, $name);
513}
514
515// Generates helper
516function gen_helper($f, $spec, $kind, $name, $op1, $op2, $param, $code, $lineno) {
517	global $definition_file, $prefix;
518
519	if (ZEND_VM_LINES) {
520		out($f, "#line $lineno \"$definition_file\"\n");
521	}
522
523	// Generate helper's entry point according to selected threading model
524	switch($kind) {
525		case ZEND_VM_KIND_CALL:
526			if ($param == null) {
527			  // Helper without parameters
528				out($f, "static int ZEND_FASTCALL ".$name.($spec?"_SPEC":"").$prefix[$op1].$prefix[$op2]."(ZEND_OPCODE_HANDLER_ARGS)\n");
529			} else {
530			  // Helper with parameter
531				out($f, "static int ZEND_FASTCALL ".$name.($spec?"_SPEC":"").$prefix[$op1].$prefix[$op2]."(".$param.", ZEND_OPCODE_HANDLER_ARGS)\n");
532			}
533			break;
534		case ZEND_VM_KIND_SWITCH:
535			out($f, $name.($spec?"_SPEC":"").$prefix[$op1].$prefix[$op2].":\n");
536			break;
537		case ZEND_VM_KIND_GOTO:
538			out($f, $name.($spec?"_SPEC":"").$prefix[$op1].$prefix[$op2].":\n");
539			break;
540	}
541
542	// Generate helper's code
543	gen_code($f, $spec, $kind, 0, $code, $op1, $op2, $name);
544}
545
546// Generates array of opcode handlers (specialized or unspecialized)
547function gen_labels($f, $spec, $kind, $prolog) {
548	global $opcodes, $op_types, $prefix, $typecode;
549
550	$next = 0;
551	if ($spec) {
552	  // Emit labels for specialized executor
553
554	  // For each opcode in opcode number order
555		foreach($opcodes as $num => $dsc) {
556			while ($next != $num) {
557			  // If some opcode numbers are not used then fill hole with pointers
558			  // to handler of undefined opcode
559				$op1t = $op_types;
560				// For each op1.op_type except ANY
561				foreach($op1t as $op1) {
562					if ($op1 != "ANY") {
563						$op2t = $op_types;
564						// For each op2.op_type except ANY
565						foreach($op2t as $op2) {
566							if ($op2 != "ANY") {
567							  // Emit pointer to handler of undefined opcode
568								switch ($kind) {
569									case ZEND_VM_KIND_CALL:
570										out($f,$prolog."ZEND_NULL_HANDLER,\n");
571										break;
572									case ZEND_VM_KIND_SWITCH:
573										out($f,$prolog."(opcode_handler_t)-1,\n");
574										break;
575									case ZEND_VM_KIND_GOTO:
576										out($f,$prolog."(opcode_handler_t)&&ZEND_NULL_HANDLER,\n");
577										break;
578								}
579							}
580						}
581					}
582				}
583				$next++;
584			}
585			$next = $num + 1;
586			$op1t = $op_types;
587			// For each op1.op_type except ANY
588			foreach($op1t as $op1) {
589				if ($op1 != "ANY") {
590					if (!isset($dsc["op1"][$op1])) {
591						// Try to use unspecialized handler
592						$op1 = "ANY";
593					}
594					$op2t = $op_types;
595					// For each op2.op_type except ANY
596					foreach($op2t as $op2) {
597						if ($op2 != "ANY") {
598							if (!isset($dsc["op2"][$op2])) {
599								// Try to use unspecialized handler
600								$op2 = "ANY";
601							}
602							// Check if specialized handler is defined
603							if (isset($dsc["op1"][$op1]) &&
604							    isset($dsc["op2"][$op2])) {
605							  // Emit pointer to specialized handler
606								switch ($kind) {
607									case ZEND_VM_KIND_CALL:
608										out($f,$prolog.$dsc["op"]."_SPEC".$prefix[$op1].$prefix[$op2]."_HANDLER,\n");
609										break;
610									case ZEND_VM_KIND_SWITCH:
611										out($f,$prolog."(opcode_handler_t)".((string)($num*25+$typecode[$op1]*5+$typecode[$op2])).",\n");
612										break;
613									case ZEND_VM_KIND_GOTO:
614										out($f,$prolog."(opcode_handler_t)&&".$dsc["op"]."_SPEC".$prefix[$op1].$prefix[$op2]."_HANDLER,\n");
615										break;
616								}
617							} else {
618							  // Emit pinter to handler of undefined opcode
619								switch ($kind) {
620									case ZEND_VM_KIND_CALL:
621										out($f,$prolog."ZEND_NULL_HANDLER,\n");
622										break;
623									case ZEND_VM_KIND_SWITCH:
624										out($f,$prolog."(opcode_handler_t)-1,\n");
625										break;
626									case ZEND_VM_KIND_GOTO:
627										out($f,$prolog."(opcode_handler_t)&&ZEND_NULL_HANDLER,\n");
628										break;
629								}
630							}
631						}
632					}
633				}
634			}
635		}
636	} else {
637	  // Emit labels for unspecialized executor
638
639	  // For each opcode in opcode number order
640		foreach($opcodes as $num => $dsc) {
641			while ($next != $num) {
642			  // If some opcode numbers are not used then fill hole with pointers
643			  // to handler of undefined opcode
644				switch ($kind) {
645					case ZEND_VM_KIND_CALL:
646						out($f,$prolog."ZEND_NULL_HANDLER,\n");
647						break;
648					case ZEND_VM_KIND_SWITCH:
649						out($f,$prolog."(opcode_handler_t)-1,\n");
650						break;
651					case ZEND_VM_KIND_GOTO:
652						out($f,$prolog."(opcode_handler_t)&&ZEND_NULL_HANDLER,\n");
653						break;
654				}
655				$next++;
656			}
657			$next = $num+1;
658		  // Emit pointer to unspecialized handler
659			switch ($kind) {
660				case ZEND_VM_KIND_CALL:
661					out($f,$prolog.$dsc["op"]."_HANDLER,\n");
662					break;
663				case ZEND_VM_KIND_SWITCH:
664					out($f,$prolog."(opcode_handler_t)".((string)$num).",\n");
665					break;
666				case ZEND_VM_KIND_GOTO:
667					out($f,$prolog."(opcode_handler_t)&&".$dsc["op"]."_HANDLER,\n");
668					break;
669			}
670		}
671	}
672
673	// Emit last handler's label (undefined opcode)
674	switch ($kind) {
675		case ZEND_VM_KIND_CALL:
676			out($f,$prolog."ZEND_NULL_HANDLER\n");
677			break;
678		case ZEND_VM_KIND_SWITCH:
679			out($f,$prolog."(opcode_handler_t)-1\n");
680			break;
681		case ZEND_VM_KIND_GOTO:
682			out($f,$prolog."(opcode_handler_t)&&ZEND_NULL_HANDLER\n");
683			break;
684	}
685}
686
687// Generates handler for undefined opcodes (CALL threading model)
688function gen_null_handler($f) {
689	static $done = 0;
690
691	// New and all executors with CALL threading model can use the same handler
692	// for undefined opcodes, do we emit code for it only once
693	if (!$done) {
694		$done = 1;
695		out($f,"static int ZEND_FASTCALL ZEND_NULL_HANDLER(ZEND_OPCODE_HANDLER_ARGS)\n");
696		out($f,"{\n");
697		out($f,"\tzend_error_noreturn(E_ERROR, \"Invalid opcode %d/%d/%d.\", EX(opline)->opcode, EX(opline)->op1.op_type, EX(opline)->op2.op_type);\n");
698		out($f,"}\n\n");
699	}
700}
701
702// Generates all opcode handlers and helpers (specialized or unspecilaized)
703function gen_executor_code($f, $spec, $kind, $prolog) {
704	global $list, $opcodes, $helpers, $op_types;
705
706	if ($spec) {
707		// Produce specialized executor
708		$op1t = $op_types;
709		// for each op1.op_type
710		foreach($op1t as $op1) {
711			$op2t = $op_types;
712			// for each op2.op_type
713			foreach($op2t as $op2) {
714				// for each handlers in helpers in original order
715				foreach ($list as $lineno => $dsc) {
716					if (isset($dsc["handler"])) {
717						$num = $dsc["handler"];
718						// Check if handler accepts such types of operands (op1 and op2)
719						if (isset($opcodes[$num]["op1"][$op1]) &&
720						    isset($opcodes[$num]["op2"][$op2])) {
721						  // Generate handler code
722							gen_handler($f, 1, $kind, $opcodes[$num]["op"], $op1, $op2, isset($opcodes[$num]["use"]), $opcodes[$num]["code"], $lineno);
723						}
724					} else if (isset($dsc["helper"])) {
725						$num = $dsc["helper"];
726						// Check if handler accepts such types of operands (op1 and op2)
727						if (isset($helpers[$num]["op1"][$op1]) &&
728						    isset($helpers[$num]["op2"][$op2])) {
729						  // Generate helper code
730							gen_helper($f, 1, $kind, $num, $op1, $op2, $helpers[$num]["param"], $helpers[$num]["code"], $lineno);
731						}
732					} else {
733						var_dump($dsc);
734						die("??? $kind:$num\n");
735					}
736				}
737			}
738		}
739	} else {
740		// Produce unspecialized executor
741
742		// for each handlers in helpers in original order
743		foreach ($list as $lineno => $dsc) {
744			if (isset($dsc["handler"])) {
745				$num = $dsc["handler"];
746			  // Generate handler code
747				gen_handler($f, 0, $kind, $opcodes[$num]["op"], "ANY", "ANY", isset($opcodes[$num]["use"]), $opcodes[$num]["code"], $lineno);
748			} else if (isset($dsc["helper"])) {
749				$num = $dsc["helper"];
750			  // Generate helper code
751				gen_helper($f, 0, $kind, $num, "ANY", "ANY", $helpers[$num]["param"], $helpers[$num]["code"], $lineno);
752			} else {
753				var_dump($dsc);
754				die("??? $kind:$num\n");
755			}
756		}
757	}
758
759	if (ZEND_VM_LINES) {
760		// Reset #line directives
761		out_line($f);
762	}
763
764	// Generate handler for undefined opcodes
765	switch ($kind) {
766		case ZEND_VM_KIND_CALL:
767			gen_null_handler($f);
768			break;
769		case ZEND_VM_KIND_SWITCH:
770			out($f,"default:\n");
771			out($f,"\tzend_error_noreturn(E_ERROR, \"Invalid opcode %d/%d/%d.\", EX(opline)->opcode, EX(opline)->op1.op_type, EX(opline)->op2.op_type);\n");
772			break;
773		case ZEND_VM_KIND_GOTO:
774			out($f,"ZEND_NULL_HANDLER:\n");
775			out($f,"\tzend_error_noreturn(E_ERROR, \"Invalid opcode %d/%d/%d.\", EX(opline)->opcode, EX(opline)->op1.op_type, EX(opline)->op2.op_type);\n");
776			break;
777	}
778}
779
780function skip_blanks($f, $prolog, $epilog) {
781	if (trim($prolog) != "" || trim($epilog) != "") {
782		out($f, $prolog.$epilog);
783	}
784}
785
786// Generates executor from skeleton file and definition (specialized or unspecialized)
787function gen_executor($f, $skl, $spec, $kind, $executor_name, $initializer_name, $old) {
788	global $params, $skeleton_file, $line_no;
789
790	$lineno      = 0;
791	foreach ($skl as $line) {
792	  // Skeleton file contains special markers in form %NAME% those are
793	  // substituted by custom code
794		if (preg_match("/(.*)[{][%]([A-Z_]*)[%][}](.*)/", $line, $m)) {
795			switch ($m[2]) {
796				case "DEFINES":
797					if (ZEND_VM_OLD_EXECUTOR && $spec) {
798						out($f,"static int zend_vm_old_executor = 0;\n\n");
799					}
800					out($f,"static opcode_handler_t zend_vm_get_opcode_handler(zend_uchar opcode, zend_op* op);\n\n");
801					switch ($kind) {
802						case ZEND_VM_KIND_CALL:
803							out($f,"\n");
804							out($f,"#define ZEND_VM_CONTINUE()   return 0\n");
805							out($f,"#define ZEND_VM_RETURN()     return 1\n");
806							out($f,"#define ZEND_VM_ENTER()      return 2\n");
807							out($f,"#define ZEND_VM_LEAVE()      return 3\n");
808							out($f,"#define ZEND_VM_DISPATCH(opcode, opline) return zend_vm_get_opcode_handler(opcode, opline)(ZEND_OPCODE_HANDLER_ARGS_PASSTHRU);\n\n");
809							out($f,"#define ZEND_OPCODE_HANDLER_ARGS_PASSTHRU_INTERNAL execute_data TSRMLS_CC\n");
810							out($f,"#undef EX\n");
811							out($f,"#define EX(element) execute_data->element\n\n");
812							break;
813						case ZEND_VM_KIND_SWITCH:
814							out($f,"\n");
815							out($f,"#define ZEND_VM_CONTINUE() goto zend_vm_continue\n");
816							out($f,"#define ZEND_VM_RETURN()   EG(in_execution) = original_in_execution; return\n");
817							out($f,"#define ZEND_VM_ENTER()    op_array = EG(active_op_array); goto zend_vm_enter\n");
818							out($f,"#define ZEND_VM_LEAVE()    ZEND_VM_CONTINUE()\n");
819							out($f,"#define ZEND_VM_DISPATCH(opcode, opline) dispatch_handler = zend_vm_get_opcode_handler(opcode, opline); goto zend_vm_dispatch;\n\n");
820							out($f,"#define ZEND_OPCODE_HANDLER_ARGS_PASSTHRU_INTERNAL execute_data TSRMLS_CC\n");
821							out($f,"#undef EX\n");
822							out($f,"#define EX(element) execute_data->element\n\n");
823							break;
824						case ZEND_VM_KIND_GOTO:
825							out($f,"\n");
826							out($f,"#define ZEND_VM_CONTINUE() goto *(void**)(EX(opline)->handler)\n");
827							out($f,"#define ZEND_VM_RETURN()   EG(in_execution) = original_in_execution; return\n");
828							out($f,"#define ZEND_VM_ENTER()    op_array = EG(active_op_array); goto zend_vm_enter\n");
829							out($f,"#define ZEND_VM_LEAVE()    ZEND_VM_CONTINUE()\n");
830							out($f,"#define ZEND_VM_DISPATCH(opcode, opline) goto *(void**)(zend_vm_get_opcode_handler(opcode, opline));\n\n");
831							out($f,"#define ZEND_OPCODE_HANDLER_ARGS_PASSTHRU_INTERNAL execute_data TSRMLS_CC\n");
832							out($f,"#undef EX\n");
833							out($f,"#define EX(element) execute_data->element\n\n");
834							break;
835					}
836					break;
837				case "EXECUTOR_NAME":
838					out($f, $m[1].$executor_name.$m[3]."\n");
839					break;
840				case "HELPER_VARS":
841					if ($kind != ZEND_VM_KIND_CALL) {
842						if ($kind == ZEND_VM_KIND_SWITCH) {
843							out($f,$m[1]."opcode_handler_t dispatch_handler;\n");
844						}
845					  // Emit local variables those are used for helpers' parameters
846						foreach ($params as $param => $x) {
847							out($f,$m[1].$param.";\n");
848						}
849					} else {
850						skip_blanks($f, $m[1], $m[3]."\n");
851					}
852					break;
853				case "EXECUTION_STATUS":
854					if ($kind != ZEND_VM_KIND_GOTO) {
855						out($f, $m[1] . "zend_bool original_in_execution = EG(in_execution);\n");
856					} else {
857						out($f, $m[1] . "zend_bool original_in_execution = op_array? EG(in_execution) : 0;\n");
858					}
859					break;
860				case "INTERNAL_LABELS":
861					if ($kind == ZEND_VM_KIND_GOTO) {
862					  // Emit array of labels of opcode handlers and code for
863					  // zend_opcode_handlers initialization
864						$prolog = $m[1];
865						out($f,$prolog."if (op_array == NULL) {\n");
866						out($f,$prolog."\tstatic const opcode_handler_t labels[] = {\n");
867						gen_labels($f, $spec, $kind, $prolog."\t\t");
868						out($f,$prolog."\t};\n");
869						out($f,$prolog."\tzend_opcode_handlers = (opcode_handler_t*)labels;\n");
870						out($f,$prolog."\treturn;\n");
871						out($f,$prolog."}\n");
872					} else {
873						skip_blanks($f, $m[1], $m[3]);
874					}
875					break;
876				case "ZEND_VM_CONTINUE_LABEL":
877					if ($kind == ZEND_VM_KIND_CALL) {
878					  // Only SWITCH dispatch method use it
879						out($f,$m[1]."\tint ret;".$m[3]."\n");
880					} else if ($kind == ZEND_VM_KIND_SWITCH) {
881					  // Only SWITCH dispatch method use it
882						out($f,"zend_vm_continue:".$m[3]."\n");
883					} else {
884						skip_blanks($f, $m[1], $m[3]);
885					}
886					break;
887				case "ZEND_VM_DISPATCH":
888				  // Emit code that dispatches to opcode handler
889					switch ($kind) {
890						case ZEND_VM_KIND_CALL:
891							out($f, $m[1]."if ((ret = EX(opline)->handler(execute_data TSRMLS_CC)) > 0)".$m[3]."\n");
892							break;
893						case ZEND_VM_KIND_SWITCH:
894							out($f, $m[1]."dispatch_handler = EX(opline)->handler;\nzend_vm_dispatch:\n".$m[1]."switch ((int)dispatch_handler)".$m[3]."\n");
895							break;
896						case ZEND_VM_KIND_GOTO:
897							out($f, $m[1]."goto *(void**)(EX(opline)->handler);".$m[3]."\n");
898							break;
899					}
900					break;
901				case "INTERNAL_EXECUTOR":
902					if ($kind == ZEND_VM_KIND_CALL) {
903					  // Executor is defined as a set of functions
904						out($f, $m[1]."switch (ret) {\n" .
905						        $m[1]."\tcase 1:\n" .
906						        $m[1]."\t\tEG(in_execution) = original_in_execution;\n".
907						        $m[1]."\t\treturn;\n".
908						        $m[1]."\tcase 2:\n" .
909						        $m[1]."\t\top_array = EG(active_op_array);\n".
910						        $m[1]."\t\tgoto zend_vm_enter;\n".
911						        $m[1]."\tcase 3:\n" .
912						        $m[1]."\t\texecute_data = EG(current_execute_data);\n".
913						        $m[1]."\tdefault:\n".
914						        $m[1]."\t\tbreak;\n".
915						        $m[1]."}".$m[3]."\n");
916					} else {
917					  // Emit executor code
918						gen_executor_code($f, $spec, $kind, $m[1]);
919					}
920					break;
921				case "EXTERNAL_EXECUTOR":
922					if ($kind == ZEND_VM_KIND_CALL) {
923					  // Unspecialized executor with CALL threading is the same as the
924					  // old one, so we don't need to produce code twitch
925						if (!$old || ZEND_VM_SPEC || (ZEND_VM_KIND != ZEND_VM_KIND_CALL)) {
926							// Emit executor code
927							gen_executor_code($f, $spec, $kind, $m[1]);
928						}
929					}
930					break;
931				case "INITIALIZER_NAME":
932					out($f, $m[1].$initializer_name.$m[3]."\n");
933					break;
934				case "EXTERNAL_LABELS":
935				  // Emit code that initializes zend_opcode_handlers array
936					$prolog = $m[1];
937					if ($kind == ZEND_VM_KIND_GOTO) {
938					  // Labels are defined in the executor itself, so we call it
939					  // with op_array NULL and it sets zend_opcode_handlers array
940						out($f,$prolog."TSRMLS_FETCH();\n");
941						out($f,$prolog."zend_execute(NULL TSRMLS_CC);\n");
942					} else {
943						if ($old) {
944						  // Reserving space for user-defined opcodes
945							out($f,$prolog."static opcode_handler_t labels[512] = {\n");
946						} else {
947							out($f,$prolog."static const opcode_handler_t labels[] = {\n");
948						}
949						gen_labels($f, $spec, $kind, $prolog."\t");
950						out($f,$prolog."};\n");
951						out($f,$prolog."zend_opcode_handlers = (opcode_handler_t*)labels;\n");
952						if ($old) {
953						  // Setup old executor
954							out($f,$prolog."zend_vm_old_executor = 1;\n");
955							out($f,$prolog."zend_execute = old_execute;\n");
956						}
957					}
958					break;
959				default:
960					die("ERROR: Unknown keyword ".$m[2]." in skeleton file.\n");
961			}
962		} else {
963		  // Copy the line as is
964			out($f, $line);
965		}
966	}
967}
968
969function gen_vm($def, $skel) {
970	global $definition_file, $skeleton_file, $executor_file,
971		$op_types, $list, $opcodes, $helpers, $params, $opnames;
972
973	// Load definition file
974	$in = @file($def);
975	if (!$in) {
976		die("ERROR: Can not open definition file '$def'\n");
977	}
978	// We need absolute path to definition file to use it in #line directives
979	$definition_file = realpath($def);
980
981	// Load skeleton file
982	$skl = @file($skel);
983	if (!$skl) {
984		die("ERROR: Can not open skeleton file '$skel'\n");
985	}
986	// We need absolute path to skeleton file to use it in #line directives
987	$skeleton_file = realpath($skel);
988
989	// Parse definition file into tree
990	$lineno         = 0;
991	$handler        = null;
992	$helper         = null;
993	$max_opcode_len = 0;
994	$max_opcode     = 0;
995	$export         = array();
996	foreach ($in as $line) {
997		++$lineno;
998		if (strpos($line,"ZEND_VM_HANDLER(") === 0) {
999		  // Parsing opcode handler's definition
1000			if (preg_match(
1001					"/^ZEND_VM_HANDLER\(\s*([0-9]+)\s*,\s*([A-Z_]+)\s*,\s*([A-Z|]+)\s*,\s*([A-Z|]+)\s*\)/",
1002					$line,
1003					$m) == 0) {
1004				die("ERROR ($def:$lineno): Invalid ZEND_VM_HANDLER definition.\n");
1005			}
1006			$code = (int)$m[1];
1007			$op   = $m[2];
1008			$len  = strlen($op);
1009			$op1  = array_flip(explode("|",$m[3]));
1010			$op2  = array_flip(explode("|",$m[4]));
1011
1012			if ($len > $max_opcode_len) {
1013				$max_opcode_len = $len;
1014			}
1015			if ($code > $max_opcode) {
1016				$max_opcode = $code;
1017			}
1018			if (isset($opcodes[$code])) {
1019				die("ERROR ($def:$lineno): Opcode with code '$code' is already defined.\n");
1020			}
1021			if (isset($opnames[$op])) {
1022				die("ERROR ($def:$lineno): Opcode with name '$op' is already defined.\n");
1023			}
1024			$opcodes[$code] = array("op"=>$op,"op1"=>$op1,"op2"=>$op2,"code"=>"");
1025			$opnames[$op] = $code;
1026			$handler = $code;
1027			$helper = null;
1028			$list[$lineno] = array("handler"=>$handler);
1029		} else if (strpos($line,"ZEND_VM_HELPER(") === 0) {
1030		  // Parsing helper's definition
1031			if (preg_match(
1032					"/^ZEND_VM_HELPER\(\s*([A-Za-z_]+)\s*,\s*([A-Z|]+)\s*,\s*([A-Z|]+)\s*\)/",
1033					$line,
1034					$m) == 0) {
1035				die("ERROR ($def:$lineno): Invalid ZEND_VM_HELPER definition.\n");
1036			}
1037			$helper = $m[1];
1038			$op1    = array_flip(explode("|",$m[2]));
1039			$op2    = array_flip(explode("|",$m[3]));
1040			if (isset($helpers[$helper])) {
1041				die("ERROR ($def:$lineno): Helper with name '$helper' is already defined.\n");
1042			}
1043			$helpers[$helper] = array("op1"=>$op1,"op2"=>$op2,"param"=>null,"code"=>"");
1044			$handler = null;
1045			$list[$lineno] = array("helper"=>$helper);
1046		} else if (strpos($line,"ZEND_VM_HELPER_EX(") === 0) {
1047		  // Parsing helper with parameter definition
1048			if (preg_match(
1049					"/^ZEND_VM_HELPER_EX\(\s*([A-Za-z_]+)\s*,\s*([A-Z|]+)\s*,\s*([A-Z|]+)\s*,\s*(.*)\s*\)/",
1050					$line,
1051					$m) == 0) {
1052				die("ERROR ($def:$lineno): Invalid ZEND_VM_HELPER definition.\n");
1053			}
1054			$helper = $m[1];
1055			$op1    = array_flip(explode("|",$m[2]));
1056			$op2    = array_flip(explode("|",$m[3]));
1057			$param  = $m[4];
1058			if (isset($helpers[$helper])) {
1059				die("ERROR ($def:$lineno): Helper with name '$helper' is already defined.\n");
1060			}
1061
1062			// Store parameter
1063			$params[$param] = 1;
1064
1065			$helpers[$helper] = array("op1"=>$op1,"op2"=>$op2,"param"=>$param,"code"=>"");
1066			$handler = null;
1067			$list[$lineno] = array("helper"=>$helper);
1068		} else if (strpos($line,"ZEND_VM_EXPORT_HANDLER(") === 0) {
1069			if (preg_match(
1070					"/^ZEND_VM_EXPORT_HANDLER\(\s*([A-Za-z_]+)\s*,\s*([A-Z_]+)\s*\)/",
1071					$line,
1072					$m) == 0) {
1073				die("ERROR ($def:$lineno): Invalid ZEND_VM_EXPORT_HANDLER definition.\n");
1074			}
1075			if (!isset($opnames[$m[2]])) {
1076				die("ERROR ($def:$lineno): opcode '{$m[2]}' is not defined.\n");
1077			}
1078			$export[] = array("handler",$m[1],$m[2]);
1079		} else if (strpos($line,"ZEND_VM_EXPORT_HELPER(") === 0) {
1080			if (preg_match(
1081					"/^ZEND_VM_EXPORT_HELPER\(\s*([A-Za-z_]+)\s*,\s*([A-Za-z_]+)\s*\)/",
1082					$line,
1083					$m) == 0) {
1084				die("ERROR ($def:$lineno): Invalid ZEND_VM_EXPORT_HELPER definition.\n");
1085			}
1086			if (!isset($helpers[$m[2]])) {
1087				die("ERROR ($def:$lineno): helper '{$m[2]}' is not defined.\n");
1088			}
1089			$export[] = array("helper",$m[1],$m[2]);
1090		} else if ($handler !== null) {
1091		  // Add line of code to current opcode handler
1092			$opcodes[$handler]["code"] .= $line;
1093		} else if ($helper !== null) {
1094		  // Add line of code to current helper
1095			$helpers[$helper]["code"] .= $line;
1096		}
1097	}
1098
1099	ksort($opcodes);
1100
1101	// Search for opcode handlers those are used by other opcode handlers
1102	foreach ($opcodes as $dsc) {
1103		if (preg_match("/ZEND_VM_DISPATCH_TO_HANDLER\(\s*([A-Z_]*)\s*\)/m", $dsc["code"], $m)) {
1104			$op = $m[1];
1105			if (!isset($opnames[$op])) {
1106				die("ERROR ($def:$lineno): Opcode with name '$op' is not defined.\n");
1107			}
1108			$code = $opnames[$op];
1109			$opcodes[$code]['use'] = 1;
1110		}
1111	}
1112
1113	// Generate opcode #defines (zend_vm_opcodes.h)
1114	$code_len = strlen((string)$max_opcode);
1115	$f = fopen("zend_vm_opcodes.h", "w+") or die("ERROR: Cannot create zend_vm_opcodes.h\n");
1116
1117	// Insert header
1118	out($f, $GLOBALS['header_text']);
1119
1120	foreach ($opcodes as $code => $dsc) {
1121		$code = str_pad((string)$code,$code_len," ",STR_PAD_LEFT);
1122		$op = str_pad($dsc["op"],$max_opcode_len);
1123		fputs($f,"#define $op $code\n");
1124	}
1125	fclose($f);
1126	echo "zend_vm_opcodes.h generated successfully.\n";
1127
1128	// Generate zend_vm_execute.h
1129	$f = fopen("zend_vm_execute.h", "w+") or die("ERROR: Cannot create zend_vm_execute.h\n");
1130	$executor_file = realpath("zend_vm_execute.h");
1131
1132	// Insert header
1133	out($f, $GLOBALS['header_text']);
1134
1135	// Suppress free_op1 warnings on Windows
1136	out($f, "#ifdef ZEND_WIN32\n# pragma warning(once : 4101)\n#endif\n");
1137
1138	// Support for ZEND_USER_OPCODE
1139	out($f, "static user_opcode_handler_t zend_user_opcode_handlers[256] = {");
1140	for ($i = 0; $i < 255; ++$i) {
1141		out($f, "(user_opcode_handler_t)NULL,");
1142	}
1143	out($f, "(user_opcode_handler_t)NULL};\n\n");
1144
1145	out($f, "static zend_uchar zend_user_opcodes[256] = {");
1146	for ($i = 0; $i < 255; ++$i) {
1147		out($f, "$i,");
1148	}
1149	out($f, "255};\n\n");
1150
1151	// Generate specialized executor
1152	gen_executor($f, $skl, ZEND_VM_SPEC, ZEND_VM_KIND, "execute", "zend_init_opcodes_handlers", 0);
1153
1154	// Generate un-specialized executor
1155	if (ZEND_VM_OLD_EXECUTOR) {
1156		out($f,"\n/* Old executor */\n\n");
1157		out($f,"#undef EX\n");
1158		out($f,"#define EX(element) execute_data.element\n\n");
1159		out($f,"#undef ZEND_VM_CONTINUE\n\n");
1160		out($f,"#undef ZEND_VM_RETURN\n\n");
1161		out($f,"#undef ZEND_VM_ENTER\n\n");
1162		out($f,"#undef ZEND_VM_LEAVE\n\n");
1163		out($f,"#undef ZEND_VM_DISPATCH\n\n");
1164		out($f,"#undef ZEND_OPCODE_HANDLER_ARGS_PASSTHRU_INTERNAL\n\n");
1165		gen_executor($f, $skl, 0, ZEND_VM_KIND_CALL, "old_execute", "zend_vm_use_old_executor", 1);
1166	}
1167
1168	// Generate zend_vm_get_opcode_handler() function
1169	out($f, "static opcode_handler_t zend_vm_get_opcode_handler(zend_uchar opcode, zend_op* op)\n");
1170	out($f, "{\n");
1171	if (!ZEND_VM_SPEC) {
1172		out($f, "\treturn zend_opcode_handlers[opcode];\n");
1173	} else {
1174		if (ZEND_VM_OLD_EXECUTOR) {
1175			out($f, "\tif (zend_vm_old_executor) {\n");
1176			out($f, "\t\treturn zend_opcode_handlers[opcode];\n");
1177			out($f, "\t} else {\n");
1178		}
1179		out($f, "\t\tstatic const int zend_vm_decode[] = {\n");
1180		out($f, "\t\t\t_UNUSED_CODE, /* 0              */\n");
1181		out($f, "\t\t\t_CONST_CODE,  /* 1 = IS_CONST   */\n");
1182		out($f, "\t\t\t_TMP_CODE,    /* 2 = IS_TMP_VAR */\n");
1183		out($f, "\t\t\t_UNUSED_CODE, /* 3              */\n");
1184		out($f, "\t\t\t_VAR_CODE,    /* 4 = IS_VAR     */\n");
1185		out($f, "\t\t\t_UNUSED_CODE, /* 5              */\n");
1186		out($f, "\t\t\t_UNUSED_CODE, /* 6              */\n");
1187		out($f, "\t\t\t_UNUSED_CODE, /* 7              */\n");
1188		out($f, "\t\t\t_UNUSED_CODE, /* 8 = IS_UNUSED  */\n");
1189		out($f, "\t\t\t_UNUSED_CODE, /* 9              */\n");
1190		out($f, "\t\t\t_UNUSED_CODE, /* 10             */\n");
1191		out($f, "\t\t\t_UNUSED_CODE, /* 11             */\n");
1192		out($f, "\t\t\t_UNUSED_CODE, /* 12             */\n");
1193		out($f, "\t\t\t_UNUSED_CODE, /* 13             */\n");
1194		out($f, "\t\t\t_UNUSED_CODE, /* 14             */\n");
1195		out($f, "\t\t\t_UNUSED_CODE, /* 15             */\n");
1196		out($f, "\t\t\t_CV_CODE      /* 16 = IS_CV     */\n");
1197		out($f, "\t\t};\n");
1198		out($f, "\t\treturn zend_opcode_handlers[opcode * 25 + zend_vm_decode[op->op1.op_type] * 5 + zend_vm_decode[op->op2.op_type]];\n");
1199		if (ZEND_VM_OLD_EXECUTOR) {
1200			out($f, "\t}\n");
1201		}
1202	}
1203	out($f, "}\n\n");
1204
1205	// Generate zend_vm_get_opcode_handler() function
1206	out($f, "ZEND_API void zend_vm_set_opcode_handler(zend_op* op)\n");
1207	out($f, "{\n");
1208	out($f, "\top->handler = zend_vm_get_opcode_handler(zend_user_opcodes[op->opcode], op);\n");
1209	out($f, "}\n\n");
1210
1211	// Export handlers and helpers
1212	if (count($export) > 0 &&
1213	    !ZEND_VM_OLD_EXECUTOR &&
1214	    ZEND_VM_KIND != ZEND_VM_KIND_CALL) {
1215		out($f,"#undef EX\n");
1216		out($f,"#define EX(element) execute_data->element\n\n");
1217		out($f,"#undef ZEND_VM_CONTINUE\n");
1218		out($f,"#undef ZEND_VM_RETURN\n");
1219		out($f,"#undef ZEND_VM_ENTER\n");
1220		out($f,"#undef ZEND_VM_LEAVE\n");
1221		out($f,"#undef ZEND_VM_DISPATCH\n");
1222		out($f,"#undef ZEND_OPCODE_HANDLER_ARGS_PASSTHRU_INTERNAL\n\n");
1223		out($f,"#define ZEND_VM_CONTINUE()   return 0\n");
1224		out($f,"#define ZEND_VM_RETURN()     return 1\n");
1225		out($f,"#define ZEND_VM_ENTER()      return 2\n");
1226		out($f,"#define ZEND_VM_LEAVE()      return 3\n");
1227		out($f,"#define ZEND_VM_DISPATCH(opcode, opline) return zend_vm_get_opcode_handler(opcode, opline)(ZEND_OPCODE_HANDLER_ARGS_PASSTHRU);\n\n");
1228		out($f,"#define ZEND_OPCODE_HANDLER_ARGS_PASSTHRU_INTERNAL execute_data TSRMLS_CC\n\n");
1229	}
1230	foreach ($export as $dsk) {
1231		list($kind, $func, $name) = $dsk;
1232		out($f, "ZEND_API int $func(");
1233		if ($kind == "handler") {
1234			out($f, "ZEND_OPCODE_HANDLER_ARGS)\n");
1235			$code = $opcodes[$opnames[$name]]['code'];
1236		} else {
1237			$h = $helpers[$name];
1238			if ($h['param'] == null) {
1239				out($f, "ZEND_OPCODE_HANDLER_ARGS)\n");
1240			} else {
1241				out($f, $h['param']. ", ZEND_OPCODE_HANDLER_ARGS)\n");
1242			}
1243			$code = $h['code'];
1244		}
1245		$done = 0;
1246		if (ZEND_VM_OLD_EXECUTOR) {
1247			if ($kind == "handler") {
1248				out($f, "{\n\treturn ".$name."_HANDLER(ZEND_OPCODE_HANDLER_ARGS_PASSTHRU);\n}\n\n");
1249				$done = 1;
1250			} else if ($helpers[$name]["param"] == null) {
1251				out($f, "{\n\treturn ".$name."(ZEND_OPCODE_HANDLER_ARGS_PASSTHRU);\n}\n\n");
1252				$done = 1;
1253			}
1254		} else if (ZEND_VM_KIND == ZEND_VM_KIND_CALL) {
1255			if ($kind == "handler") {
1256				$op = $opcodes[$opnames[$name]];
1257				if (isset($op['op1']["ANY"]) && isset($op['op2']["ANY"])) {
1258					out($f, "{\n\treturn ".$name.(ZEND_VM_SPEC?"_SPEC":"")."_HANDLER(ZEND_OPCODE_HANDLER_ARGS_PASSTHRU);\n}\n\n");
1259					$done = 1;
1260				}
1261			} else if ($helpers[$name]["param"] == null) {
1262				$h = $helpers[$name];
1263				if (isset($h['op1']["ANY"]) && isset($h['op2']["ANY"])) {
1264					out($f, "{\n\treturn ".$name.(ZEND_VM_SPEC?"_SPEC":"")."(ZEND_OPCODE_HANDLER_ARGS_PASSTHRU);\n}\n\n");
1265					$done = 1;
1266				}
1267			}
1268		}
1269		if (!$done) {
1270			gen_code($f, 0, ZEND_VM_KIND_CALL, 1, $code, 'ANY', 'ANY', $name);
1271		}
1272	}
1273
1274	fclose($f);
1275	echo "zend_vm_execute.h generated successfully.\n";
1276}
1277
1278function usage() {
1279	echo("\nUsage: php zend_vm_gen.php [options]\n".
1280	     "\nOptions:".
1281	     "\n  --with-vm-kind=CALL|SWITCH|GOTO - select threading model (default is CALL)".
1282	     "\n  --without-specializer           - disable executor specialization".
1283	     "\n  --with-old-executor             - enable old executor".
1284	     "\n  --with-lines                    - enable #line directives".
1285	     "\n\n");
1286}
1287
1288// Parse arguments
1289for ($i = 1;  $i < $argc; $i++) {
1290	if (strpos($argv[$i],"--with-vm-kind=") === 0) {
1291		$kind = substr($argv[$i], strlen("--with-vm-kind="));
1292		switch ($kind) {
1293			case "CALL":
1294				define("ZEND_VM_KIND", ZEND_VM_KIND_CALL);
1295				break;
1296			case "SWITCH":
1297				define("ZEND_VM_KIND", ZEND_VM_KIND_SWITCH);
1298				break;
1299			case "GOTO":
1300				define("ZEND_VM_KIND", ZEND_VM_KIND_GOTO);
1301				break;
1302			default:
1303				echo("ERROR: Invalid vm kind '$kind'\n");
1304				usage();
1305				die();
1306		}
1307	} else if ($argv[$i] == "--without-specializer") {
1308	  // Disabling specialization
1309		define("ZEND_VM_SPEC", 0);
1310	} else if ($argv[$i] == "--with-old-executor") {
1311	  // Disabling code for old-style executor
1312		define("ZEND_VM_OLD_EXECUTOR", 1);
1313	} else if ($argv[$i] == "--with-lines") {
1314		// Enabling debuging using original zend_vm_def.h
1315		define("ZEND_VM_LINES", 1);
1316	} else if ($argv[$i] == "--help") {
1317		usage();
1318		exit();
1319	} else {
1320		echo("ERROR: Invalid option '".$argv[$i]."'\n");
1321		usage();
1322		die();
1323	}
1324}
1325
1326// Using defaults
1327if (!defined("ZEND_VM_KIND")) {
1328  // Using CALL threading by default
1329	define("ZEND_VM_KIND", ZEND_VM_KIND_CALL);
1330}
1331if (!defined("ZEND_VM_SPEC")) {
1332  // Using specialized executor by default
1333	define("ZEND_VM_SPEC", 1);
1334}
1335if (!defined("ZEND_VM_OLD_EXECUTOR")) {
1336  // Include old-style executor by default
1337	define("ZEND_VM_OLD_EXECUTOR", 0);
1338}
1339if (!defined("ZEND_VM_LINES")) {
1340  // Disabling #line directives
1341	define("ZEND_VM_LINES", 0);
1342}
1343
1344gen_vm("zend_vm_def.h", "zend_vm_execute.skl");
1345
1346?>
1347