cvs: pear /PECL/bcompiler CREDITS EXPERIMENTAL Makefile.in.old README bcompiler.c bcompiler.dsp bcompiler.xml config.m4 config.m4.old php_bcompiler.h
/PECL/bcompiler/examples bcompiler.php bcompiler_parse.php bcompiler_read.php
| From: | Alan Knowles | Date: | Tue, 23 Jul 2002 06:55:57 +0000 |
| Subject: | cvs: pear /PECL/bcompiler CREDITS EXPERIMENTAL Makefile.in.old README bcompiler.c bcompiler.dsp bcompiler.xml config.m4 config.m4.old php_bcompiler.h /PECL/bcompiler/examples bcompiler.php bcompiler_parse.php bcompiler_read.php |
||
| Groups: | php.pear.cvs | ||
| Request: | Send a blank email to pear-cvs+get-5290@lists.php.net to get a copy of this message | ||
alan_k Tue Jul 23 02:55:57 2002 EDT
Added files:
/pear/PECL/bcompiler CREDITS EXPERIMENTAL Makefile.in.old README
bcompiler.c bcompiler.dsp bcompiler.xml
config.m4 config.m4.old php_bcompiler.h
/pear/PECL/bcompiler/examples bcompiler.php bcompiler_parse.php
bcompiler_read.php
Log:
First commit of bytecode compiler
Index: pear/PECL/bcompiler/Makefile.in.old +++ pear/PECL/bcompiler/Makefile.in.old LTLIBRARY_NAME = libbcompiler.la LTLIBRARY_SOURCES = bcompiler.c LTLIBRARY_SHARED_NAME = bcompiler.la LTLIBRARY_SHARED_LIBADD = $(BCOMPILER_SHARED_LIBADD) include $(top_srcdir)/build/dynlib.mk Index: pear/PECL/bcompiler/bcompiler.c +++ pear/PECL/bcompiler/bcompiler.c /* ================================================================== * PHP bcompiler Based on APC Cache * Copyright (c) 2000-2001 Community Connect, Inc. * All rights reserved. * ================================================================== * This source code is made available free and without charge subject * to the terms of the QPL as detailed in bundled LICENSE file, which * is also available at http://apc.communityconnect.com/LICENSE. * ================================================================== * php module by Alan Knowles <alan@akbkhome.com> * Daniel Cowgill <dan@mail.communityconnect.com> * George Schlossnagle <george@lethargy.org> * Mike Bretz <mike@metropolis-ag.de> * ================================================================== */ /* __header_here__ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/file.h" #include "php_bcompiler.h" #include "zend.h" #include <stdlib.h> #include <assert.h> #define BCOMPILER_VERSION "0.3" #ifdef PHP_HAVE_STREAMS #define BCOMPILER_STREAMS "s" #else #define BCOMPILER_STREAMS "" #endif #define BCOMPILER_MAGIC_HEADER "bcompiler v" BCOMPILER_VERSION BCOMPILER_STREAMS #define DEBUGLEVEL 0 #if DEBUGLEVEL #define BCOMPILER_DEBUG(args) (printf("DEBUG: "), printf args) #else #define BCOMPILER_DEBUG(args) #endif // If you declare any globals in php_compiler.h uncomment this: ZEND_DECLARE_MODULE_GLOBALS(bcompiler) /* {{{ bcompiler_functions[] * * Every user visible function must have an entry in bcompiler_functions[]. */ function_entry bcompiler_functions[] = { PHP_FE(bcompile_write_header, NULL) /* bCompiler a class and return data.*/ PHP_FE(bcompile_write_class, NULL) /* bCompiler a class and return data.*/ PHP_FE(bcompile_write_footer, NULL) /* bCompiler a class and return data.*/ PHP_FE(bcompile_write_exe_footer, NULL) /* bCompiler a class and return data.*/ PHP_FE(bcompile_read, NULL) /* bCompiler a class and return data.*/ PHP_FE(bcompile_load, NULL) /* bCompiler a class and return data.*/ PHP_FE(bcompile_load_exe, NULL) /* bCompiler a class and return data.*/ PHP_FE(bcompile_parse_class, NULL) /* bCompiler a class and return data.*/ /* __function_entries_here__ */ {NULL, NULL, NULL} /* Must be the last line in compiler_functions[] */ }; /* }}} */ /* {{{ bcompiler_module_entry */ zend_module_entry bcompiler_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "bcompiler", bcompiler_functions, PHP_MINIT(bcompiler), PHP_MSHUTDOWN(bcompiler), PHP_RINIT(bcompiler), /* Replace with NULL if there's nothing to do at request start */ PHP_RSHUTDOWN(bcompiler), /* Replace with NULL if there's nothing to do at request end */ PHP_MINFO(bcompiler), #if ZEND_MODULE_API_NO >= 20010901 BCOMPILER_VERSION BCOMPILER_STREAMS, /* Replace with version number for your extension */ #endif STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_BCOMPILER ZEND_GET_MODULE(bcompiler) #endif /* {{{ PHP_INI */ /* Remove comments and fill if you need to have entries in php.ini PHP_INI_BEGIN() STD_PHP_INI_ENTRY("bcompiler.global_value", "42", PHP_INI_ALL, OnUpdateInt, global_value, zend_bcompiler_globals, bcompiler_globals) STD_PHP_INI_ENTRY("bcompiler.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_bcompiler_globals, bcompiler_globals) PHP_INI_END() */ /* }}} */ enum { START_SIZE = 1, GROW_FACTOR = 2 }; /* {{{ php_bcompiler_init_globals */ static void php_bcompiler_init_globals(zend_bcompiler_globals *bcompiler_globals) { /*if (bcompiler_globals->dst == 0) { bcompiler_globals->dstsize = START_SIZE; bcompiler_globals->dst = (char*) malloc(bcompiler_globals->dstsize); } bcompiler_globals->dstpos = 0; */ bcompiler_globals->buffer = (char*) emalloc(START_SIZE); bcompiler_globals->stream = NULL; bcompiler_globals->callback = NULL; bcompiler_globals->callback_value = NULL; bcompiler_globals->callback_key = "NONE"; } /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(bcompiler) { // If you have INI entries, uncomment these lines ZEND_INIT_MODULE_GLOBALS(bcompiler, php_bcompiler_init_globals, NULL); //REGISTER_INI_ENTRIES(); return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(bcompiler) { // uncomment this line if you have INI entries //UNREGISTER_INI_ENTRIES(); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request start */ /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(bcompiler) { return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request end */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(bcompiler) { efree(BCOMPILERG(buffer)); return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(bcompiler) { php_info_print_table_start(); php_info_print_table_header(2, "bcompiler support", "enabled"); php_info_print_table_end(); /* Remove comments if you have entries in php.ini DISPLAY_INI_ENTRIES(); */ } /* }}} */ /* ---------------------------------------------------------------------------- * * MAJOR DEFINES * * * ---------------------------------------------------------------------------- */ /* These are flags that define start points in the decompile code.. */ #define BCOMPILER_CLASS_ENTRY 1 /* type: Fundamental operations */ /* ------------- STREAM BASED - eg. => php 4.3 -------------- */ #ifdef PHP_HAVE_STREAMS /* SERIALIZE_SCALAR: write a scalar value to dst */ #define SERIALIZE_SCALAR(x, type) { \ if (BCOMPILERG(stream) != NULL) { \ char _buf[255]; \ BCOMPILER_DEBUG((" scalar: %i\n",(type) x)); \ *(type*) _buf = x; \ php_stream_write((php_stream *) BCOMPILERG(stream) , _buf, (size_t) apclib_alignword_int(sizeof(type))); \ } \ } /* DESERIALIZE_SCALAR: read a scalar value from src */ #define DESERIALIZE_SCALAR(xp, type) { \ if (php_stream_eof(BCOMPILERG(stream))) { \ php_error(E_WARNING, "bcompiler: Read Past End of File"); \ return; \ } \ BCOMPILERG(buffer) = (char*) erealloc(BCOMPILERG(buffer), sizeof(type) + 1); \ php_stream_read((php_stream *) BCOMPILERG(stream) , BCOMPILERG(buffer) , (size_t) apclib_alignword_int(sizeof(type))); \ *(xp) = *((type*) BCOMPILERG(buffer)); \ BCOMPILER_DEBUG((" read : %i \n",(type) *(xp))); \ } /* STORE_BYTES: memcpy wrapper, writes to dst buffer */ #define STORE_BYTES(bytes, n) { \ if (BCOMPILERG(stream) != NULL) { \ BCOMPILER_DEBUG((" STORE: %s \n",bytes)); \ php_stream_write((php_stream *) BCOMPILERG(stream) , (char *)bytes, n); \ } \ } /* LOAD_BYTES: memcpy wrapper, reads from src buffer */ #define LOAD_BYTES(bytes, n) { \ if (php_stream_eof(BCOMPILERG(stream))) { \ php_error(E_WARNING, "bcompiler: Read Past End of File"); \ return; \ } \ BCOMPILERG(buffer) = (char*) erealloc(BCOMPILERG(buffer), n + 1); \ php_stream_read((php_stream *) BCOMPILERG(stream) , BCOMPILERG(buffer) , n); \ memcpy((char*)bytes, BCOMPILERG(buffer), n); \ BCOMPILER_DEBUG(("Got: %s\n",(char*)BCOMPILERG(buffer))); \ } #else /* ------------- NON STREAM BASED - eg. before php 4.3 -------------- */ /* SERIALIZE_SCALAR: write a scalar value to dst */ #define SERIALIZE_SCALAR(x, type) { \ if (BCOMPILERG(stream) != NULL) { \ char _buf[255]; \ BCOMPILER_DEBUG((" scalar: %i\n",(type) x)); \ *(type*) _buf = x; \ fwrite(_buf, 1, (size_t) apclib_alignword_int(sizeof(type)), (FILE*) BCOMPILERG(stream)); \ } \ } /* DESERIALIZE_SCALAR: read a scalar value from src */ #define DESERIALIZE_SCALAR(xp, type) { \ if (php_stream_eof(BCOMPILERG(stream))) { \ php_error(E_WARNING, "bcompiler: Read Past End of File"); \ return; \ } \ BCOMPILERG(buffer) = (char*) erealloc(BCOMPILERG(buffer), sizeof(type) + 1); \ fread(BCOMPILERG(buffer) , 1, (size_t) apclib_alignword_int(sizeof(type)), (FILE*) BCOMPILERG(stream)); \ *(xp) = *((type*) BCOMPILERG(buffer)); \ BCOMPILER_DEBUG((" read : %i \n",(type) *(xp))); \ } /* STORE_BYTES: memcpy wrapper, writes to dst buffer */ #define STORE_BYTES(bytes, n) { \ if (BCOMPILERG(stream) != NULL) { \ BCOMPILER_DEBUG((" STORE: %s \n",bytes)); \ fwrite((char *)bytes, 1, n, (FILE*) BCOMPILERG(stream)); \ } \ } /* LOAD_BYTES: memcpy wrapper, reads from src buffer */ #define LOAD_BYTES(bytes, n) { \ if (php_stream_eof(BCOMPILERG(stream))) { \ php_error(E_WARNING, "bcompiler: Read Past End of File"); \ return; \ } \ BCOMPILERG(buffer) = (char*) erealloc(BCOMPILERG(buffer), n + 1); \ fread(BCOMPILERG(buffer) ,1, n, (FILE*) BCOMPILERG(stream)); \ memcpy((char*)bytes, BCOMPILERG(buffer), n); \ BCOMPILER_DEBUG(("Got: %s\n",(char*)BCOMPILERG(buffer))); \ } #endif /* -------------------- Callbacks for bcompiler_parse() ------------------- */ #define CALLBACK_ADD_STRING(str,strlen) { \ if (BCOMPILERG(callback) != NULL) { \ add_assoc_stringl(BCOMPILERG(callback_value), BCOMPILERG(callback_key), str, strlen , 1); \ } \ } #define CALLBACK_ADD_KEY_STRING(key, str,strlen) { \ if (BCOMPILERG(callback) != NULL) { \ add_assoc_stringl(BCOMPILERG(callback_value), key, str, strlen , 1); \ } \ } #define CALLBACK_ADD_STRING_LONG(str,val) { \ char out[255]; \ int len; \ len = sprintf(out,str,val); \ if (BCOMPILERG(callback) != NULL) { \ add_assoc_stringl(BCOMPILERG(callback_value), BCOMPILERG(callback_key), out, len , 1); \ } \ } #define CALLBACK_ADD_LONG(key, val) { \ if (BCOMPILERG(callback) != NULL) { \ add_assoc_long(BCOMPILERG(callback_value), key, val); \ } \ } #define CALLBACK_ADD_SUB_LONG(kkey, val) { \ char out[255]; \ strcpy(out, BCOMPILERG(callback_key)); \ sprintf(out,"%s.%s",out, kkey); \ if (BCOMPILERG(callback) != NULL) { \ add_assoc_long(BCOMPILERG(callback_value), out, val); \ } \ } #define CALLBACK_ADD_SUB_DOUBLE(kkey, val) { \ char out[255]; \ strcpy(out, BCOMPILERG(callback_key)); \ sprintf(out,"%s.%s",out, kkey); \ if (BCOMPILERG(callback) != NULL) { \ add_assoc_double(BCOMPILERG(callback_value), out, val); \ } \ } #define CALLBACK_ADD_SUB_STRING(kkey, sval,slen) { \ char out[255]; \ strcpy(out, BCOMPILERG(callback_key)); \ sprintf(out,"%s.%s",out, kkey); \ if (BCOMPILERG(callback) != NULL) { \ add_assoc_stringl(BCOMPILERG(callback_value), out, sval ,slen , 1); \ } \ } #define CALLBACK_ADD_DOUBLE(key,val) { \ if (BCOMPILERG(callback) != NULL) { \ add_assoc_double(BCOMPILERG(callback_value), key, val); \ } \ } /* CALLBACK START (opcode) */ #define CALLBACK_START(code) { \ if (BCOMPILERG(callback) != NULL) { \ char *str; \ MAKE_STD_ZVAL(BCOMPILERG(callback_value)); \ array_init(BCOMPILERG(callback_value)); \ /*Optype - */ \ str = (char *) getOpcodeName(code ); \ add_assoc_long(BCOMPILERG(callback_value), "OPCODE", code); \ add_assoc_stringl(BCOMPILERG(callback_value), "OPCODE_STR", str, strlen(str) , 1); \ } \ } #define CALLBACK_END() { \ zval myretval; \ zval *sendval; \ if (BCOMPILERG(callback) != NULL) { \ sendval = BCOMPILERG(callback_value); \ zval_copy_ctor(sendval); \ if(!call_user_function( EG(function_table), NULL, BCOMPILERG(callback), &myretval, 1, &sendval TSRMLS_CC )) { \ zval_dtor(BCOMPILERG(callback_value)); \ } \ } \ } /* ---------------------------------------------------------------------------- * * function defs - putting this in .h doesnt work. * * * ---------------------------------------------------------------------------- */ /* {{{ proto boolean bcompile_write_class(stream out | filehandle, string class_name) Writes compiled data to stream*/ PHP_FUNCTION(bcompile_write_class) { char *class_name = NULL; int class_len; zend_class_entry *ce = NULL; zval *rsrc; void *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &rsrc, &class_name, &class_len) == FAILURE) { return; } #ifdef PHP_HAVE_STREAMS ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_stream()); #else ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_fopen()); #endif zend_str_tolower(class_name, class_len); zend_hash_find(EG(class_table), class_name, class_len+1, (void **)&ce); if (!ce) { RETURN_NULL(); } BCOMPILERG(stream) = stream; BCOMPILERG(callback) = NULL; SERIALIZE_SCALAR(BCOMPILER_CLASS_ENTRY, char) apc_serialize_zend_class_entry(ce TSRMLS_CC); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean bcompile_parse_class(callback, string class_name) Writes compiled data to stream*/ PHP_FUNCTION(bcompile_parse_class) { char *class_name = NULL; int class_len; zend_class_entry *ce = NULL; zval *rsrc; zval *callback = NULL; void *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zs", &callback, &class_name, &class_len) == FAILURE) { return; } zend_str_tolower(class_name, class_len); zend_hash_find(EG(class_table), class_name, class_len+1, (void **)&ce); if (!ce) { RETURN_NULL(); } BCOMPILERG(callback) = callback; BCOMPILERG(stream) = NULL; apc_serialize_zend_class_entry(ce TSRMLS_CC); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean bcompiler_write_header(stream out) Writes the start flag*/ PHP_FUNCTION(bcompile_write_header) { char *class_name = NULL; int class_len; zend_class_entry *ce = NULL; zval *rsrc; void *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &rsrc) == FAILURE) { return; } #ifdef PHP_HAVE_STREAMS ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_stream()); #else ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_fopen()); #endif BCOMPILERG(stream) = stream; apc_serialize_magic(TSRMLS_CC); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean bcompiler_write_end(stream out) Writes the end zero*/ PHP_FUNCTION(bcompile_write_footer) { char *class_name = NULL; int class_len; zend_class_entry *ce = NULL; zval *rsrc; void *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &rsrc) == FAILURE) { return; } #ifdef PHP_HAVE_STREAMS ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_stream()); #else ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_fopen()); #endif BCOMPILERG(stream) = stream; SERIALIZE_SCALAR(0, char); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean bcompile_class(stream out, int start_pos) Writes compiled data to stream*/ PHP_FUNCTION(bcompile_write_exe_footer) { char *class_name = NULL; int class_len; zend_class_entry *ce = NULL; zval *rsrc; int start; void *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &rsrc, &start) == FAILURE) { return; } #ifdef PHP_HAVE_STREAMS ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_stream()); #else ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_fopen()); #endif BCOMPILERG(stream) = stream; SERIALIZE_SCALAR(start, int); apc_serialize_magic(TSRMLS_CC); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean bcompile_read(stream in) Reads compiled data from stream*/ PHP_FUNCTION(bcompile_read) { char *class_name = NULL; int class_len =0; zval *rsrc; int test =0; char item; void *stream; zend_class_entry* zc; zend_class_entry *ce = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &rsrc) == FAILURE) { return; } #ifdef PHP_HAVE_STREAMS ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_stream()); #else ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_fopen()); #endif BCOMPILERG(stream) = stream; test = apc_deserialize_magic(TSRMLS_CC); if (test != 0) { php_error(E_WARNING, "Could not find Magic header in stream"); return; } BCOMPILER_DEBUG(("STARTING CLASS\n")); bcompiler_read( TSRMLS_CC); RETURN_TRUE; } /* {{{ proto boolean bcompile_load(bziped file) Reads compiled data bziped file*/ PHP_FUNCTION(bcompile_load) { void *stream = NULL; int test =0; zval *bzopen_mode; zval *rsrc; zval **args[2]; // used for call array zval *zbzopen; // zval for "bzopen" zval *zfilename; zval *zmode; /* recive args */ char *filename; int filename_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &filename,&filename_len) == FAILURE) { return; } MAKE_STD_ZVAL(zbzopen); #ifdef PHP_HAVE_STREAMS ZVAL_STRING(zbzopen, "bzopen", 1); #else ZVAL_STRING(zbzopen, "fopen", 1); #endif MAKE_STD_ZVAL(zfilename); ZVAL_STRING(zfilename, filename, 1); args[0] = &zfilename; MAKE_STD_ZVAL(zmode); ZVAL_STRING(zmode, "r", 1); args[1] = &zmode; call_user_function_ex(CG(function_table), NULL,zbzopen, &rsrc, 2, args, 0, NULL TSRMLS_CC ); #ifdef PHP_HAVE_STREAMS ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_stream()); #else ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_fopen()); #endif BCOMPILERG(stream) = stream; test = apc_deserialize_magic(TSRMLS_CC); if (test != 0) { php_error(E_WARNING, "Could not find Magic header in stream"); return; } bcompiler_read( TSRMLS_CC); #ifdef PHP_HAVE_STREAMS php_stream_close(stream); #else fclose((FILE *)stream); #endif RETURN_TRUE; } /* }}} */ /* {{{ proto boolean bcompile_load(bziped file) Reads compiled data bziped file*/ PHP_FUNCTION(bcompile_load_exe) { void *stream = NULL; int test =0; zval *bzopen_mode; zval *rsrc; zval *rsrc2; zval **args[2]; // used for call array zval *zbzopen; // zval for "bzopen" zval *zfopen; // zval for "bzopen" zval *zfilename; zval *zmode; /* recive args */ char *filename; int filename_len; long pos; //offset to use if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &filename,&filename_len) == FAILURE) { return; } MAKE_STD_ZVAL(zfopen); ZVAL_STRING(zfopen, "fopen", 1); MAKE_STD_ZVAL(zfilename); ZVAL_STRING(zfilename, filename, 1); args[0] = &zfilename; MAKE_STD_ZVAL(zmode); ZVAL_STRING(zmode, "r", 1); args[1] = &zmode; call_user_function_ex(CG(function_table), NULL, zfopen, &rsrc, 2, args, 0, NULL TSRMLS_CC ); #ifdef PHP_HAVE_STREAMS ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_stream()); #else ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_fopen()); #endif BCOMPILERG(stream) = stream; pos = (long) ((strlen(BCOMPILER_MAGIC_HEADER)+4) * -1); // +4 cause we need to read the string size BCOMPILER_DEBUG(("move to start: %d\n", pos)); #ifdef PHP_HAVE_STREAMS php_stream_seek(stream, pos , SEEK_END); #else fseek((FILE*)stream, pos, SEEK_END); #endif test = apc_deserialize_magic(TSRMLS_CC); if (test != 0) { php_error(E_WARNING, "Could not find Magic header in stream"); return; } /* now read the length */ pos = pos - 4; BCOMPILER_DEBUG(("move to start: %d\n", pos)); #ifdef PHP_HAVE_STREAMS php_stream_seek(stream, pos , SEEK_END); #else fseek((FILE*)stream, pos, SEEK_END); #endif DESERIALIZE_SCALAR(&pos, int); BCOMPILER_DEBUG(("move to start: %d\n", pos)); #ifdef PHP_HAVE_STREAMS php_stream_seek(stream, pos , SEEK_SET); #else fseek((FILE*)stream, pos, SEEK_SET); #endif MAKE_STD_ZVAL(zbzopen); #ifdef PHP_HAVE_STREAMS ZVAL_STRING(zbzopen, "bzopen", 1); #else ZVAL_STRING(zbzopen, "fopen", 1); #endif args[0] = &rsrc; MAKE_STD_ZVAL(zmode); ZVAL_STRING(zmode, "r", 1); args[1] = &zmode; call_user_function_ex(CG(function_table), NULL,zbzopen, &rsrc2, 2, args, 0, NULL TSRMLS_CC ); #ifdef PHP_HAVE_STREAMS ZEND_FETCH_RESOURCE(stream, void *, &rsrc2, -1, "File-Handle", php_file_le_stream()); #else ZEND_FETCH_RESOURCE(stream, void *, &rsrc2, -1, "File-Handle", php_file_le_fopen()); #endif BCOMPILERG(stream) = stream; test = apc_deserialize_magic(TSRMLS_CC); if (test != 0) { php_error(E_WARNING, "Could not find Magic header in stream"); return; } bcompiler_read( TSRMLS_CC); #ifdef PHP_HAVE_STREAMS php_stream_close(stream); #else fclose((FILE *)stream); #endif RETURN_TRUE; } /* }}} */ void bcompiler_read(TSRMLS_DC) { char item; zend_class_entry* zc; zend_class_entry *ce = NULL; DESERIALIZE_SCALAR(&item, char); while (item) { switch (item) { case BCOMPILER_CLASS_ENTRY: BCOMPILER_DEBUG(("STARTING CLASS\n")); apc_create_zend_class_entry(&zc TSRMLS_CC); /* is it in the class table already? */ zend_hash_find(EG(class_table), zc->name, zc->name_length+1, (void **)&ce); if (ce) { php_error(E_WARNING, "Could not redefine class %s", zc->name); efree(zc); } else { (*zc->refcount)++; BCOMPILER_DEBUG(("ADDING %s \n",zc->name)); zend_hash_add(EG(class_table), zc->name, zc->name_length+1, zc, sizeof(zend_class_entry), NULL); } } DESERIALIZE_SCALAR(&item, char); } } /* ---------------------------------------------------------------------------- * * from apc_lib.h -- GENERALLY STUFF that doesnt need GLOBALS! * * * ---------------------------------------------------------------------------- */ char* apclib_vstrdup(const char* s, apc_malloc_t ctor) { int n; char* t; if (s == NULL) { return NULL; } n = strlen(s) + 1; t = (char*) ctor(n); memcpy(t, s, n); return t; } void* apclib_vmemcpy(void* p, int n, apc_malloc_t ctor) { void* q; if (p == NULL) { return NULL; } q = ctor(n); memcpy(q, p, n); return q; } char* apclib_estrdup(const char* s) { int len; char* dup; if (s == NULL) { return NULL; } len = strlen(s); dup = (char*) malloc(len+1); if (dup == NULL) { apc_eprint("apclib_estrdup: malloc failed to allocate %u bytes:", len+1); } memcpy(dup, s, len); dup[len] = '\0'; return dup; } void* apclib_erealloc(void* p, size_t n) { p = realloc(p, n); if (p == NULL) { apc_eprint("apclib_erealloc: realloc failed to allocate %u bytes:", n); } return p; } /* type: string (null-terminated) */ void apclib_free_string(char **string) { if (*string == NULL) return; efree(*string); *string = NULL; } /* expandbuf: resize buffer to be at least minsize bytes in length */ static void apclib_expandbuf(char** bufptr, int* cursize, int minsize) { while (*cursize < minsize) { *cursize *= GROW_FACTOR; } *bufptr = (char*) realloc(*bufptr, *cursize); } int apclib_alignword_int(int x) { typedef union { void* p; int i; } word_t; return sizeof(word_t) * (1 + ((x-1)/sizeof(word_t))); } /* NO IDEA WHAT THIS STUFF IS ABOUT - probably needs sorting out... /* namearray_t is used to record deferred inheritance relationships */ typedef struct namearray_t namearray_t; struct namearray_t { char* strings; /* array of null-terminated names */ int length; /* logical size of strings */ int size; /* physical size of strings */ }; /* namearray_dtor: used to clean up deferred_inheritance table (see below) */ static void namearray_dtor(void* p) { namearray_t* na = (namearray_t*) p; if (na->strings != 0) { free(na->strings); } free(na); } /* ---------------------------------------------------------------------------- * * The name stuff is only really usefull for debugging.... * * * ---------------------------------------------------------------------------- */ static const char* opcodes[] = { "NOP", /* 0 */ "ADD", /* 1 */ "SUB", /* 2 */ "MUL", /* 3 */ "DIV", /* 4 */ "MOD", /* 5 */ "SL", /* 6 */ "SR", /* 7 */ "CONCAT", /* 8 */ "BW_OR", /* 9 */ "BW_AND", /* 10 */ "BW_XOR", /* 11 */ "BW_NOT", /* 12 */ "BOOL_NOT", /* 13 */ "BOOL_XOR", /* 14 */ "IS_IDENTICAL", /* 15 */ "IS_NOT_IDENTICAL", /* 16 */ "IS_EQUAL", /* 17 */ "IS_NOT_EQUAL", /* 18 */ "IS_SMALLER", /* 19 */ "IS_SMALLER_OR_EQUAL", /* 20 */ "CAST", /* 21 */ "QM_ASSIGN", /* 22 */ "ASSIGN_ADD", /* 23 */ "ASSIGN_SUB", /* 24 */ "ASSIGN_MUL", /* 25 */ "ASSIGN_DIV", /* 26 */ "ASSIGN_MOD", /* 27 */ "ASSIGN_SL", /* 28 */ "ASSIGN_SR", /* 29 */ "ASSIGN_CONCAT", /* 30 */ "ASSIGN_BW_OR", /* 31 */ "ASSIGN_BW_AND", /* 32 */ "ASSIGN_BW_XOR", /* 33 */ "PRE_INC", /* 34 */ "PRE_DEC", /* 35 */ "POST_INC", /* 36 */ "POST_DEC", /* 37 */ "ASSIGN", /* 38 */ "ASSIGN_REF", /* 39 */ "ECHO", /* 40 */ "PRINT", /* 41 */ "JMP", /* 42 */ "JMPZ", /* 43 */ "JMPNZ", /* 44 */ "JMPZNZ", /* 45 */ "JMPZ_EX", /* 46 */ "JMPNZ_EX", /* 47 */ "CASE", /* 48 */ "SWITCH_FREE", /* 49 */ "BRK", /* 50 */ "CONT", /* 51 */ "BOOL", /* 52 */ "INIT_STRING", /* 53 */ "ADD_CHAR", /* 54 */ "ADD_STRING", /* 55 */ "ADD_VAR", /* 56 */ "BEGIN_SILENCE", /* 57 */ "END_SILENCE", /* 58 */ "INIT_FCALL_BY_NAME", /* 59 */ "DO_FCALL", /* 60 */ "DO_FCALL_BY_NAME", /* 61 */ "RETURN", /* 62 */ "RECV", /* 63 */ "RECV_INIT", /* 64 */ "SEND_VAL", /* 65 */ "SEND_VAR", /* 66 */ "SEND_REF", /* 67 */ "NEW", /* 68 */ "JMP_NO_CTOR", /* 69 */ "FREE", /* 70 */ "INIT_ARRAY", /* 71 */ "ADD_ARRAY_ELEMENT", /* 72 */ "INCLUDE_OR_EVAL", /* 73 */ "UNSET_VAR", /* 74 */ "UNSET_DIM_OBJ", /* 75 */ "ISSET_ISEMPTY", /* 76 */ "FE_RESET", /* 77 */ "FE_FETCH", /* 78 */ "EXIT", /* 79 */ "FETCH_R", /* 80 */ "FETCH_DIM_R", /* 81 */ "FETCH_OBJ_R", /* 82 */ "FETCH_W", /* 83 */ "FETCH_DIM_W", /* 84 */ "FETCH_OBJ_W", /* 85 */ "FETCH_RW", /* 86 */ "FETCH_DIM_RW", /* 87 */ "FETCH_OBJ_RW", /* 88 */ "FETCH_IS", /* 89 */ "FETCH_DIM_IS", /* 90 */ "FETCH_OBJ_IS", /* 91 */ "FETCH_FUNC_ARG", /* 92 */ "FETCH_DIM_FUNC_ARG", /* 93 */ "FETCH_OBJ_FUNC_ARG", /* 94 */ "FETCH_UNSET", /* 95 */ "FETCH_DIM_UNSET", /* 96 */ "FETCH_OBJ_UNSET", /* 97 */ "FETCH_DIM_TMP_VAR", /* 98 */ "FETCH_CONSTANT", /* 99 */ "DECLARE_FUNCTION_OR_CLASS", /* 100 */ "EXT_STMT", /* 101 */ "EXT_FCALL_BEGIN", /* 102 */ "EXT_FCALL_END", /* 103 */ "EXT_NOP", /* 104 */ "TICKS", /* 105 */ "SEND_VAR_NO_REF", /* 106 */ "BEGIN_CLASS_DEF", /* 107 */ "BEGIN_HASH_DEF", /* 108 */ "OPCODE_ARRAY", /* 109 */ }; #define ZEND_BEGIN_HASH_DEF 108 #define ZEND_OPCODE_ARRAY 109 static const int NUM_OPCODES = sizeof(opcodes) / sizeof(opcodes[0]); const char* getOpcodeName(int op) { if (op < 0 || op >= NUM_OPCODES) { return "(unknown)"; } return opcodes[op]; } /* ---------------------------------------------------------------------------- * * STUFF THAT PROBALY NEEDS DELETING. * * * ---------------------------------------------------------------------------- */ /* inherit: recursively inherit methods from base to all the children * of parent, the children of parent's children, and so on */ /* static void apc_inherit(zend_class_entry* base, zend_class_entry* parent, TSRMLS_DC) { namearray_t* children; // classes derived directly from parent char* child_name; // name of the ith child of parent int i; return; // stuff in here is ignored at present.. // later - // children = apc_nametable_retrieve(deferred_inheritance, parent->name); if (!children) { return; // 'parent' has no children, nothing to do } // For each child of parent, resolve the inheritance from base // to the child. for (i = 0; i < children->length; i += strlen(child_name) + 1) { zend_class_entry* child; int result; child_name = children->strings + i; // look up the child class entry result = zend_hash_find(CG(class_table), child_name, strlen(child_name) + 1, (void**) &child); assert(result == SUCCESS); // FIXME: is this correct? // child inherits from base ZEND_DO_INHERITANCE(child, parent); // all children of child inherit from base apc_inherit(parent, child); } }*/ /* call_inherit */ static void apc_call_inherit(char *key, void *data TSRMLS_DC) { zend_class_entry *ce; if(zend_hash_find(CG(class_table), key, strlen(key) + 1, (void **) &ce) == SUCCESS) { apc_inherit(ce, ce); } } /* ---------------------------------------------------------------------------- * * START STUFF THAT NEEDS GLOBALS.... * * * ---------------------------------------------------------------------------- */ /* First step in deserialization. Sets the size/position of the * serialized buffer */ void apc_init_deserializer(char* input, int size TSRMLS_DC) { } /* apc_serialize_debug: prints information about the source and * destination serialization buffers */ void apc_serialize_debug(char * string TSRMLS_DC) { BCOMPILER_DEBUG(("%s\n", string)); //printf( "src=%p, srcpos=%d, srcsize=%d\n", BCOMPILERG(src), BCOMPILERG(srcpos), BCOMPILERG(srcsize)); //printf( "dst=%p, dstpos=%d, dstsize=%d\n", BCOMPILERG(dst), BCOMPILERG(dstpos), BCOMPILERG(dstsize)); } void apc_serialize_string(char* string TSRMLS_DC) { int len; /* by convention, mark null strings with a length of -1 */ if (string == NULL) { SERIALIZE_SCALAR(-1, int); return; } len = strlen(string); if (len <= 0) { SERIALIZE_SCALAR(-1, int); return; } BCOMPILER_DEBUG(("STRING: len, string : %s\n", string)); SERIALIZE_SCALAR(len, int); STORE_BYTES(string, len); } void apc_serialize_zstring(char* string, int len TSRMLS_DC) { /* by convention, mark null strings with a length of -1 */ if (len <= 0 || string == NULL) { SERIALIZE_SCALAR(-1, int); return; } // len = strlen(string); SERIALIZE_SCALAR(len, int); STORE_BYTES(string, len); } void apc_create_string(char** string TSRMLS_DC) { int len = 0; DESERIALIZE_SCALAR(&len, int); if (len <= 0) { /* by convention, empty marked strings (len is -1) are returned as an empty string */ *string = (char*) emalloc(1); (*string)[0] = '\0'; return; } *string = (char*) emalloc(len + 1); LOAD_BYTES(*string, len); (*string)[len] = '\0'; } void apc_serialize_arg_types(zend_uchar* arg_types TSRMLS_DC) { if (arg_types == NULL) { SERIALIZE_SCALAR(0, char); return; /* arg_types is null */ } SERIALIZE_SCALAR(1, char); SERIALIZE_SCALAR(arg_types[0], zend_uchar); STORE_BYTES(arg_types + 1, arg_types[0]*sizeof(zend_uchar)); } void apc_create_arg_types(zend_uchar** arg_types TSRMLS_DC) { char exists; zend_uchar count; DESERIALIZE_SCALAR(&exists, char); if (!exists) { *arg_types = NULL; return; /* arg_types is null */ } DESERIALIZE_SCALAR(&count, zend_uchar); *arg_types = emalloc(count + 1); (*arg_types)[0] = count; LOAD_BYTES((*arg_types) + 1, count*sizeof(zend_uchar)); } /* precompiler routines */ void apc_serialize_magic(TSRMLS_DC) { apc_serialize_string(BCOMPILER_MAGIC_HEADER TSRMLS_CC); } int apc_deserialize_magic(TSRMLS_DC) { char *tmp; int retval; apc_create_string(&tmp TSRMLS_CC); BCOMPILER_DEBUG(("got %s\n", tmp)); retval = strcmp(tmp,BCOMPILER_MAGIC_HEADER); apclib_free_string(&tmp); // MPB return retval; } /* type: zend_llist */ static void store_zend_llist_element(void* arg, void* data TSRMLS_DC) { int size = *((int*)arg); STORE_BYTES((char*)data, size); } void apc_serialize_zend_llist(zend_llist* list TSRMLS_DC) { char exists; exists = (list != NULL) ? 1 : 0; SERIALIZE_SCALAR(exists, char); // write twice to remove need for peeking. if (!exists) { return; } SERIALIZE_SCALAR(exists, char); SERIALIZE_SCALAR(list->size, size_t); SERIALIZE_SCALAR(list->dtor, void*); SERIALIZE_SCALAR(list->persistent, unsigned char); SERIALIZE_SCALAR(zend_llist_count(list), int); zend_llist_apply_with_argument(list, store_zend_llist_element, &list->size); } void apc_deserialize_zend_llist(zend_llist* list TSRMLS_DC) { char exists; size_t size; void (*dtor)(void*); unsigned char persistent; int count, i; char* data; DESERIALIZE_SCALAR(&exists, char); assert(exists != 0); /* read the list parameters */ DESERIALIZE_SCALAR(&size, size_t); DESERIALIZE_SCALAR(&dtor, void*); DESERIALIZE_SCALAR(&persistent, unsigned char); /* initialize the list */ zend_llist_init(list, size, dtor, persistent); /* insert the list elements */ DESERIALIZE_SCALAR(&count, int); data = (char*) malloc(list->size); for (i = 0; i < count; i++) { LOAD_BYTES(data, list->size); zend_llist_add_element(list, data); } free(data); } void apc_create_zend_llist(zend_llist** list TSRMLS_DC) { char exists; /* Sneak a look one byte ahead to see whether the list exists or not. * If it does, then exists is part of the structure, otherwise it was * a zero-value placeholder byte. */ /*PEEK_SCALAR(&exists, char); */ DESERIALIZE_SCALAR(&exists, char); if (exists) { *list = (zend_llist*) emalloc(sizeof(zend_llist)); apc_deserialize_zend_llist(*list TSRMLS_CC); } else { /* DESERIALIZE_SCALAR(&exists, char); */ *list = 0; } } /* type: HashTable */ /* type: HashTable */ void apc_serialize_hashtable(HashTable* ht, void* funcptr TSRMLS_DC) { char exists; /* for identifying null lists */ Bucket* p; void (*serialize_bucket)(void*); serialize_bucket = (void(*)(void*)) funcptr; exists = (ht != NULL) ? 1 : 0; SERIALIZE_SCALAR(exists, char); if (!exists) { return; } /* Serialize the hash meta-data. */ SERIALIZE_SCALAR(ht->nTableSize, uint); SERIALIZE_SCALAR(ht->pDestructor, void*); SERIALIZE_SCALAR(ht->nNumOfElements, uint); SERIALIZE_SCALAR(ht->persistent, int); /* Iterate through the buckets of the hash, serializing as we go. */ p = ht->pListHead; while(p != NULL) { SERIALIZE_SCALAR(p->h, ulong); SERIALIZE_SCALAR(p->nKeyLength,uint); CALLBACK_START(ZEND_BEGIN_HASH_DEF); CALLBACK_ADD_LONG("LINE", -1); BCOMPILERG(callback_key) = "HASH"; CALLBACK_ADD_STRING(p->arKey, p->nKeyLength); CALLBACK_END(); apc_serialize_zstring(p->arKey, p->nKeyLength TSRMLS_CC); serialize_bucket(p->pData); p = p->pListNext; } } void apc_deserialize_hashtable(HashTable* ht, void* funcptr, void* dptr, int datasize, char exists TSRMLS_DC) { uint nSize; dtor_func_t pDestructor; uint nNumOfElements; int persistent; int j; ulong h; uint nKeyLength; char* arKey; void* pData; int status; void (*deserialize_bucket)(void*); void (*free_bucket)(void*); BCOMPILER_DEBUG(("-----------------------------\nHASH TABLE:\n")); deserialize_bucket = (void(*)(void*)) funcptr; free_bucket = (void(*)(void*)) dptr; assert(exists != 0); DESERIALIZE_SCALAR(&nSize, uint); DESERIALIZE_SCALAR(&pDestructor, void*); DESERIALIZE_SCALAR(&nNumOfElements,uint); DESERIALIZE_SCALAR(&persistent, int); BCOMPILER_DEBUG(("-----------------------------\nBEGIN TABLE:\n")); /* Although the hash is already allocated (we're a deserialize, not a * create), we still need to initialize it. If this fails, something * very very bad happened. */ status = zend_hash_init(ht, nSize, NULL, pDestructor, persistent); assert(status != FAILURE); /* Luckily, the number of elements in a hash is part of its struct, so * we can just deserialize that many hashtable elements. */ for (j = 0; j < nNumOfElements; j++) { DESERIALIZE_SCALAR(&h, ulong); DESERIALIZE_SCALAR(&nKeyLength, uint); apc_create_string(&arKey TSRMLS_CC); deserialize_bucket(&pData); /* If nKeyLength is non-zero, this element is a hashed key/value * pair. Otherwise, it is an array element with a numeric index */ BCOMPILER_DEBUG(("-----------------------------\nFUNC %s\n",arKey)); if (nKeyLength != 0) { if(datasize == sizeof(void*)) { zend_hash_add_or_update(ht, arKey, nKeyLength, &pData, datasize, NULL, HASH_ADD); } else { zend_hash_add_or_update(ht, arKey, nKeyLength, pData, datasize, NULL, HASH_ADD); } } else { /* numeric index, not key string */ if(datasize == sizeof(void*)) { zend_hash_index_update(ht, h, &pData, datasize, NULL); } else { zend_hash_index_update(ht, h, pData, datasize, NULL); } } if (dptr != NULL) { free_bucket(&pData); } // else { // BCOMPILER_DEBUG((stderr, "Do not free: %s\n", arKey)); // } apclib_free_string(&arKey); // ADDED BY MPB } } void apc_create_hashtable(HashTable** ht, void* funcptr, void* dptr, int datasize TSRMLS_DC) { char exists; /* for identifying null hashtables */ /*PEEK_SCALAR(&exists, char); */ DESERIALIZE_SCALAR(&exists, char); if (exists==1) { *ht = (HashTable*) emalloc(sizeof(HashTable)); apc_deserialize_hashtable(*ht, funcptr, dptr, datasize,exists TSRMLS_CC); } else { /* DESERIALIZE_SCALAR(&exists, char); */ *ht = 0; } } /* type: zvalue_value */ void apc_serialize_zvalue_value(zvalue_value* zv, int type TSRMLS_DC) { /* A zvalue_value is a union, and as such we first need to * determine exactly what it's type is, then serialize the * appropriate structure. */ CALLBACK_ADD_SUB_LONG("u.constant.type",type); switch (type) { case IS_RESOURCE: case IS_BOOL: case IS_LONG: CALLBACK_ADD_SUB_LONG("u.constant.val",zv->lval); CALLBACK_ADD_LONG(BCOMPILERG(callback_key),zv->lval); SERIALIZE_SCALAR(zv->lval, long); break; case IS_DOUBLE: CALLBACK_ADD_SUB_DOUBLE("u.constant.val",zv->dval); CALLBACK_ADD_DOUBLE(BCOMPILERG(callback_key),zv->dval); SERIALIZE_SCALAR(zv->dval, double); break; case IS_NULL: /* null value, do nothing */ break; case IS_CONSTANT: case IS_STRING: case FLAG_IS_BC: CALLBACK_ADD_SUB_STRING("u.constant.val",zv->str.val, zv->str.len); CALLBACK_ADD_STRING(zv->str.val, zv->str.len); apc_serialize_zstring(zv->str.val, zv->str.len TSRMLS_CC); SERIALIZE_SCALAR(zv->str.len, int); break; case IS_ARRAY: CALLBACK_ADD_STRING("ARRAY?", 6); apc_serialize_hashtable(zv->ht, apc_serialize_zval_ptr TSRMLS_CC); break; case IS_CONSTANT_ARRAY: CALLBACK_ADD_STRING("CARRAY?", 7); apc_serialize_hashtable(zv->ht, apc_serialize_zval_ptr TSRMLS_CC); break; case IS_OBJECT: CALLBACK_ADD_STRING("OBJECT?", 7); apc_serialize_zend_class_entry(zv->obj.ce TSRMLS_CC); apc_serialize_hashtable(zv->obj.properties, apc_serialize_zval_ptr TSRMLS_CC); break; default: /* The above list enumerates all types. If we get here, * something very very bad has happened. */ assert(0); } } void apc_deserialize_zvalue_value(zvalue_value* zv, int type TSRMLS_DC) { /* We peeked ahead in the calling routine to deserialize the * type. Now we just deserialize. */ switch(type) { case IS_RESOURCE: case IS_BOOL: case IS_LONG: DESERIALIZE_SCALAR(&zv->lval, int); break; case IS_NULL: /* null value, do nothing */ break; case IS_DOUBLE: DESERIALIZE_SCALAR(&zv->dval, double); break; case IS_CONSTANT: case IS_STRING: case FLAG_IS_BC: apc_create_string(&zv->str.val TSRMLS_CC); DESERIALIZE_SCALAR(&zv->str.len, int); break; case IS_ARRAY: apc_create_hashtable(&zv->ht, apc_create_zval, NULL, sizeof(void*) TSRMLS_CC); break; case IS_CONSTANT_ARRAY: apc_create_hashtable(&zv->ht, apc_create_zval, NULL, sizeof(void*) TSRMLS_CC); break; case IS_OBJECT: apc_create_zend_class_entry(&zv->obj.ce TSRMLS_CC); apc_create_hashtable(&zv->obj.properties, apc_create_zval, NULL, sizeof(zval *) TSRMLS_CC); break; default: /* The above list enumerates all types. If we get here, * something very very bad has happened. */ assert(0); } } /* type: zval */ void apc_serialize_zval_ptr(zval** zv TSRMLS_DC) { apc_serialize_zval(*zv TSRMLS_CC); } void apc_serialize_zval(zval* zv TSRMLS_DC) { /* type is the switch for serializing zvalue_value */ SERIALIZE_SCALAR(zv->type, zend_uchar); apc_serialize_zvalue_value(&zv->value, zv->type TSRMLS_CC); SERIALIZE_SCALAR(zv->is_ref, zend_uchar); SERIALIZE_SCALAR(zv->refcount, zend_ushort); } void apc_deserialize_zval(zval* zv TSRMLS_DC) { /* type is the switch for deserializing zvalue_value */ DESERIALIZE_SCALAR(&zv->type, zend_uchar); apc_deserialize_zvalue_value(&zv->value, zv->type TSRMLS_CC); DESERIALIZE_SCALAR(&zv->is_ref, zend_uchar); DESERIALIZE_SCALAR(&zv->refcount, zend_ushort); } void apc_create_zval(zval** zv TSRMLS_DC) { *zv = (zval*) emalloc(sizeof(zval)); apc_deserialize_zval(*zv TSRMLS_CC); } void apc_free_zval(zval** zv TSRMLS_DC) { if (*zv != NULL) { switch((*zv)->type) { case IS_CONSTANT: case IS_STRING: case FLAG_IS_BC: apclib_free_string(&(*zv)->value.str.val); break; } efree(*zv); } *zv = NULL; } /* type: zend_function_entry */ void apc_serialize_zend_function_entry(zend_function_entry* zfe TSRMLS_DC) { apc_serialize_string(zfe->fname TSRMLS_CC); BCOMPILER_DEBUG(("serializing function %s\n",zfe->fname )); SERIALIZE_SCALAR(zfe->handler, void*); apc_serialize_arg_types(zfe->func_arg_types TSRMLS_CC); } void apc_deserialize_zend_function_entry(zend_function_entry* zfe TSRMLS_DC) { apc_create_string(&zfe->fname TSRMLS_CC); DESERIALIZE_SCALAR(&zfe->handler, void*); BCOMPILER_DEBUG(("deserializing function %s\n",zfe->handler)); apc_create_arg_types(&zfe->func_arg_types TSRMLS_CC); } /* type: zend_property_reference */ void apc_serialize_zend_property_reference(zend_property_reference* zpr TSRMLS_DC) { SERIALIZE_SCALAR(zpr->type, int); apc_serialize_zval(zpr->object TSRMLS_CC); apc_serialize_zend_llist(zpr->elements_list TSRMLS_CC); } void apc_deserialize_zend_property_reference(zend_property_reference* zpr TSRMLS_DC) { SERIALIZE_SCALAR(zpr->type, int); apc_deserialize_zval(zpr->object TSRMLS_CC); apc_create_zend_llist(&zpr->elements_list TSRMLS_CC); } /* type: zend_overloaded_element */ void apc_serialize_zend_overloaded_element(zend_overloaded_element* zoe TSRMLS_DC) { SERIALIZE_SCALAR(zoe->type, zend_uchar); apc_serialize_zval(&zoe->element TSRMLS_CC); } void apc_deserialize_zend_overloaded_element(zend_overloaded_element* zoe TSRMLS_DC) { DESERIALIZE_SCALAR(&zoe->type, zend_uchar); apc_deserialize_zval(&zoe->element TSRMLS_CC); } /* type: zend_class_entry */ void apc_serialize_zend_class_entry(zend_class_entry* zce TSRMLS_DC) { /* other than sending to a stream it also does a callback! The Array for a Class entry should look like: NOT::Type? - what is this used for? Name Parent NOT::refcount[0] ?? NOT::constants_updated ?? NOT::call,set etc: - would these point to a 'method?' !! ZEND_DECLARE_FUNCTION_OR_CLASS */ zval token; zval *keyword; zend_function_entry* zfe; int count, i, exists; /*apc_serialize_debug("starting adding class :" TSRMLS_CC); */ BCOMPILER_DEBUG(("adding type : %i\n",zce->type )); SERIALIZE_SCALAR(zce->type, char); apc_serialize_zstring(zce->name, zce->name_length TSRMLS_CC); SERIALIZE_SCALAR(zce->name_length, uint); /*apc_serialize_debug("done name" TSRMLS_CC); */ /* Serialize the name of this class's parent class (if it has one) * so that we can perform inheritance during deserialization (see * apc_deserialize_zend_class_entry). */ exists = (zce->parent != NULL) ? 1 : 0; SERIALIZE_SCALAR(exists, char); if (exists) { /*Parent*/ apc_serialize_zstring(zce->parent->name, zce->parent->name_length TSRMLS_CC); } CALLBACK_START(zce->type); BCOMPILERG(callback_key) = "CLASS"; CALLBACK_ADD_STRING(zce->name, zce->name_length); CALLBACK_END(); /* now callback to class/funct etc. */ /* apc_serialize_debug("done exists?" TSRMLS_CC); */ SERIALIZE_SCALAR(zce->refcount[0], int); SERIALIZE_SCALAR(zce->constants_updated, zend_bool); BCOMPILER_DEBUG(("-----------------------------\nFUNC TABLE:\n")); apc_serialize_hashtable(&zce->function_table, apc_serialize_zend_function TSRMLS_CC); BCOMPILER_DEBUG(("-----------------------------\nVARS:\n")); apc_serialize_hashtable(&zce->default_properties, apc_serialize_zval_ptr TSRMLS_CC); /* zend_class_entry.builtin_functions: this array appears to be * terminated by an element where zend_function_entry.fname is null * First we count the number of elements, then we serialize that count * and all the functions. */ BCOMPILER_DEBUG(("-----------------------------\nBUILTIN:\n")); count = 0; if (zce->builtin_functions) { for (zfe = zce->builtin_functions; zfe->fname != NULL; zfe++) { count++; } } SERIALIZE_SCALAR(count, int); for (i = 0; i < count; i++) { apc_serialize_zend_function_entry(&zce->builtin_functions[i] TSRMLS_CC); } /* apc_serialize_debug("tail stuff" TSRMLS_CC); */ SERIALIZE_SCALAR(zce->handle_function_call, void*); SERIALIZE_SCALAR(zce->handle_property_get, void*); SERIALIZE_SCALAR(zce->handle_property_set, void*); } void apc_deserialize_zend_class_entry(zend_class_entry* zce TSRMLS_DC) { int count, i, exists; DESERIALIZE_SCALAR(&zce->type, char); apc_create_string(&zce->name TSRMLS_CC); DESERIALIZE_SCALAR(&zce->name_length, uint); DESERIALIZE_SCALAR(&exists, char); if (exists) { // This class knows the name of its parent, most likely because // its parent is defined in the same source file. Therefore, we // can simply restore the parent link, and not worry about // manually inheriting methods from the parent (PHP will perform // the inheritance). char* parent_name; // name of parent class apc_create_string(&parent_name TSRMLS_CC); if ((zend_hash_find(CG(class_table), parent_name, strlen(parent_name) + 1, (void**) &zce->parent) == FAILURE)) { php_error(E_ERROR, "unable to inherit %s", parent_name); } } else { zce->parent = NULL; } /* refcount is a pointer to a single int. Don't ask me why, I // just work here. */ zce->refcount = (int*) emalloc(sizeof(int)); DESERIALIZE_SCALAR(zce->refcount, int); DESERIALIZE_SCALAR(&zce->constants_updated, zend_bool); BCOMPILER_DEBUG(("-----------------------------\nFUNC TABLE:\n")); DESERIALIZE_SCALAR(&exists, char); apc_deserialize_hashtable(&zce->function_table, apc_create_zend_function, apc_free_zend_function, sizeof(zend_function) ,exists TSRMLS_CC); BCOMPILER_DEBUG(("-----------------------------\nDEFAYLT PROPS:\n")); DESERIALIZE_SCALAR(&exists, char); apc_deserialize_hashtable(&zce->default_properties, apc_create_zval, NULL, sizeof(zval *), exists TSRMLS_CC); // see apc_serialize_zend_class_entry() for a description of the // zend_class_entry.builtin_functions member DESERIALIZE_SCALAR(&count, int); zce->builtin_functions = NULL; if (count > 0) { zce->builtin_functions = (zend_function_entry*) emalloc((count+1) * sizeof(zend_function_entry)); zce->builtin_functions[count].fname = NULL; for (i = 0; i < count; i++) { apc_deserialize_zend_function_entry(&zce->builtin_functions[i] TSRMLS_CC); } } DESERIALIZE_SCALAR(&zce->handle_function_call, void*); DESERIALIZE_SCALAR(&zce->handle_property_get, void*); DESERIALIZE_SCALAR(&zce->handle_property_set, void*); /* Resolve the inheritance relationships that have been delayed and * are waiting for this class to be created, i.e., every child of * this class that has already been compiled needs to be inherited * from this class. Call inherit() with this class as the base class * (first parameter) and as the current parent class (second parameter). * inherit will recursively resolve every inheritance relationships * in which this class is the base. */ /* apc_inherit(zce, zce TSRMLS_CC); */ /* code from zend_do_inheritance - ignores constructor inheritance currenlty? */ if (zce->parent) { zval *tmp; zend_function tmp_zend_function; zend_hash_merge(&zce->default_properties, &zce->parent->default_properties, (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); zend_hash_merge(&zce->function_table, &zce->parent->function_table, (void (*)(void *)) function_add_ref, &tmp_zend_function, sizeof(zend_function), 0); if (!zce->handle_property_get) zce->handle_property_get = zce->parent->handle_property_get; if (!zce->handle_property_set) zce->handle_property_set = zce->parent->handle_property_set; if (!zce->handle_function_call) zce->handle_function_call = zce->parent->handle_function_call; } } void apc_create_zend_class_entry(zend_class_entry** zce TSRMLS_DC) { *zce = (zend_class_entry*) emalloc(sizeof(zend_class_entry)); apc_deserialize_zend_class_entry(*zce TSRMLS_CC); } /* type: znode */ void apc_serialize_znode(znode* zn TSRMLS_DC) { SERIALIZE_SCALAR(zn->op_type, int); /* If the znode's op_type is IS_CONST, we know precisely what it is. * otherwise, it is too case-dependent (or inscrutable), so we do * a bitwise copy. */ CALLBACK_ADD_SUB_LONG("op_type" ,(long) zn->op_type); CALLBACK_ADD_SUB_LONG("u.fetch_type" ,(int) zn->u.fetch_type); CALLBACK_ADD_SUB_LONG("u.EA.type" ,(int) zn->u.EA.type); switch(zn->op_type) { case IS_CONST: if (&zn->u.fetch_type == ZEND_FETCH_GLOBAL) { CALLBACK_ADD_STRING("**GLOBAL",8); } apc_serialize_zval(&zn->u.constant TSRMLS_CC); break; case IS_VAR: CALLBACK_ADD_SUB_LONG("u.var" ,(long) zn->u.var); CALLBACK_ADD_STRING_LONG("VAR:%i",(long) zn->u.var); STORE_BYTES(&zn->u, sizeof(zn->u)); break; case IS_TMP_VAR: CALLBACK_ADD_SUB_LONG("u.var" ,(long) zn->u.var); CALLBACK_ADD_STRING_LONG("TMPVAR:%i",(long) zn->u.var); STORE_BYTES(&zn->u, sizeof(zn->u)); break; case IS_UNUSED: /* CALLBACK_ADD_STRING("**NOTUSED",9); */ CALLBACK_ADD_SUB_LONG("u.opline_num" ,(long) zn->u.opline_num); STORE_BYTES(&zn->u, sizeof(zn->u)); break; default: CALLBACK_ADD_STRING_LONG("**UNKNOWN",(long) sizeof(zn->u)); STORE_BYTES(&zn->u, sizeof(zn->u)); break; } } void apc_deserialize_znode(znode* zn TSRMLS_DC) { DESERIALIZE_SCALAR(&zn->op_type, int); /* If the znode's op_type is IS_CONST, we know precisely what it is. * otherwise, it is too case-dependent (or inscrutable), so we do * a bitwise copy. */ switch(zn->op_type) { case IS_CONST: apc_deserialize_zval(&zn->u.constant TSRMLS_CC); break; default: LOAD_BYTES(&zn->u, sizeof(zn->u)); break; } } /* type: zend_op */ void apc_serialize_zend_op(int id, zend_op* zo TSRMLS_DC) { /* apc_serialize_debug(getOpcodeName(zo->opcode)); */ //fprintf(stderr, "Outputting %s\n", getOpcodeName(zo->opcode)); CALLBACK_START(zo->opcode); SERIALIZE_SCALAR(zo->opcode, zend_uchar); BCOMPILERG(callback_key)="RESULT"; apc_serialize_znode(&zo->result TSRMLS_CC); BCOMPILERG(callback_key)="OP1"; apc_serialize_znode(&zo->op1 TSRMLS_CC); BCOMPILERG(callback_key)="OP2"; apc_serialize_znode(&zo->op2 TSRMLS_CC); SERIALIZE_SCALAR(zo->extended_value, ulong); if (zo->extended_value != 0) { CALLBACK_ADD_LONG("EXTENDED",(long) zo->extended_value); } CALLBACK_ADD_LONG("LINE",(long) id); /* add some useful info! */ switch (zo->opcode) { case ZEND_JMP: CALLBACK_ADD_LONG("JMP",zo->op1.u.opline_num); break; case ZEND_JMPZ: CALLBACK_ADD_LONG("JMP",zo->op2.u.opline_num); break; } CALLBACK_END(); SERIALIZE_SCALAR(zo->lineno, uint); } void apc_deserialize_zend_op(zend_op* zo TSRMLS_DC) { DESERIALIZE_SCALAR(&zo->opcode, zend_uchar); BCOMPILER_DEBUG(("Outputting %s\n", getOpcodeName(zo->opcode))); apc_deserialize_znode(&zo->result TSRMLS_CC); apc_deserialize_znode(&zo->op1 TSRMLS_CC); apc_deserialize_znode(&zo->op2 TSRMLS_CC); DESERIALIZE_SCALAR(&zo->extended_value, ulong); DESERIALIZE_SCALAR(&zo->lineno, uint); } /* type: zend_op_array */ void apc_serialize_zend_op_array(zend_op_array* zoa TSRMLS_DC) { char exists; int i; CALLBACK_START(ZEND_OPCODE_ARRAY); CALLBACK_ADD_LONG("TYPE",(long) zoa->type); CALLBACK_ADD_LONG("LINE",-1); CALLBACK_ADD_LONG("return_reference",zoa->return_reference); CALLBACK_ADD_KEY_STRING("FUNCTION_NAME",zoa->function_name, strlen(zoa->function_name)); SERIALIZE_SCALAR(zoa->type, zend_uchar); apc_serialize_arg_types(zoa->arg_types TSRMLS_CC); apc_serialize_string(zoa->function_name TSRMLS_CC); SERIALIZE_SCALAR(zoa->refcount[0], zend_uint); SERIALIZE_SCALAR(zoa->last, zend_uint); SERIALIZE_SCALAR(zoa->size, zend_uint); /* If a file 'A' is included twice in a single request, the following * situation can occur: A is deserialized and its functions added to * the global function table. On its next call, A is expired (either * forcibly removed or removed due to an expired ttl). Now when A is * compiled, its functions can't be added to the global function_table * (they are already present) so they are serialized as an opcode * ZEND_DECLARE_FUNCTION_OR_CLASS. This means that the functions will * be declared at execution time. Since they are present in the global * function_table, they will will also be serialized. This will cause * a fatal 'failed to redclare....' error. We avoid this by simulating * the action of the parser and changing all * ZEND_DECLARE_FUNCTION_OR_CLASS opcodes to ZEND_NOPs. */ CALLBACK_ADD_LONG("T",(long) zoa->T); CALLBACK_ADD_LONG("USES_GLOBALS",(long) zoa->uses_globals); CALLBACK_END(); for (i = 0; i < zoa->last; i++) { apc_serialize_zend_op(i, &zoa->opcodes[i] TSRMLS_CC); } SERIALIZE_SCALAR(zoa->T, zend_uint); SERIALIZE_SCALAR(zoa->last_brk_cont, zend_uint); SERIALIZE_SCALAR(zoa->current_brk_cont, zend_uint); SERIALIZE_SCALAR(zoa->uses_globals, zend_bool); exists = (zoa->brk_cont_array != NULL) ? 1 : 0; SERIALIZE_SCALAR(exists, char); if (exists) { STORE_BYTES(zoa->brk_cont_array, zoa->last_brk_cont * sizeof(zend_brk_cont_element)); } apc_serialize_hashtable(zoa->static_variables, apc_serialize_zval_ptr TSRMLS_CC); #ifdef APC_MUST_DEFINE_START_OP /* Introduced in php-4.0.7 */ assert(zoa->start_op == NULL); #endif SERIALIZE_SCALAR(zoa->return_reference, zend_bool); SERIALIZE_SCALAR(zoa->done_pass_two, zend_bool); apc_serialize_string(zoa->filename TSRMLS_CC); CALLBACK_START(ZEND_OPCODE_ARRAY); CALLBACK_ADD_LONG("ISEND",1); CALLBACK_ADD_LONG("LINE",-1); CALLBACK_END(); /* zend_op_array.reserved is not used */ } void apc_deserialize_zend_op_array(zend_op_array* zoa, int master TSRMLS_DC) { char *fname; char exists; int i; DESERIALIZE_SCALAR(&zoa->type, zend_uchar); apc_create_arg_types(&zoa->arg_types TSRMLS_CC); apc_create_string(&zoa->function_name TSRMLS_CC); zoa->refcount = (int*) emalloc(sizeof(zend_uint)); DESERIALIZE_SCALAR(zoa->refcount, zend_uint); DESERIALIZE_SCALAR(&zoa->last, zend_uint); DESERIALIZE_SCALAR(&zoa->size, zend_uint); zoa->opcodes = NULL; if (zoa->last > 0) { zoa->opcodes = (zend_op*) emalloc(zoa->last * sizeof(zend_op)); for (i = 0; i < zoa->last; i++) { apc_deserialize_zend_op(&zoa->opcodes[i] TSRMLS_CC); if(zoa->opcodes[i].opcode == ZEND_DECLARE_FUNCTION_OR_CLASS) { HashTable* table; char* op2str; /* op2str and op2len are for convenience */ int op2len; exists = 1; op2str = zoa->opcodes[i].op2.u.constant.value.str.val; op2len = zoa->opcodes[i].op2.u.constant.value.str.len; switch(zoa->opcodes[i].extended_value) { /* a run-time function declaration */ case ZEND_DECLARE_FUNCTION: { zend_function* function; table = CG(function_table); if (zend_hash_find(table, op2str, op2len + 1, (void**) &function) == SUCCESS) { zval_dtor(&zoa->opcodes[i].op1.u.constant); zval_dtor(&zoa->opcodes[i].op2.u.constant); zoa->opcodes[i].opcode = ZEND_NOP; memset(&zoa->opcodes[i].op1, 0, sizeof(znode)); memset(&zoa->opcodes[i].op2, 0, sizeof(znode)); zoa->opcodes[i].op1.op_type = IS_UNUSED; zoa->opcodes[i].op2.op_type = IS_UNUSED; } } break; /* a run-time class declaration */ case ZEND_DECLARE_CLASS: { zend_class_entry *ce; table = CG(class_table); if (zend_hash_find(table, op2str, op2len + 1, (void**) &ce) == SUCCESS) { zval_dtor(&zoa->opcodes[i].op1.u.constant); zval_dtor(&zoa->opcodes[i].op2.u.constant); zoa->opcodes[i].opcode = ZEND_NOP; memset(&zoa->opcodes[i].op1, 0, sizeof(znode)); memset(&zoa->opcodes[i].op2, 0, sizeof(znode)); zoa->opcodes[i].op1.op_type = IS_UNUSED; zoa->opcodes[i].op2.op_type = IS_UNUSED; } } break; /* a run-time derived class declaration */ case ZEND_DECLARE_INHERITED_CLASS: { zend_class_entry *ce; char* class_name; char* parent_name; int class_name_length; namearray_t* children; int minSize; table = CG(class_table); /* op2str is a class name of the form "base:derived", * where derived is the class being declared and base * is its parent in the class hierarchy. Extract the * two names into parent_name and class_name. */ parent_name = apclib_estrdup(op2str); if ((class_name = strchr(parent_name, ':')) == 0) { zend_error(E_CORE_ERROR,"Invalid runtime class entry"); } *class_name++ = '\0'; /* advance past ':' */ if (zend_hash_find(table, class_name, strlen(class_name)+1, (void**) &ce) == SUCCESS) { zval_dtor(&zoa->opcodes[i].op1.u.constant); zval_dtor(&zoa->opcodes[i].op2.u.constant); zoa->opcodes[i].opcode = ZEND_NOP; memset(&zoa->opcodes[i].op1, 0, sizeof(znode)); memset(&zoa->opcodes[i].op2, 0, sizeof(znode)); zoa->opcodes[i].op1.op_type = IS_UNUSED; zoa->opcodes[i].op2.op_type = IS_UNUSED; } /* The parent class hasn't been compiled yet, most likely * because it is defined in an included file. We must defer * this inheritance until the parent class is created. Add * a tuple for this class and its parent to the deferred * inheritance table */ class_name_length = strlen(class_name); //children = apc_nametable_retrieve(deferred_inheritance, // parent_name TSRMLS_CC); if (children == 0) { /* Create and initialize a new namearray_t for this * class's parent and insert into the deferred * inheritance table. */ children = (namearray_t*) malloc(sizeof(namearray_t)); children->length = 0; children->size = class_name_length + 1; children->strings = (char*) malloc(children->size); //apc_nametable_insert(deferred_inheritance, // parent_name, children TSRMLS_CC); } /* a deferred class can't be a top-level parent */ //apc_nametable_insert(non_inheritors, class_name, NULL TSRMLS_CC); minSize = children->length + class_name_length + 1; if (minSize > children->size) { /* The strings array (children->strings) is not big * enough to store this class name. Expand the array * using an exponential resize. */ while (minSize > children->size) { children->size *= 2; } children->strings = apclib_erealloc(children->strings, children->size); } memcpy(children->strings + children->length, class_name, class_name_length + 1); children->length += class_name_length + 1; } break; default: break; } } } } DESERIALIZE_SCALAR(&zoa->T, zend_uint); DESERIALIZE_SCALAR(&zoa->last_brk_cont, zend_uint); DESERIALIZE_SCALAR(&zoa->current_brk_cont, zend_uint); DESERIALIZE_SCALAR(&zoa->uses_globals, zend_bool); DESERIALIZE_SCALAR(&exists, char); zoa->brk_cont_array = NULL; if (exists) { zoa->brk_cont_array = (zend_brk_cont_element*) emalloc(zoa->last_brk_cont * sizeof(zend_brk_cont_element)); LOAD_BYTES(zoa->brk_cont_array, zoa->last_brk_cont * sizeof(zend_brk_cont_element)); } apc_create_hashtable(&zoa->static_variables, apc_create_zval, NULL, sizeof(zval *) TSRMLS_CC); #ifdef APC_MUST_DEFINE_START_OP /* Introduced in php 4.0.7 */ zoa->start_op = NULL; #endif DESERIALIZE_SCALAR(&zoa->return_reference, zend_bool); DESERIALIZE_SCALAR(&zoa->done_pass_two, zend_bool); apc_create_string(&fname TSRMLS_CC); zoa->filename = zend_set_compiled_filename(fname); apclib_free_string(&fname); if(master) { // apc_nametable_difference(parental_inheritors, non_inheritors TSRMLS_CC); // apc_nametable_apply(parental_inheritors, call_inherit TSRMLS_CC); } } void apc_create_zend_op_array(zend_op_array** zoa TSRMLS_DC) { *zoa = (zend_op_array*) emalloc(sizeof(zend_op_array)); apc_deserialize_zend_op_array(*zoa, 0 TSRMLS_CC); } /* type: zend_internal_function */ void apc_serialize_zend_internal_function(zend_internal_function* zif TSRMLS_DC) { SERIALIZE_SCALAR(zif->type, zend_uchar); apc_serialize_arg_types(zif->arg_types TSRMLS_CC); apc_serialize_string(zif->function_name TSRMLS_CC); SERIALIZE_SCALAR(zif->handler, void*); } void apc_deserialize_zend_internal_function(zend_internal_function* zif TSRMLS_DC) { DESERIALIZE_SCALAR(&zif->type, zend_uchar); apc_create_arg_types(&zif->arg_types TSRMLS_CC); apc_create_string(&zif->function_name TSRMLS_CC); DESERIALIZE_SCALAR(&zif->handler, void*); } /* type: zend_overloaded_function */ void apc_serialize_zend_overloaded_function(zend_overloaded_function* zof TSRMLS_DC) { SERIALIZE_SCALAR(zof->type, zend_uchar); apc_serialize_arg_types(zof->arg_types TSRMLS_CC); apc_serialize_string(zof->function_name TSRMLS_CC); SERIALIZE_SCALAR(zof->var, zend_uint); } void apc_deserialize_zend_overloaded_function(zend_overloaded_function* zof TSRMLS_DC) { DESERIALIZE_SCALAR(&zof->type, zend_uchar); apc_create_arg_types(&zof->arg_types TSRMLS_CC); apc_create_string(&zof->function_name TSRMLS_CC); DESERIALIZE_SCALAR(&zof->var, zend_uint); } /* type: zend_function */ void apc_serialize_zend_function(zend_function* zf TSRMLS_DC) { /* zend_function come in 4 different types with different internal * structs. */ zval retval; SERIALIZE_SCALAR(zf->type, zend_uchar); switch(zf->type) { case ZEND_INTERNAL_FUNCTION: apc_serialize_zend_internal_function(&zf->internal_function TSRMLS_CC); break; case ZEND_OVERLOADED_FUNCTION: apc_serialize_zend_overloaded_function(&zf->overloaded_function TSRMLS_CC); break; case ZEND_USER_FUNCTION: case ZEND_EVAL_CODE: apc_serialize_zend_op_array(&zf->op_array TSRMLS_CC); break; default: /* the above are all valid zend_function types. If we hit this * case something has gone very very wrong. */ assert(0); } } void apc_deserialize_zend_function(zend_function* zf TSRMLS_DC) { /* PEEK_SCALAR(&zf->type, zend_uchar); */ DESERIALIZE_SCALAR(&zf->type, zend_uchar); switch(zf->type) { case ZEND_INTERNAL_FUNCTION: apc_deserialize_zend_internal_function(&zf->internal_function TSRMLS_CC); break; case ZEND_OVERLOADED_FUNCTION: apc_deserialize_zend_overloaded_function(&zf->overloaded_function TSRMLS_CC); break; case ZEND_USER_FUNCTION: case ZEND_EVAL_CODE: apc_deserialize_zend_op_array(&zf->op_array, 0 TSRMLS_CC); break; default: /* the above are all valid zend_function types. If we hit this * case something has gone very very wrong. */ assert(0); } } void apc_create_zend_function(zend_function** zf TSRMLS_DC) { *zf = (zend_function*) emalloc(sizeof(zend_function)); apc_deserialize_zend_function(*zf TSRMLS_CC); } void apc_free_zend_function(zend_function** zf TSRMLS_DC) { if (*zf != NULL) efree(*zf); *zf = NULL; } /* The logic for serialize_class_table and deserialize_class_table * mirror that of the corresponding function_table functions (see * above), with classes in place of functions. */ static int store_class_table(void *element, int num_args, va_list args, zend_hash_key *hash_key TSRMLS_DC) { zend_class_entry* zc; zc = (zend_class_entry*) element; /* do not serialize internal classes */ if (zc->type == ZEND_INTERNAL_CLASS) { return 0; } /* serialize differences */ SERIALIZE_SCALAR(1, char); apc_serialize_zend_class_entry(zc TSRMLS_CC); if(zc->parent != NULL) { //apc_nametable_insert(priv, zc->name, 0); } return 0; } static int store_class_table_ex(void *element, int num_args, va_list args, zend_hash_key *hash_key TSRMLS_DC) { zend_class_entry* zc; zc = (zend_class_entry*) element; /* do not serialize internal classes */ if (zc->type == ZEND_INTERNAL_CLASS) { return 0; } /* serialize differences */ SERIALIZE_SCALAR(1, char); // apc_serialize_zstring(hash_key->arKey, hash_key->nKeyLength); apc_serialize_zend_class_entry(zc TSRMLS_CC); // Think about tracking same-file inheritance return 0; } void apc_serialize_zend_class_table(HashTable* gct TSRMLS_DC) { zend_hash_apply_with_arguments(gct, store_class_table, 0, NULL); SERIALIZE_SCALAR(0, char); } int apc_deserialize_zend_class_table(HashTable* gct TSRMLS_DC) { char exists; int i; zend_class_entry* zc; i = 0; DESERIALIZE_SCALAR(&exists, char); while (exists) { apc_create_zend_class_entry(&zc TSRMLS_CC); if (zend_hash_add(gct, zc->name, zc->name_length + 1, zc, sizeof(zend_class_entry), NULL) == FAILURE) { /* This can validly happen. */ } /* We may only want to do this insert if zc->parent is NULL */ //apc_nametable_insert(parental_inheritors, zc->name, NULL); //apc_nametable_insert(acc, zc->name, 0); //apc_nametable_insert(priv, zc->name, 0); DESERIALIZE_SCALAR(&exists, char); // apc_free_zend_class_entry if (zc != NULL) efree(zc); // ADDED BY MPB i++; } return i; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ Index: pear/PECL/bcompiler/bcompiler.dsp +++ pear/PECL/bcompiler/bcompiler.dsp # Microsoft Developer Studio Project File - Name="bcompiler" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 CFG=bcompiler - Win32 Debug_TS !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "bcompiler.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "bcompiler.mak" CFG="bcompiler - Win32 Debug_TS" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "bcompiler - Win32 Release_TS" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE "bcompiler - Win32 Debug_TS" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe MTL=midl.exe RSC=rc.exe !IF "$(CFG)" == "bcompiler - Win32 Release_TS" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release_TS" # PROP BASE Intermediate_Dir "Release_TS" # PROP BASE Ignore_Export_Lib 0 # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "Release_TS" # PROP Intermediate_Dir "Release_TS" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "TOKENIZER_EXPORTS" /YX /FD /c # ADD CPP /nologo /MD /W3 /GX /O2 /I "..\.." /I "..\..\main" /I "..\..\Zend" /I "..\..\TSRM" /D ZEND_DEBUG=0 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "PHP_EXPORTS" /D "COMPILE_DL_TOKENIZER" /D ZTS=1 /D "ZEND_WIN32" /D "PHP_WIN32" /D HAVE_TOKENIZER=1 /YX /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x407 /d "NDEBUG" # ADD RSC /l 0x407 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 # ADD LINK32 php4ts.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /out:"..\..\Release_TS/php_bcompiler.dll" /libpath:"..\..\Release_TS" /libpath:"..\..\Release_TS_Inline" !ELSEIF "$(CFG)" == "bcompiler - Win32 Debug_TS" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug_TS" # PROP BASE Intermediate_Dir "Debug_TS" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "Debug_TS" # PROP Intermediate_Dir "Debug_TS" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "TOKENIZER_EXPORTS" /YX /FD /GZ /c # ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\.." /I "..\..\main" /I "..\..\Zend" /I "..\..\TSRM" /D ZEND_DEBUG=1 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "PHP_EXPORTS" /D "COMPILE_DL_TOKENIZER" /D ZTS=1 /D "ZEND_WIN32" /D "PHP_WIN32" /D HAVE_TOKENIZER=1 /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x407 /d "_DEBUG" # ADD RSC /l 0x407 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept # ADD LINK32 php4ts_debug.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /out:"..\..\Debug_TS/php_bcompiler.dll" /pdbtype:sept /libpath:"..\..\Debug_TS" !ENDIF # Begin Target # Name "bcompiler - Win32 Release_TS" # Name "bcompiler - Win32 Debug_TS" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE=.\bcompiler.c # End Source File # End Group # Begin Group "Header Files" # PROP Default_Filter "h;hpp;hxx;hm;inl" # Begin Source File SOURCE=.\php_bcompiler.h # End Source File # End Group # End Target # End Project Index: pear/PECL/bcompiler/bcompiler.xml +++ pear/PECL/bcompiler/bcompiler.xml <?xml version="1.0" encoding="iso-8859-1"?> <!-- $Revision: 1.1 $ --> <reference id="pecl.bcompiler"> <title>bcompiler</title> <titleabbrev>bcompiler</titleabbrev> <partintro> &warn.experimental; <sect1 id="pecl.bcompiler.partintro"> <title>Introduction</title> <sect2 id="pecl.bcompiler.intro"> <title>About bcompiler</title> <para> Bcompiler was written for two reasons: <simplelist> <member>To encode some classes in a proprietary php application</member> <member>To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe.</member> <member>To do the feasiblity study for a PHP to C convertor</member> </simplelist> The first of these goals is achieved using the bcompiler_write_header, bcompiler_write_class, bcompiler_write_footer, bcompiler_read, and bcompiler_load functions. The bytecode files can be written as either uncompressed or plain. The bcompiler_load reads a bzip compressed bytecode file, which tends to be 1/3 of the size of the original file. </para> To create EXE type files, bcompiler has to be used with a modified sapi file or a version of php which has been compiled as a shared library. In this scenario, bcompiler reads the compressed bytecode from the end of the exe file. <para> </para> bcompiler is unlikely to improve performance very much, as it only bypasses the compiler stage of the php running process and replaces it with the import process in bcompiler. It also does not do any bytecode optimization, this could be added in the future... <para> </para> in terms of code protection, it is safe to say that it would be impossible to recreate the exact source code that it was built from, and without the accompanying source code comments. It would effectively be useless to use the bcompiler bytecodes to recreate and modify a class. However it is possible to retreive data from a bcompiled bytecode file - so dont put your private passwords or anything in it.. <para> </sect2> <sect2 id="pecl.bcompiler.install"> <title>Installation</title> <para> short installation note: <itemizedlist> <listitem><simpara>You need at least PHP 4.3.</simpara></listitem> <listitem> <simpara> untar the bcompiler.tgz archive into php4/ext (Get it directly from PEAR <ulink url="http://pear.php.net/get/bcompiler">http://pear.php.net/get/bcompiler</ulink>) </simpara> </listitem> <listitem> <simpara> If the new directory is now called something like bcompiler-0.x, then you should rename it to bcompiler (except you only want to build it as self-contained php-module) </simpara> </listitem> <listitem><simpara>run phpize in ext/bcompiler</simpara></listitem> <listitem><simpara>run ./buildconf in php4</simpara></listitem> <listitem> <simpara> run configure with --with-bcompiler (and your other options) </simpara> </listitem> <listitem><simpara>make; make install</simpara></listitem> <listitem><simpara>that's it.</simpara></listitem> </itemizedlist> </para> </sect2> <sect2 id="pecl.bcompiler.contact"> <title>Contact Information</title> <para> ...... </para> <para> If you have comments, bugfixes, enhancements or want to help developping this beast, you can drop me a mail at <ulink url="mailto:alan_k@php.net">alan_k@php.net</ulink>. Any help is very welcome. </para> </sect2> </sect1> </partintro> <!-- header --> <refentry id="pecl.bcompiler.bcompile-write-header"> <refnamediv> <refname>bcompile_write_header</refname> <refpurpose>Writes the bcompiler header</refpurpose> </refnamediv> <refsect1> <title>Description</title> <funcsynopsis> <funcprototype> <funcdef><function>bcompile_write_header</function></funcdef> <paramdef>resource <parameter>filehandle</parameter></paramdef> </funcprototype> </funcsynopsis> &warn.experimental.func; <para> Writes the header part of a bcompiler file. </para> <example> <title><function>bcompile_write_header</function> example</title> <programlisting role="php"> <![CDATA[ <?php $fh = fopen("/tmp/example","w"); bcompile_write_header($fh); bcompile_write_class($fh,"DB"); bcompile_write_footer($fh); fclose($fh); ?> ]]> </programlisting> </example> <para> See also: <function>bcompile_write_class</function>, <function>bcompile_write_footer</function>. </para> </refsect1> </refentry> <!-- footer --> <refentry id="pecl.bcompiler.bcompile-write-footer"> <refnamediv> <refname>bcompile_write_footer</refname> <refpurpose>Writes the a single character \x00 to indicate End of compiled data</refpurpose> </refnamediv> <refsect1> <title>Description</title> <funcsynopsis> <funcprototype> <funcdef><function>bcompile_write_footer</function></funcdef> <paramdef>resource <parameter>filehandle</parameter></paramdef> </funcprototype> </funcsynopsis> &warn.experimental.func; <para> Writes the a single character \x00 to indicate End of compiled data </para> <example> <title><function>bcompile_write_footer</function> example</title> <programlisting role="php"> <![CDATA[ <?php $fh = fopen("/tmp/example","w"); bcompile_write_header($fh); bcompile_write_class($fh,"DB"); bcompile_write_class($fh,"DB_common"); bcompile_write_footer($fh); fclose($fh); ?> ]]> </programlisting> </example> <para> See also: <function>bcompile_write_header</function>, <function>bcompile_write_header</function>. </para> </refsect1> </refentry> <!-- footer --> <refentry id="pecl.bcompiler.bcompile-write-exe-footer"> <refnamediv> <refname>bcompile_write_exe_footer</refname> <refpurpose>Writes the the start pos, and sig to the end of a exe type file</refpurpose> </refnamediv> <refsect1> <title>Description</title> <funcsynopsis> <funcprototype> <funcdef><function>bcompile_write_exe_footer</function></funcdef> <paramdef>resource <parameter>filehandle</parameter></paramdef> <paramdef>int <parameter>startpos</parameter></paramdef> </funcprototype> </funcsynopsis> &warn.experimental.func; <para> An EXE (or self exectutable) file consists of 3 parts, </para> <para> <simplelist> <member>The Exectutable code (eg. a compiled C program that can initiate call the php bcompiler)</member> <member>The Bzip encoded Bytecodes</member> <member>The bcompiler exe footer</member> </simplelist> The startpos is the position of in the file at which the Bzip encoded bytecodes start, and can be obtained using ftell($fh), </para> <example> <title><function>bcompile_write_footer</function> example</title> <programlisting role="php"> <![CDATA[ <?php $fh = fopen("/tmp/example.exe","w"); $size = filesize("/tmp/base.exe"); $fr = fopen("/tmp/base.exe","r"); fwrite($fh,fread($fr,$size),$size); $startpos = ftell($fh); /* write bytecodes compressed */ $fz = bzopen($fh,"w"); bcompile_write_header($fz); bcompile_write_class($fz,"DB"); bcompile_write_class($fz,"DB_common"); bcompile_write_footer($fz); /* write footer exe uncompressed */ bcompiler_write_exe_footer($fh,$startpos); fclose($fh); ?> ]]> </programlisting> </example> <para> See also:<function>bcompile_write_header</function> <function>bcompile_write_class</function>, <function>bcompile_write_footer</function>. </para> </refsect1> </refentry> <!-- read --> <refentry id="pecl.bcompiler.bcompile-read"> <refnamediv> <refname>bcompile_read</refname> <refpurpose>reads and creates classes from a filehandle</refpurpose> </refnamediv> <refsect1> <title>Description</title> <funcsynopsis> <funcprototype> <funcdef><function>bcompile_read</function></funcdef> <paramdef>resource <parameter>filehandle</parameter></paramdef> </funcprototype> </funcsynopsis> &warn.experimental.func; <para> Reads data from a open file handle and creates classes from the bytecodes </para> <example> <title><function>bcompile_read</function> example</title> <programlisting role="php"> <![CDATA[ <?php $fh = fopen("/tmp/example","r"); bcompile_read($fh); fclose($fh); print_r(get_defined_classes()); ?> ]]> </programlisting> </example> </refsect1> </refentry> <!-- load --> <refentry id="pecl.bcompiler.bcompile-load"> <refnamediv> <refname>bcompile_load</refname> <refpurpose>reads and creates classes from a bz compressed file</refpurpose> </refnamediv> <refsect1> <title>Description</title> <funcsynopsis> <funcprototype> <funcdef><function>bcompile_load</function></funcdef> <paramdef>string <parameter>filename</parameter></paramdef> </funcprototype> </funcsynopsis> &warn.experimental.func; <para> Reads data from a bzcompressed file and creates classes from the bytecodes </para> <example> <title><function>bcompile_load</function> example</title> <programlisting role="php"> <![CDATA[ <?php bcompile_load("/tmp/example"); print_r(get_defined_classes()); ?> ]]> </programlisting> </example> </refsect1> </refentry> <!-- load_exe --> <refentry id="pecl.bcompiler.bcompile-load-exe"> <refnamediv> <refname>bcompile_load_exe</refname> <refpurpose>reads and creates classes from a bcompiler exe file</refpurpose> </refnamediv> <refsect1> <title>Description</title> <funcsynopsis> <funcprototype> <funcdef><function>bcompile_load_exe</function></funcdef> <paramdef>string <parameter>filename</parameter></paramdef> </funcprototype> </funcsynopsis> &warn.experimental.func; <para> Reads data from a bcompiler exe file and creates classes from the bytecodes </para> <example> <title><function>bcompile_load</function> example</title> <programlisting role="php"> <![CDATA[ <?php bcompile_load_exe("/tmp/example.exe"); print_r(get_defined_classes()); ?> ]]> </programlisting> </example> </refsect1> </refentry> <!-- parse_class --> <refentry id="pecl.bcompiler.parse_class"> <refnamediv> <refname>bcompile_parse_class</refname> <refpurpose>reads the bytecodes of a class and calls back to a user function</refpurpose> </refnamediv> <refsect1> <title>Description</title> <funcsynopsis> <funcprototype> <funcdef><function>bcompile_parse_class</function></funcdef> <paramdef>string <parameter>class</parameter></paramdef> <paramdef>string <parameter>callback</parameter></paramdef> </funcprototype> </funcsynopsis> &warn.experimental.func; <para> reads the bytecodes of a class and calls back to a user function </para> <example> <title><function>bcompile_parse_class</function> example</title> <programlisting role="php"> <![CDATA[ <?php function readByteCodes($data) { print_r($data); } bcompile_parse_class("DB","readByteCodes"); ?> ]]> </programlisting> </example> </refsect1> </refentry> </reference> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> Index: pear/PECL/bcompiler/config.m4 +++ pear/PECL/bcompiler/config.m4 dnl dnl $Id: config.m4,v 1.1 2002/07/23 06:55:57 alan_k Exp $ dnl PHP_ARG_ENABLE(bcompiler,whether to enable bcompiler support, [ --enable-bcompiler Enable bcompiler support]) if test "$PHP_BCOMPILER" = "yes"; then AC_DEFINE(HAVE_BCOMPILER,1,[Whether you want bcompiler support]) PHP_NEW_EXTENSION(bcompiler, bcompiler.c, $ext_shared) fi Index: pear/PECL/bcompiler/config.m4.old +++ pear/PECL/bcompiler/config.m4.old dnl $Id: config.m4.old,v 1.1 2002/07/23 06:55:57 alan_k Exp $ dnl config.m4 for extension tokenizer dnl Otherwise use enable: PHP_ARG_ENABLE(bcompiler, whether to enable bcompiler support, [ --enable-tokenizer Enable bcompiler support]) if test "$PHP_BCOMPILER" != "no"; then PHP_EXTENSION(bcompiler, $ext_shared) fi Index: pear/PECL/bcompiler/php_bcompiler.h +++ pear/PECL/bcompiler/php_bcompiler.h /* __header_here__ */ #include "ext/standard/file.h" #ifndef PHP_BCOMPILER_H #define PHP_BCOMPILER_H extern zend_module_entry bcompiler_module_entry; #define phpext_bcompiler_ptr &bcompiler_module_entry #ifdef PHP_WIN32 #define PHP_BCOMPILER_API __declspec(dllexport) #else #define PHP_BCOMPILER_API #endif #ifdef ZTS #include "TSRM.h" #endif PHP_MINIT_FUNCTION(bcompiler); PHP_MSHUTDOWN_FUNCTION(bcompiler); PHP_RINIT_FUNCTION(bcompiler); PHP_RSHUTDOWN_FUNCTION(bcompiler); PHP_MINFO_FUNCTION(bcompiler); /* __function_declarations_here__ */ PHP_FUNCTION(confirm_bcompiler_compiled); /* For testing, remove later. */ PHP_FUNCTION(bcompile_write_class); /* Write a class */ PHP_FUNCTION(bcompile_write_header); /* Write the header */ PHP_FUNCTION(bcompile_write_exe_footer); /* Write the end zero byte */ PHP_FUNCTION(bcompile_write_footer); /* Write the tail for a exe type file*/ PHP_FUNCTION(bcompile_read); /* Read a file handle */ PHP_FUNCTION(bcompile_load); /* Read a file handle */ PHP_FUNCTION(bcompile_load_exe); /* Read a file handle */ PHP_FUNCTION(bcompile_parse_class); /* Write a class */ /* Declare any global variables you may need between the BEGIN and END macros here: */ ZEND_BEGIN_MODULE_GLOBALS(bcompiler) void *stream; /* output stream */ char* buffer; /* our read buffer */ zval* callback; /* callback for parser */ zval* callback_value; /* callback for grouped calls */ char* callback_key; /* callback key for associated vals*/ ZEND_END_MODULE_GLOBALS(bcompiler) #include "zend.h" #include "zend_variables.h" // for zval_dtor() /* In every utility function you add that needs to use variables in php_bcompiler_globals, call TSRM_FETCH(); after declaring other variables used by that function, or better yet, pass in TSRMG_CC after the last function argument and declare your utility function with TSRMLS_DC after the last declared argument. Always refer to the globals in your function as COMPILER_G(variable). You are encouraged to rename these macros something shorter, see examples in any other php module directory. */ #ifdef ZTS #define BCOMPILERG(v) TSRMG(bcompiler_globals_id, zend_bcompiler_globals *, v) #else #define BCOMPILERG(v) (bcompiler_globals.v) #endif typedef void* (*apc_malloc_t)(int); /* By convention all apc_serialize_* functions serialize objects of the * specified type to the serialization buffer (dst). The apc_deserialize_* * functions deserialize objects of the specified type from the * deserialization buffer (src). The apc_create_* functions allocate * objects of the specified type, then call the appropriate deserialization * function. */ void bcompiler_read(TSRMLS_DC); /* general */ void apc_serialize_string(char* string TSRMLS_DC); void apc_create_string(char** string TSRMLS_DC); void apc_serialize_zstring(char* string, int len TSRMLS_DC); void apc_create_zstring(char** string TSRMLS_DC); void apc_serialize_arg_types(zend_uchar* arg_types TSRMLS_DC); void apc_create_arg_types(zend_uchar** arg_types TSRMLS_DC); /* pre-bcompiler routines */ void apc_serialize_magic(TSRMLS_DC); int apc_deserialize_magic(TSRMLS_DC); /* routines for handling structures from zend_llist.h */ void apc_serialize_zend_llist(zend_llist* list TSRMLS_DC); void apc_deserialize_zend_llist(zend_llist* list TSRMLS_DC); void apc_create_zend_llist(zend_llist** list TSRMLS_DC); /* routines for handling structures from zend_hash.h */ void apc_serialize_hashtable(HashTable* ht, void* funcptr TSRMLS_DC); void apc_deserialize_hashtable(HashTable* ht, void* funcptr, void* dptr, int datasize, char exists TSRMLS_DC); void apc_create_hashtable(HashTable** ht, void* funcptr, void* dptr, int datasize TSRMLS_DC); /* routines for handling structures from zend.h */ void apc_serialize_zvalue_value(zvalue_value* zvv, int type TSRMLS_DC); void apc_deserialize_zvalue_value(zvalue_value* zvv, int type TSRMLS_DC); void apc_serialize_zval_ptr(zval** zv TSRMLS_DC); void apc_serialize_zval(zval* zv TSRMLS_DC); void apc_deserialize_zval(zval* zv TSRMLS_DC); void apc_create_zval(zval** zv TSRMLS_DC); void apc_free_zval(zval** zv TSRMLS_DC); void apc_serialize_zend_function_entry(zend_function_entry* zfe TSRMLS_DC); void apc_deserialize_zend_function_entry(zend_function_entry* zfe TSRMLS_DC); void apc_serialize_zend_property_reference(zend_property_reference* zpr TSRMLS_DC); void apc_deserialize_zend_property_reference(zend_property_reference* zpr TSRMLS_DC); void apc_serialize_zend_overloaded_element(zend_overloaded_element* zoe TSRMLS_DC); void apc_deserialize_zend_overloaded_element(zend_overloaded_element* zoe TSRMLS_DC); void apc_serialize_zend_class_entry(zend_class_entry* zce TSRMLS_DC); void apc_deserialize_zend_class_entry(zend_class_entry* zce TSRMLS_DC); void apc_create_zend_class_entry(zend_class_entry** zce TSRMLS_DC); /* routines for handling structures from zend_compile.h */ void apc_serialize_znode(znode* zn TSRMLS_DC); void apc_deserialize_znode(znode* zn TSRMLS_DC); void apc_serialize_zend_op(int i, zend_op* zo TSRMLS_DC); void apc_deserialize_zend_op(zend_op* zo TSRMLS_DC); void apc_serialize_zend_op_array(zend_op_array* zoa TSRMLS_DC); void apc_deserialize_zend_op_array(zend_op_array* zoa, int master TSRMLS_DC); void apc_create_zend_op_array(zend_op_array** zoa TSRMLS_DC); void apc_serialize_zend_internal_function(zend_internal_function* zif TSRMLS_DC); void apc_deserialize_zend_internal_function(zend_internal_function* zif TSRMLS_DC); void apc_serialize_zend_overloaded_function(zend_overloaded_function* zof TSRMLS_DC); void apc_deserialize_zend_overloaded_function(zend_overloaded_function* zof TSRMLS_DC); void apc_serialize_zend_function(zend_function* zf TSRMLS_DC); void apc_deserialize_zend_function(zend_function* zf TSRMLS_DC); void apc_create_zend_function(zend_function** zf TSRMLS_DC); void apc_free_zend_function(zend_function** zf TSRMLS_DC); /* special purpose */ void apc_serialize_zend_function_table(HashTable* gft TSRMLS_DC); void apc_deserialize_zend_function_table(HashTable* gft TSRMLS_DC); void apc_serialize_zend_class_table(HashTable* gct TSRMLS_DC); int apc_deserialize_zend_class_table(HashTable* gct TSRMLS_DC); void apc_fixup_opcodes(zend_op* opcodes, int num_ops, apc_malloc_t ctor TSRMLS_DC); void apc_fixup_class_table(HashTable* ht, apc_malloc_t ctor TSRMLS_DC); void apc_free_string(char **ptr TSRMLS_DC); void apc_serialize_debug(char * string TSRMLS_DC); #endif /* PHP_BCOMPILER_H */ /* __footer_here__ */ Index: pear/PECL/bcompiler/examples/bcompiler.php +++ pear/PECL/bcompiler/examples/bcompiler.php <? if(!extension_loaded('bcompiler')) { dl('bcompiler.so'); } require_once('DB.php'); $fh = fopen("/tmp/testcompile","w"); bcompile_write_header($fh); bcompile_write_class($fh,'DB'); bcompile_write_class($fh,'PEAR_error'); bcompile_write_class($fh,'DB_error'); fclose($fh); $fh = bzopen("/tmp/testcompileb","w"); bcompile_write_header($fh); bcompile_write_class($fh,'DB'); bcompile_write_class($fh,'PEAR_error'); bcompile_write_class($fh,'DB_error'); fclose($fh); $fh = fopen("/tmp/testcompile2","w"); $fc = fopen(dirname(__FILE__)."/code","r"); $data = fread($fc,filesize(dirname(__FILE__)."/code")); fwrite($fh,$data, filesize(dirname(__FILE__)."/code")); fclose($fc); $start = ftell($fh); $bz = bzopen($fh,"w"); bcompile_write_header($bz); bcompile_write_class($bz,'DB'); bcompile_write_class($bz,'PEAR_error'); bcompile_write_class($bz,'DB_error'); bcompile_write_footer($bz); fclose($bz); $fh= fopen("/tmp/testcompile2","a"); fseek($fh,0,SEEK_END); bcompile_write_exe_footer($fh,$start); fclose($fh); ?> Done Index: pear/PECL/bcompiler/examples/bcompiler_parse.php +++ pear/PECL/bcompiler/examples/bcompiler_parse.php <? if(!extension_loaded('bcompiler')) { dl('bcompiler.so'); } require_once('DB.php'); define('ZEND_FETCH_GLOBAL', 0); define('ZEND_FETCH_LOCAL', 1); define('ZEND_FETCH_STATIC', 2); /* var status for backpatching */ define('BP_VAR_R', 0); define('BP_VAR_W', 1); define('BP_VAR_RW', 2); define('BP_VAR_IS', 3); define('BP_VAR_NA', 4); /* if not applicable */ define('BP_VAR_FUNC_ARG', 5); define('BP_VAR_UNSET', 6); define('ZEND_IS_CONST' ,1); define('ZEND_IS_TMP_VAR' ,2); define('ZEND_IS_VAR' ,4); define('ZEND_IS_UNUSED' ,8); /* Unused variable */ function test($data) { global $generator; if (@$data['ISEND']) { //print_r($data); if ($generator->_opcodes) { $generator->_pass_two(); } //echo "NEW GENERATOR"; $generator = new generator; } /* echo " "; echo @str_pad($data['LINE'],4) . ":"; echo str_pad($data['OPCODE'],4); echo str_pad($data['OPCODE_STR'],20); if (@$data['HASH'] || @$data['CLASS']) { echo " ".@$data['HASH'] . " ". @$data['CLASS'] ; } echo ":"; echo str_pad(@$data['RESULT'] ,15); echo "= "; echo str_pad(@$data['OP1'] ,15); echo str_pad(@$data['OP2'] ,15); */ $generator->_add_op($data); echo "\n"; //print_r($data); } $generator = new generator; $classname = "vending_omnitor"; bcompile_parse_class('test','DB'); class generator { var $zend_to_realname; var $realname_to_zend; var $args; var $function_name; var $_fcall; // funciton about to be called. var $send_vars = array(); var $_gotos = array(); var $init_opcode; // initilized opcode var $Ts = array(); var $_init_static_vars = FALSE; var $_string_buffer; // deprecieated function op_begin_hash_def($d) { // //$this->function_name = $d['HASH']; } function op_opcode_array($d) { // expects an op array... if (!$d) { return; } global $classname; $this->init_opcode = unserialize(serialize($d)); $this->function_name = $d['FUNCTION_NAME']; $this->_out2("",TRUE); $this->_out2("PHP_FUNCTION({$classname}_".$d['FUNCTION_NAME']. ")\n{"); ## TODO = the base_function stuff needs sorting out - re: pointer or what... $out = " /* dummy op codes */ znode* result= (zend_op*) emalloc(sizeof(znode)); znode* op1= (zend_op*) emalloc(sizeof(znode)); znode* op2= (zend_op*) emalloc(sizeof(znode)); zval* result_zv = (zval*) emalloc(sizeof(zval)); zval* op1_zv = (zval*) emalloc(sizeof(zval)); zval* op2_zv = (zval*) emalloc(sizeof(zval)); zvalue* result_zvalue = (zval*) emalloc(sizeof(zvalue)); zvalue* op1_zvalue = (zval*) emalloc(sizeof(zvalue)); zvalue* op2_zvalue = (zval*) emalloc(sizeof(zvalue)); int extended_value = 0; zend_execute_data execute_data; zend_function base_function; /* not really sure how this is needed.....*/ base_function.type = {$d['TYPE']} ; base_function.function_name = \"{$d['FUNCTION_NAME']}\"; EG(execute_data_ptr) = &execute_data; /* Initialize execute_data */ execute_data.fbc = NULL; execute_data.object.ptr = NULL; execute_data.Ts = (temp_variable *) do_alloca(sizeof(temp_variable)*".$d['T']."); execute_data.original_in_execution=EG(in_execution); EG(in_execution) = 1; /* EG(opline_ptr) = &execute_data.opline; */ execute_data.function_state.function = base_function; EG(function_state_ptr) = &execute_data.function_state; "; $this->_out2($out); if (@$this->args) { $out = " if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \""; $start_optional = FALSE; foreach($this->args as $d) { //print_r($d); if ($d['OPCODE'] == 64) { // RECV_INIT if (!$start_optional) { $out .= "|"; $start_optional = TRUE; } } $out .= "z"; } $out .= "\" "; foreach($this->args as $d) { $out .= ", &". $this->_get_zval_ptr_ptr("RESULT", $d) ; } $out .=")== FAILURE) return;"; $this->_out2($out); /* initialize values */ foreach($this->args as $d) { if ($d['OPCODE'] != 64) { // RECV_INIT continue; } if (($d["OP2.u.constant.type"] == IS_CONSTANT) || ($d["OP2.u.constant.type"]==IS_CONSTANT_ARRAY)) { echo "NOT SUPPORTED YET"; exit; } else { // lets hope it was a string! $this->_out2(" if (ZEND_NUM_ARGS() < {$d['OP1']}) { "); $this->_assign_zval("execute_data.Ts[{$d['RESULT.u.var']}].tmp_var",$d['OP2.u.constant.val']); $this->_out2(" } "); } } } } function op_add_string($d) { list($free,$var) = $this->_get_zval_ptr("OP1",$d); $this->_out2(" add_string_to_string( execute_data.Ts[". $d["RESULT.u.var"]."].tmp_var, ". $var . ", \"". $d["OP2.u.constant.val"] . "\")"); } function op_add_var($d) { list($free, $var2) = $this->_get_zval_ptr("OP2",$d); list($free, $var1) = $this->_get_zval_ptr("OP1",$d); $this->_out2(" { zval var_copy; int use_copy; zval *var = $var2 zend_make_printable_zval(var, &var_copy, &use_copy); if (use_copy) { var = &var_copy; } add_string_to_string( &execute_data.Ts[". $d["RESULT.u.var"]."].tmp_var, $var1, var); if (use_copy) { zval_dtor(var); } } "); // FREE_OP(execute_data.Ts, &EX(opline)->op2, EG(free_op2)); } function op_assign($d) { //print_r($d); /* ??? what if its an int or something? */ //$string_to_use = $this->_string_buffer[$d['OP2']]; //$args_to_use = $this->_string_buffer_args[$d['OP2']]; //$var = $this->zend_to_realname[$d['OP1']]; //$this->_out( " $var = sprintf(\"{$string_to_use}\",". implode(",",$args_to_use).");"); $this->_out2(" { "); $this->_make_opcode("RESULT",$d); $this->_make_opcode("OP1",$d); $this->_make_opcode("OP2",$d); $this->_out2(" zval *value; value = get_zval_ptr(op2, execute_data.Ts, &EG(free_op2), BP_VAR_R); zend_assign_to_variable(result, op1, op2, value, (EG(free_op2)?IS_TMP_VAR:{$d['OP2.op_type']}), execute_data.Ts TSRMLS_CC); } "); } function op_assign_ref($d) { $this->_make_opcode("RESULT",$d); $this->_make_opcode("OP1",$d); $this->_make_opcode("OP2",$d); $this->_out2(" zend_assign_to_variable_reference(result, get_zval_ptr_ptr(&op1, execute_data.Ts, BP_VAR_W), get_zval_ptr_ptr(&op2, execute_data.Ts, BP_VAR_W), execute_data.Ts TSRMLS_CC); "); } function op_bool_not($d) { $this->_make_opcode('OP1',$d); $this->_out2(" EG(unary_op) = get_unary_op({$d['OPCODE']}); EG(unary_op)(&execute_data.Ts[{$d['RESULT.u.var']}].tmp_var, get_zval_ptr(op1, execute_data.Ts, &EG(free_op1), BP_VAR_R) ); FREE_OP(execute_data.Ts, &op1, EG(free_op1)); "); } function op_do_fcall($d) { $this->_make_opcode("OP1",$d); $this->_out2(" { zval *fname = get_zval_ptr(&op1, execute_data.Ts, &EG(free_op1), BP_VAR_R); if (zend_hash_find(EG(function_table), fname->value.str.val, fname->value.str.len+1, (void **) &execute_data.function_state.function)==FAILURE) { zend_error(E_ERROR, \"Unknown function: %s()\n\", fname->value.str.val); } FREE_OP(execute_data.Ts, &op1, EG(free_op1)); zend_ptr_stack_push(&EG(arg_types_stack), execute_data.object.ptr); execute_data.object.ptr = NULL; "); $this->_do_fcall_common($d); $this->_out2(" } "); } function op_do_fcall_by_name($d) { if ($this->_fcall) { /* object + array! */ $this->_out2(" call_user_function_ex(CG(function_table), execute_data.Ts[{$this->_fcall['OP1.u.var']}].var.ptr, \"{$this->_fcall['OP2.u.constant.val']}\", execute_data.Ts[{$d['RESULT.u.var']}].var.ptr, 0, NULL, 0); "); } print_r($d); return; $this->_out2(" execute_data.function_state.function = execute_data.fbc; "); $this->_do_fcall_common($d); } function op_echo($d) { list ($free, $var) = $this->_get_zval_ptr("OP1",$d); //zend_print_variable(get_zval_ptr(&EX(opline)->op1, EX(Ts), &EG(free_op1), BP_VAR_R)); if ($var{0} == '"') { $this->_out2(" zend_write({$var}, ".(strlen($var)-1) ."); "); } else { $this->_out2(" zend_print_variable($var); "); //FREE_OP(EX(Ts), &EX(opline)->op1, EG(free_op1)); } } function op_fetch_w ($d) { // zend_fetch_var_address(EX(opline), execute_data.Ts, BP_VAR_W TSRMLS_CC); // initialize a new variable of type $d[op2].type // result: is set to refer to it.. $this->_fetch_var_address($d, BP_VAR_W); //$this->zend_to_realname[$d['RESULT']] = $d['OP1']; //$this->realname_to_zend[$d['OP1']] = $d['RESULT']; } function op_fetch_r($d) { $this->_fetch_var_address($d, BP_VAR_R); //$this->zend_to_realname[$d['RESULT']] = $d['OP1']; //if (!@$this->realname_to_zend[$d['OP1']]) { // $this->realname_to_zend[$d['OP1']] = $d['RESULT']; //} } function op_fetch_constant($d) { $starterror = $GLOBALS['php_errormsg']; $const = @constant($d['OP1.u.constant.val']); if ($starterror != $GLOBALS['php_errormsg']) { echo "NOT A CONSTANT: {$d['OP1.u.constant.val']}"; exit; } $this->_assign_zval("execute_data.Ts[{$d['RESULT.u.var']}].tmp_var",$const); } function op_init_string($d) { $this->_out2( " execute_data.Ts[". $d['RESULT.u.var'] . "].tmp_var.value.str.val = emalloc(1); execute_data.Ts[". $d['RESULT.u.var'] . "].tmp_var.value.str.val[0] = 0; execute_data.Ts[". $d['RESULT.u.var'] . "].tmp_var.value.str.len = 0; execute_data.Ts[". $d['RESULT.u.var'] . "].tmp_var.refcount = 1; "); } function op_init_fcall_by_name($d) { /* handle these types: */ $this->_fcall = unserialize(serialize($d)); return; $this->_make_opcode("OP1",$d); $this->_make_opcode("OP2",$d); $this->_out2(" zval *function_name; zend_function *function; HashTable *active_function_table; zval tmp; zend_ptr_stack_n_push(&EG(arg_types_stack), 2, execute_data.fbc, execute_data.object.ptr); if ({$d['EXTENDED']} & ZEND_CTOR_CALL) { /* constructor call */ if ({$d['OP1.op_type']} == IS_VAR) { SELECTIVE_PZVAL_LOCK(*execute_data.Ts[{$d['OP1.u.var']}].var.ptr_ptr, &op1); } if ({$d['OP2.op_type']} == IS_VAR) { PZVAL_LOCK(*execute_data.Ts[{$d['OP1.u.var']}].var.ptr_ptr); } } function_name = get_zval_ptr(&op2, execute_data.Ts, &EG(free_op2), BP_VAR_R); tmp = *function_name; zval_copy_ctor(&tmp); convert_to_string(&tmp); function_name = &tmp; zend_str_tolower(tmp.value.str.val, tmp.value.str.len); if ({$d['OP1.op_type']} != IS_UNUSED) { if ({$d['OP1.op_type']}==IS_CONST) { /* used for class_name::function() */ zend_class_entry *ce; zval **object_ptr_ptr; if (zend_hash_find(EG(active_symbol_table), \"this\", sizeof(\"this\"), (void **) &object_ptr_ptr)==FAILURE) { execute_data.object.ptr=NULL; } else { /* We assume that \"this\" is already is_ref and pointing to the object. If it isn't then tough */ execute_data.object.ptr = *object_ptr_ptr; execute_data.object.ptr->refcount++; /* For this pointer */ } if (zend_hash_find(EG(class_table), \"{$d['OP1.u.constant.val']}\", ". (strlen($d['OP1.u.constant.val'])+1). ", (void **) &ce)==FAILURE) { /* class doesn't exist */ zend_error(E_ERROR, \"Undefined class name '%s'\", {$d['OP1.u.constant.val']}); } active_function_table = &ce->function_table; } else { /* used for member function calls */ execute_data.object.ptr = _get_object_zval_ptr(&op1, execute_data.Ts, &EG(free_op1) TSRMLS_CC); if ((!execute_data.object.ptr && execute_data.Ts[{$d['OP1.u.var']}].EA.type==IS_OVERLOADED_OBJECT) || ((execute_data.object.ptr && execute_data.object.ptr->type==IS_OBJECT) && (execute_data.object.ptr->value.obj.ce->handle_function_call))) { /* overloaded function call */ zend_overloaded_element overloaded_element; overloaded_element.element = *function_name; overloaded_element.type = OE_IS_METHOD; if (execute_data.object.ptr) { execute_data.Ts[{$d['OP1.u.var']}].EA.data.overloaded_element.object = execute_data.object.ptr; execute_data.Ts[{$d['OP1.u.var']}].EA.data.overloaded_element.type = BP_VAR_NA; execute_data.Ts[{$d['OP1.u.var']}].EA.data.overloaded_element.elements_list = (zend_llist *) emalloc(sizeof(zend_llist)); zend_llist_init(execute_data.Ts[{$d['OP1.u.var']}].EA.data.overloaded_element.elements_list, sizeof(zend_overloaded_element), NULL, 0); } zend_llist_add_element(execute_data.Ts[{$d['OP1.u.var']}].EA.data.overloaded_element.elements_list, &overloaded_element); execute_data.fbc = (zend_function *) emalloc(sizeof(zend_function)); execute_data.fbc->type = ZEND_OVERLOADED_FUNCTION; execute_data.fbc->common.arg_types = NULL; execute_data.fbc->overloaded_function.var = {$d['OP1.u.var']}; goto overloaded_function_call_cont; } if (!execute_data.object.ptr || execute_data.object.ptr->type != IS_OBJECT) { zend_error(E_ERROR, \"Call to a member function on a non-object\"); } if (!execute_data.object.ptr->is_ref && execute_data.object.ptr->refcount > 1) { zend_error(E_ERROR, \"Bug: Problem in method call\n\"); } execute_data.object.ptr->is_ref=1; execute_data.object.ptr->refcount++; /* For $ this pointer */ active_function_table = &(execute_data.object.ptr->value.obj.ce->function_table); } } else { /* function pointer */ execute_data.object.ptr = NULL; active_function_table = EG(function_table); } if (zend_hash_find(active_function_table, function_name->value.str.val, function_name->value.str.len+1, (void **) &function)==FAILURE) { zend_error(E_ERROR, \"Call to undefined function: %s()\", function_name->value.str.val); } zval_dtor(&tmp); execute_data.fbc = function; overloaded_function_call_cont: FREE_OP(execute_data.Ts, &op2, EG(free_op2)); } "); } function op_include_or_eval($d) { $string_to_use = $this->_string_buffer[$d['OP1']]; $args_to_use = $this->_string_buffer_args[$d['OP1']]; $this->_out2( " /* NOT SUPPORTED !*/"); // $this->_out2( " /*tmpstring = sprintf(\"{$string_to_use}\",". implode(",",$args_to_use).");*/"); $this->_out2( " /* zend_include_file(tmpstring);*/"); $this->_out2( " /* END NOT SUPPORTED */"); } function op_return($d) { //$this->init_opcode['return_reference'] $this->_out2( " { zval *retval_ptr; zval **retval_ptr_ptr; "); if (( $this->init_opcode['return_reference'] == 1) && ($d['OP1.op_type'] != IS_CONST) && ($d['OP1.op_type'] != IS_TMP_VAR)) { $this->_make_opcode("OP1",$d); $this->_out2(" retval_ptr_ptr = get_zval_ptr_ptr(&op1, execute_data.Ts), BP_VAR_W); SEPARATE_ZVAL_TO_MAKE_IS_REF(retval_ptr_ptr); (*retval_ptr_ptr)->refcount++; (*EG(return_value_ptr_ptr)) = (*retval_ptr_ptr); "); } else { $this->_make_opcode("OP1",$d); $this->_out2(" retval_ptr = get_zval_ptr(&op1, execute_data.Ts, &EG(free_op1), BP_VAR_R); if (!EG(free_op1)) { /* Not a temp var */ if (PZVAL_IS_REF(retval_ptr) && retval_ptr->refcount > 0) { ALLOC_ZVAL(*(EG(return_value_ptr_ptr))); **EG(return_value_ptr_ptr) = *retval_ptr; (*EG(return_value_ptr_ptr))->is_ref = 0; (*EG(return_value_ptr_ptr))->refcount = 1; zval_copy_ctor(*EG(return_value_ptr_ptr)); } else { *EG(return_value_ptr_ptr) = retval_ptr; retval_ptr->refcount++; } } else { ALLOC_ZVAL(*(EG(return_value_ptr_ptr))); **EG(return_value_ptr_ptr) = *retval_ptr; (*EG(return_value_ptr_ptr))->refcount = 1; (*EG(return_value_ptr_ptr))->is_ref = 0; } "); } $this->_out2(" free_alloca(execute_data.Ts); EG(in_execution) = execute_data.original_in_execution; return; } "); } function op_jmp($d) { if (($d['JMP']-1) == $d['LINE']) { return; } $this->_gotos[$d['JMP']] = 1; $this->_out( " goto line_".$d['JMP']) ; } function op_jmpz($d) { $this->_make_opcode("OP1",$d); $this->_out2(" if (!i_zend_is_true(get_zval_ptr(op1, execute_data.Ts, &EG(free_op1), BP_VAR_R))) { FREE_OP(execute_data.Ts, op1, EG(free_op1)); goto line_{$d['OP2.u.opline_num']}; } FREE_OP(execute_data.Ts, op1, EG(free_op1)); "); $this->_gotos[$d['JMP']] = 1; } function op_jmp_no_ctor($d) { // jump past object initialization call if it doesnt exist. list($free,$var) = $this->_get_zval_ptr("OP1", $d); $this->_out2(" if (!{$var}->value.obj.ce->handle_function_call && !zend_hash_exists(&{$var}->value.obj.ce->function_table, {$var}->value.obj.ce->name, {$var}->value.obj.ce->name_length+1)) { goto line_{$d['OP2.u.opline_num']}; } "); return; $this->_out2(" { zval *object; "); if ($d['OP1.op_type'] == IS_VAR) { $this->_out2(" PZVAL_LOCK(*execute_data.Ts[{$d['OP1.u.var']}].var.ptr_ptr); "); } $this->_make_opcode("OP1",$d); //print_r($d); //exit; $this->_out2(" object = get_zval_ptr(&op1, execute_data.Ts, &EG(free_op1), BP_VAR_R); if (!object->value.obj.ce->handle_function_call && !zend_hash_exists(&object->value.obj.ce->function_table, object->value.obj.ce->name, object->value.obj.ce->name_length+1)) { goto line_{$d['OP2.u.opline_num']}; } } "); $this->_gotos[$d['OP2.u.opline_num']] = 1; } function op_new($d) { list($free,$var) = $this->_get_zval_ptr("OP1", $d); if ($var{0} == '"') { //echo "GOT STRING $var"; $lvar = strtolower($var); $this->_out2( " { zend_class_entry *ce; zend_hash_find(EG(class_table), $lvar, ".(strlen($var) -1).", (void **) &ce); execute_data.Ts[{$d['RESULT.u.var']}].var.ptr_ptr = &execute_data.Ts[{$d['RESULT.u.var']}].var.ptr; ALLOC_ZVAL(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); object_init_ex(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr, ce); execute_data.Ts[{$d['RESULT.u.var']}].var.ptr->refcount=1; execute_data.Ts[{$d['RESULT.u.var']}].var.ptr->is_ref=1; } "); return; } $this->_make_opcode("OP1", $d); $this->_out2(" { zval *tmp = get_zval_ptr(&op1, execute_data.Ts, &EG(free_op1), BP_VAR_R); zval class_name; zend_class_entry *ce; class_name = *tmp; zval_copy_ctor(&class_name); convert_to_string(&class_name); zend_str_tolower(class_name.value.str.val, class_name.value.str.len); if (zend_hash_find(EG(class_table), class_name.value.str.val, class_name.value.str.len+1, (void **) &ce)==FAILURE) { zend_error(E_ERROR, \"Cannot instantiate non-existent class: %s\", class_name.value.str.val); } execute_data.Ts[{$d['RESULT.u.var']}].var.ptr_ptr = &execute_data.Ts[{$d['RESULT.u.var']}].var.ptr; ALLOC_ZVAL(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); object_init_ex(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr, ce); execute_data.Ts[{$d['RESULT.u.var']}].var.ptr->refcount=1; execute_data.Ts[{$d['RESULT.u.var']}].var.ptr->is_ref=1; zval_dtor(&class_name); FREE_OP(execute_data.Ts, &op1, EG(free_op1)); } "); } function op_recv($d) { //print_r($d); $this->args[$d['OP1.u.constant.val'] ] = $d; } function op_recv_init($d) { $this->args[$d['OP1.u.constant.val'] ] = unserialize(serialize($d)); } function op_send_var($d) { $this->_make_opcode("OP1",$d); $this->_out2(" if (({$d['EXTENDED']} == ZEND_DO_FCALL_BY_NAME) && ARG_SHOULD_BE_SENT_BY_REF({$d['OP2.u.opline_num']}, execute_data.fbc , execute_data.fbc->common.arg_types)) { zval **varptr_ptr; zval *varptr; varptr_ptr = get_zval_ptr_ptr(&op1,execute_data.Ts, BP_VAR_W); if (!varptr_ptr) { zend_error(E_ERROR, \"Only variables can be passed by reference\"); } SEPARATE_ZVAL_TO_MAKE_IS_REF(varptr_ptr); varptr = *varptr_ptr; varptr->refcount++; zend_ptr_stack_push(&EG(argument_stack), varptr); } else { zval *varptr; varptr = get_zval_ptr(&op1, execute_data.Ts, &EG(free_op1), BP_VAR_R); if (varptr == &EG(uninitialized_zval)) { ALLOC_ZVAL(varptr); INIT_ZVAL(*varptr); varptr->refcount = 0; } else if (PZVAL_IS_REF(varptr)) { zval *original_var = varptr; ALLOC_ZVAL(varptr); *varptr = *original_var; varptr->is_ref = 0; varptr->refcount = 0; zval_copy_ctor(varptr); } varptr->refcount++; zend_ptr_stack_push(&EG(argument_stack), varptr); FREE_OP(execute_data.Ts, op1, EG(free_op1)); } "); } function op_send_val($d) { $this->_make_opcode("OP1",$d); $this->_out2(" if ({$d['EXTENDED']} == ZEND_DO_FCALL_BY_NAME && ARG_SHOULD_BE_SENT_BY_REF({$d['OP2.u.opline_num']}, execute_data.fbc , execute_data.fbc->common.arg_types)) { zend_error(E_ERROR, \"Cannot pass parameter %d by reference\", {$d['OP2.u.opline_num']}); } { zval *valptr; zval *value; value = get_zval_ptr(op1, execute_data.Ts, &EG(free_op1), BP_VAR_R); ALLOC_ZVAL(valptr); *valptr = *value; if (!EG(free_op1)) { zval_copy_ctor(valptr); } INIT_PZVAL(valptr); zend_ptr_stack_push(&EG(argument_stack), valptr); } "); } /* ---------------NON OP CODES ------------*/ var $_opcodes = array(); var $_pass = 0; function _add_op($d) { if ($d['LINE'] != -1) { $this->_opcodes[$d['LINE']] = $d; } $this->_do_op($d); } function _do_op($data) { $this->_outComment($data); if (@$this->_gotos[$data['LINE']]) { $this->_out2("line_{$data['LINE']}:",FALSE); } $op = "op_".strtolower(trim($data['OPCODE_STR'])); if (method_exists($this, $op)) { $this->$op($data); } else { if (!$this->_pass) { $this->_out2("/* --TODO--*/"); } } } function _out($s,$do_cr=TRUE) { //if ($this->_pass != 0) { echo $s; if ($do_cr) { echo "\n"; } //} } function _out2($data) { if (!$this->_pass) return; echo "$data\n"; } function _outComment($data) { $this->_out2(" /*". str_pad($data['LINE'],4) . ":" . //str_pad($data['OPCODE'],4) . str_pad($data['OPCODE_STR'],20) . ":". str_pad(@$data['RESULT'] ,15) . "= " . str_pad(@$data['OP1'] ,15) . "," . str_pad(@$data['OP2'] ,15) . "*/" ); } function _pass_two() { echo "\n\n--------------------------------------------------\n\n"; $this->_pass=1; //print_r($this->_opcodes); global $classname; $this->op_opcode_array($this->init_opcode); foreach($this->_opcodes as $data) { $this->_do_op($data); } $this->_out("}"); echo "\n\n--------------------------------------------------\n\n"; } function _set_zendvalue($zend,$real) { $this->zend_to_realname[$zend] = $real; $this->realname_to_zend[$real] = $zend; } function _get_zendvalue($zend) { return @$this->zend_to_realname[$zend]; } function _init_static_vars() { if ($this->_init_static_vars) { return; } $this->_out2(" /* make sure static variables are initialized */ if (!EG(active_op_array)->static_variables) { ALLOC_HASHTABLE(EG(active_op_array)->static_variables); zend_hash_init(EG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } "); $this->_init_static_vars = TRUE; } function _get_zval_ptr($opcode, $d) { switch ($d[$opcode.".op_type"]) { case 1: //ZEND_IS_CONST: /* probably need to make a zval here */ //echo "CONST?".$d[$opcode.".u.constant.val"]; return array(0,"\"".$d[$opcode.".u.constant.val"]."\""); case 2: //ZEND_IS_TMP_VAR: return array(0,"(&execute_data.Ts[".$d[$opcode.".u.var"]."].tmp_var)"); case 4: //ZEND_IS_VAR: //if (@$this->Ts[$d[$opcode.".u.var"]]["var.ptr"]) { /*PZVAL_UNLOCK(Ts[node->u.var].var.ptr); */ return array(0,"(execute_data.Ts[".$d[$opcode.".u.var"]."].var.ptr)"); //} //print_r($d); //echo "\nUNHANDLED VAR : see get_zval_ptr\n"; exit; default: echo "Unknown type ". $d[$opcode.".op_type"]; exit; } } function _get_zval_ptr_ptr($opcode, $d) { return "execute_data.Ts[".((int) $d[$opcode.".u.var"]) ."].var.ptr_ptr"; } function _fetch_var_address($d,$type) { // variable can be string or a $this->_out2('',TRUE); list($free_op1, $varname ) = $this->_get_zval_ptr("OP1",$d); /* determine where to look for variable */ //echo "GOT: :".$varname; switch ($d['OP2.u.fetch_type']) { case 1://ZEND_FETCH_LOCAL: $target_symbol_table = "EG(active_symbol_table)"; break; case 0://ZEND_FETCH_GLOBAL: /* acutal code does some locking? if (opline->op1.op_type == IS_VAR) { PZVAL_LOCK(varname); }*/ $target_symbol_table = "EG(symbol_table)"; break; case 2://ZEND_FETCH_STATIC: $this->_init_static_vars(); $target_symbol_table = "EG(active_op_array)->static_variables"; break; } /* if (varname->type != IS_STRING) { tmp_varname = *varname; zval_copy_ctor(&tmp_varname); convert_to_string(&tmp_varname); varname = &tmp_varname; } */ $varname_str = "{$varname}->value.str.val"; $varname_len = "{$varname}->value.str.len+1"; if ($varname{0} == '"') { $varname_str = $varname; $varname_len = strlen($varname) +1 ; } $this->_out2(" if (zend_hash_find($target_symbol_table, {$varname_str}, {$varname_len}, (void **) &execute_data.Ts[{$d['RESULT.u.var']}].var.ptr_ptr) == FAILURE) {",TRUE); switch($type) { case BP_VAR_R: /*zend_error(E_NOTICE,"Undefined variable: %s", varname->value.str.val); */ /* break missing intentionally */ case BP_VAR_IS: $this->_out2(" execute_data.Ts[{$d['RESULT.u.var']}].var.ptr_ptr = &EG(uninitialized_zval_ptr);",TRUE); break; case BP_VAR_RW: /*zend_error(E_NOTICE,"Undefined variable: %s", varname->value.str.val); */ /* break missing intentionally */ case BP_VAR_W: { $this->_out2(" zval *new_zval = &EG(uninitialized_zval);",TRUE); $this->_out2(" new_zval->refcount++;",TRUE); $this->_out2(" zend_hash_update({$target_symbol_table}, {$varname_str}, {$varname_len}, &new_zval, sizeof(zval *), (void **) &execute_data.Ts[{$d['RESULT.u.var']}].var.ptr_ptr);",TRUE); } break; } $this->_out2( " }",TRUE); if ($d["OP2.u.fetch_type"] == 1) { //ZEND_FETCH_LOCAL //$this->_out( "FREE_OP(Ts, &opline->op1, free_op1); "); } else if ($d["OP2.u.fetch_type"] == 2) { //ZEND_FETCH_STATIC $this->_out2(" zval_update_constant(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr_ptr, (void *) 1 TSRMLS_CC);"); } } function _make_opcode($op,$d) { /* This is the opcode structure!!! znode.op_type // it could be any one of these.... - union is a optional structure thing znode.u.constant //zval znode.u.var znode.u.opline_num znode.u.op_array; // op_array ??? znode.u.EA.var znode.u.EA.type zval.value // zvalue zval.type // uchar zval.is_ref zval.refcount // union! zvalue.lval zvalue.dval zvalue.str.val zvalue.str.len zvalue.ht zvalue.obj */ // make some space available! - do this at the beginning... $opu= strtolower($op); $this->_out2(" {$opu}.op_type = ".$d["{$op}.op_type"].";"); switch ($d["{$op}.op_type"]) { case 1: //ZEND_IS_CONST: $this->_out2(" {$opu}.u.constant = {$opu}_zv;"); $this->_out2(" {$opu}.u.constant.type = ".$d["{$op}.u.constant.type"].";"); $this->_out2(" {$opu}.u.constant.is_ref = ".$d["{$op}.u.constant.is_ref"].";"); $this->_out2(" {$opu}.u.constant.refcount = ".$d["{$op}.u.constant.refcount"].";"); $this->_out2(" {$opu}.u.constant.value = {$opu}_zvalue;"); switch ($d["{$op}.u.constant.type"]) { case 7://IS_RESOURCE: case 6://IS_BOOL: case 1://IS_LONG: $this->_out2(" {$opu}.u.constant.value.lval = ".$d["{$op}.u.constant.val"].";"); break; case 0://IS_NULL: $this->_out2(" {$opu}.u.constant.value.lval = 0;"); /* null value, do nothing - although just do this anyway*/ break; case 2://IS_DOUBLE: $this->_out2(" {$opu}.u.constant.value.dval = ".$d["{$op}.u.constant.val"].";"); break; case 8://IS_CONSTANT: case 3://IS_STRING: case 10://FLAG_IS_BC: $this->_out2(" {$opu}.u.constant.value.str.val = \"".$d["{$op}.u.constant.val"]."\";"); $this->_out2(" {$opu}.u.constant.value.str.len = ".strlen($d["{$op}.u.constant.val"]).";"); break; case 4://IS_ARRAY: case 9://IS_CONSTANT_ARRAY: case 5://IS_OBJECT: default: echo "UNHANDLED: op_type $op";exit; } break; case 2: //ZEND_IS_TMP_VAR: case 4: //ZEND_IS_VAR: $this->_out2(" {$opu}.u.var = ".$d["{$op}.u.var"].";"); break; default: print_r($d); echo "Unknown type $op ". $d[$opcode.".op_type"]; exit; } } function _assign_zval($name,$value) { switch(gettype($value)) { case "NULL"; $this->_out2(" {$name}.type = 0;"); $this->_out2(" {$name}.lval = 0;"); break; case "boolean"; $this->_out2(" {$name}.type = 6;"); $this->_out2(" {$name}.lval = $value;"); break; case "integer"; $this->_out2(" {$name}.type = 1;"); $this->_out2(" {$name}.lval = $value;"); break; case "double"; $this->_out2(" {$name}.type = 2;"); $this->_out2(" {$name}.dval = $value;"); break; case "string"; $this->_out2(" {$name}.type = 3;"); $this->_out2(" {$name}.val = \"$value\";"); $this->_out2(" {$name}.len = ". (strlen($value) +1) .";"); break; default: echo 'Unhandled zval type '. gettype($value) ." : $name : $value "; exit; } } function _do_fcall_common($d) { $this->_out2(" { zval **original_return_value; int return_value_used = (!({$d['RESULT.u.EA.type']} & EXT_TYPE_UNUSED)); zend_ptr_stack_n_push(&EG(argument_stack), 2, (void *) {$d['EXTENDED']}, NULL); execute_data.Ts[{$d['RESULT.u.var']}].var.ptr_ptr = &execute_data.Ts[{$d['RESULT.u.var']}].var.ptr; if (execute_data.function_state.function->type==ZEND_INTERNAL_FUNCTION) { ALLOC_ZVAL(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); INIT_ZVAL(*(execute_data.Ts[{$d['RESULT.u.var']}.var.ptr)); ((zend_internal_function *) execute_data.function_state.function->handler( {$d['EXTENDED']}, execute_data.Ts[{$d['RESULT.u.var']}].var.ptr, execute_data.object.ptr, return_value_used TSRMLS_CC); if (execute_data.object.ptr) { execute_data.object.ptr->refcount--; } execute_data.Ts[{$d['RESULT.u.var']}].var.ptr->is_ref = 0; execute_data.Ts[{$d['RESULT.u.var']}].var.ptr->refcount = 1; if (!return_value_used) { zval_ptr_dtor(&execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); } } else if (execute_data.function_state.function->type==ZEND_USER_FUNCTION) { /* this is probably not needed as it should never call internal user functions! */ HashTable *calling_symbol_table; execute_data.Ts[{$d['RESULT.u.var']}].var.ptr = NULL; if (EG(symtable_cache_ptr)>=EG(symtable_cache)) { execute_data.function_state.function_symbol_table = *(EG(symtable_cache_ptr)--); } else { ALLOC_HASHTABLE(execute_data.function_state.function_symbol_table); zend_hash_init(execute_data.function_state.function_symbol_table, 0, NULL, ZVAL_PTR_DTOR, 0); } calling_symbol_table = EG(active_symbol_table); EG(active_symbol_table) = execute_data.function_state.function_symbol_table; if ({$d['opcode']}==ZEND_DO_FCALL_BY_NAME && execute_data.object.ptr && execute_data.fbc->type!=ZEND_OVERLOADED_FUNCTION) { zval **this_ptr; zval *null_ptr = NULL; zend_hash_update(execute_data.function_state.function_symbol_table, \"this\", sizeof(\"this\"), &null_ptr, sizeof(zval *), (void **) &this_ptr); if (!PZVAL_IS_REF(execute_data.object.ptr)) { zend_error(E_WARNING, \"Problem with method call - please report this bug\"); } *this_ptr = execute_data.object.ptr; execute_data.object.ptr = NULL; } original_return_value = EG(return_value_ptr_ptr); EG(return_value_ptr_ptr) = execute_data.Ts[{$d['RESULT.u.var']}].var.ptr_ptr; EG(active_op_array) = (zend_op_array *) execute_data.function_state.function; zend_execute(EG(active_op_array) TSRMLS_CC); if (return_value_used && !execute_data.Ts[{$d['RESULT.u.var']}].var.ptr) { ALLOC_ZVAL(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); INIT_ZVAL(*execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); } else if (!return_value_used && execute_data.Ts[{$d['RESULT.u.var']}].var.ptr) { zval_ptr_dtor(&execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); } /*EG(opline_ptr) = &EX(opline); EG(active_op_array) = op_array; */ EG(return_value_ptr_ptr)=original_return_value; if (EG(symtable_cache_ptr)>=EG(symtable_cache_limit)) { zend_hash_destroy(execute_data.function_state.function_symbol_table); FREE_HASHTABLE(execute_data.function_state.function_symbol_table); } else { *(++EG(symtable_cache_ptr)) = execute_data.function_state.function_symbol_table; zend_hash_clean(*EG(symtable_cache_ptr)); } EG(active_symbol_table) = calling_symbol_table; } else { /* ZEND_OVERLOADED_FUNCTION */ ALLOC_ZVAL(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); INIT_ZVAL(*(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr)); call_overloaded_function(&execute_data.Ts[execute_data.fbc->overloaded_function.var], {$d['EXTENDED']}, execute_data.Ts[{$d['RESULT.u.var']}].var.ptr TSRMLS_CC); efree(execute_data.fbc); if (!return_value_used) { zval_ptr_dtor(&execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); } } if ({$d['opcode']} == ZEND_DO_FCALL_BY_NAME) { zend_ptr_stack_n_pop(&EG(arg_types_stack), 2, &execute_data.object.ptr, &execute_data.fbc); } else { execute_data.object.ptr = zend_ptr_stack_pop(&EG(arg_types_stack)); } execute_data.function_state.function = base_function; EG(function_state_ptr) = &execute_data.function_state; zend_ptr_stack_clear_multiple(TSRMLS_C); } } "); } } ?> Index: pear/PECL/bcompiler/examples/bcompiler_read.php +++ pear/PECL/bcompiler/examples/bcompiler_read.php <? if(!extension_loaded('bcompiler')) { dl('bcompiler.so'); } echo "\n\n\n"; //$fh = bzopen("/tmp/testcompile","r"); //bcompile_read($fh); //fclose($fh); //bcompile_load("/tmp/testcompile"); bcompile_load_exe("/tmp/testcompile2"); echo "GOT THIS FAR?\n"; print_r(get_class_methods("vending_dba")); print_r(get_declared_classes()); ?>DONE
Index: pear/PECL/bcompiler/Makefile.in.old +++ pear/PECL/bcompiler/Makefile.in.old LTLIBRARY_NAME = libbcompiler.la LTLIBRARY_SOURCES = bcompiler.c LTLIBRARY_SHARED_NAME = bcompiler.la LTLIBRARY_SHARED_LIBADD = $(BCOMPILER_SHARED_LIBADD) include $(top_srcdir)/build/dynlib.mk Index: pear/PECL/bcompiler/bcompiler.c +++ pear/PECL/bcompiler/bcompiler.c /* ================================================================== * PHP bcompiler Based on APC Cache * Copyright (c) 2000-2001 Community Connect, Inc. * All rights reserved. * ================================================================== * This source code is made available free and without charge subject * to the terms of the QPL as detailed in bundled LICENSE file, which * is also available at http://apc.communityconnect.com/LICENSE. * ================================================================== * php module by Alan Knowles <alan@akbkhome.com> * Daniel Cowgill <dan@mail.communityconnect.com> * George Schlossnagle <george@lethargy.org> * Mike Bretz <mike@metropolis-ag.de> * ================================================================== */ /* __header_here__ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/file.h" #include "php_bcompiler.h" #include "zend.h" #include <stdlib.h> #include <assert.h> #define BCOMPILER_VERSION "0.3" #ifdef PHP_HAVE_STREAMS #define BCOMPILER_STREAMS "s" #else #define BCOMPILER_STREAMS "" #endif #define BCOMPILER_MAGIC_HEADER "bcompiler v" BCOMPILER_VERSION BCOMPILER_STREAMS #define DEBUGLEVEL 0 #if DEBUGLEVEL #define BCOMPILER_DEBUG(args) (printf("DEBUG: "), printf args) #else #define BCOMPILER_DEBUG(args) #endif // If you declare any globals in php_compiler.h uncomment this: ZEND_DECLARE_MODULE_GLOBALS(bcompiler) /* {{{ bcompiler_functions[] * * Every user visible function must have an entry in bcompiler_functions[]. */ function_entry bcompiler_functions[] = { PHP_FE(bcompile_write_header, NULL) /* bCompiler a class and return data.*/ PHP_FE(bcompile_write_class, NULL) /* bCompiler a class and return data.*/ PHP_FE(bcompile_write_footer, NULL) /* bCompiler a class and return data.*/ PHP_FE(bcompile_write_exe_footer, NULL) /* bCompiler a class and return data.*/ PHP_FE(bcompile_read, NULL) /* bCompiler a class and return data.*/ PHP_FE(bcompile_load, NULL) /* bCompiler a class and return data.*/ PHP_FE(bcompile_load_exe, NULL) /* bCompiler a class and return data.*/ PHP_FE(bcompile_parse_class, NULL) /* bCompiler a class and return data.*/ /* __function_entries_here__ */ {NULL, NULL, NULL} /* Must be the last line in compiler_functions[] */ }; /* }}} */ /* {{{ bcompiler_module_entry */ zend_module_entry bcompiler_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "bcompiler", bcompiler_functions, PHP_MINIT(bcompiler), PHP_MSHUTDOWN(bcompiler), PHP_RINIT(bcompiler), /* Replace with NULL if there's nothing to do at request start */ PHP_RSHUTDOWN(bcompiler), /* Replace with NULL if there's nothing to do at request end */ PHP_MINFO(bcompiler), #if ZEND_MODULE_API_NO >= 20010901 BCOMPILER_VERSION BCOMPILER_STREAMS, /* Replace with version number for your extension */ #endif STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_BCOMPILER ZEND_GET_MODULE(bcompiler) #endif /* {{{ PHP_INI */ /* Remove comments and fill if you need to have entries in php.ini PHP_INI_BEGIN() STD_PHP_INI_ENTRY("bcompiler.global_value", "42", PHP_INI_ALL, OnUpdateInt, global_value, zend_bcompiler_globals, bcompiler_globals) STD_PHP_INI_ENTRY("bcompiler.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_bcompiler_globals, bcompiler_globals) PHP_INI_END() */ /* }}} */ enum { START_SIZE = 1, GROW_FACTOR = 2 }; /* {{{ php_bcompiler_init_globals */ static void php_bcompiler_init_globals(zend_bcompiler_globals *bcompiler_globals) { /*if (bcompiler_globals->dst == 0) { bcompiler_globals->dstsize = START_SIZE; bcompiler_globals->dst = (char*) malloc(bcompiler_globals->dstsize); } bcompiler_globals->dstpos = 0; */ bcompiler_globals->buffer = (char*) emalloc(START_SIZE); bcompiler_globals->stream = NULL; bcompiler_globals->callback = NULL; bcompiler_globals->callback_value = NULL; bcompiler_globals->callback_key = "NONE"; } /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(bcompiler) { // If you have INI entries, uncomment these lines ZEND_INIT_MODULE_GLOBALS(bcompiler, php_bcompiler_init_globals, NULL); //REGISTER_INI_ENTRIES(); return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(bcompiler) { // uncomment this line if you have INI entries //UNREGISTER_INI_ENTRIES(); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request start */ /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(bcompiler) { return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request end */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(bcompiler) { efree(BCOMPILERG(buffer)); return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(bcompiler) { php_info_print_table_start(); php_info_print_table_header(2, "bcompiler support", "enabled"); php_info_print_table_end(); /* Remove comments if you have entries in php.ini DISPLAY_INI_ENTRIES(); */ } /* }}} */ /* ---------------------------------------------------------------------------- * * MAJOR DEFINES * * * ---------------------------------------------------------------------------- */ /* These are flags that define start points in the decompile code.. */ #define BCOMPILER_CLASS_ENTRY 1 /* type: Fundamental operations */ /* ------------- STREAM BASED - eg. => php 4.3 -------------- */ #ifdef PHP_HAVE_STREAMS /* SERIALIZE_SCALAR: write a scalar value to dst */ #define SERIALIZE_SCALAR(x, type) { \ if (BCOMPILERG(stream) != NULL) { \ char _buf[255]; \ BCOMPILER_DEBUG((" scalar: %i\n",(type) x)); \ *(type*) _buf = x; \ php_stream_write((php_stream *) BCOMPILERG(stream) , _buf, (size_t) apclib_alignword_int(sizeof(type))); \ } \ } /* DESERIALIZE_SCALAR: read a scalar value from src */ #define DESERIALIZE_SCALAR(xp, type) { \ if (php_stream_eof(BCOMPILERG(stream))) { \ php_error(E_WARNING, "bcompiler: Read Past End of File"); \ return; \ } \ BCOMPILERG(buffer) = (char*) erealloc(BCOMPILERG(buffer), sizeof(type) + 1); \ php_stream_read((php_stream *) BCOMPILERG(stream) , BCOMPILERG(buffer) , (size_t) apclib_alignword_int(sizeof(type))); \ *(xp) = *((type*) BCOMPILERG(buffer)); \ BCOMPILER_DEBUG((" read : %i \n",(type) *(xp))); \ } /* STORE_BYTES: memcpy wrapper, writes to dst buffer */ #define STORE_BYTES(bytes, n) { \ if (BCOMPILERG(stream) != NULL) { \ BCOMPILER_DEBUG((" STORE: %s \n",bytes)); \ php_stream_write((php_stream *) BCOMPILERG(stream) , (char *)bytes, n); \ } \ } /* LOAD_BYTES: memcpy wrapper, reads from src buffer */ #define LOAD_BYTES(bytes, n) { \ if (php_stream_eof(BCOMPILERG(stream))) { \ php_error(E_WARNING, "bcompiler: Read Past End of File"); \ return; \ } \ BCOMPILERG(buffer) = (char*) erealloc(BCOMPILERG(buffer), n + 1); \ php_stream_read((php_stream *) BCOMPILERG(stream) , BCOMPILERG(buffer) , n); \ memcpy((char*)bytes, BCOMPILERG(buffer), n); \ BCOMPILER_DEBUG(("Got: %s\n",(char*)BCOMPILERG(buffer))); \ } #else /* ------------- NON STREAM BASED - eg. before php 4.3 -------------- */ /* SERIALIZE_SCALAR: write a scalar value to dst */ #define SERIALIZE_SCALAR(x, type) { \ if (BCOMPILERG(stream) != NULL) { \ char _buf[255]; \ BCOMPILER_DEBUG((" scalar: %i\n",(type) x)); \ *(type*) _buf = x; \ fwrite(_buf, 1, (size_t) apclib_alignword_int(sizeof(type)), (FILE*) BCOMPILERG(stream)); \ } \ } /* DESERIALIZE_SCALAR: read a scalar value from src */ #define DESERIALIZE_SCALAR(xp, type) { \ if (php_stream_eof(BCOMPILERG(stream))) { \ php_error(E_WARNING, "bcompiler: Read Past End of File"); \ return; \ } \ BCOMPILERG(buffer) = (char*) erealloc(BCOMPILERG(buffer), sizeof(type) + 1); \ fread(BCOMPILERG(buffer) , 1, (size_t) apclib_alignword_int(sizeof(type)), (FILE*) BCOMPILERG(stream)); \ *(xp) = *((type*) BCOMPILERG(buffer)); \ BCOMPILER_DEBUG((" read : %i \n",(type) *(xp))); \ } /* STORE_BYTES: memcpy wrapper, writes to dst buffer */ #define STORE_BYTES(bytes, n) { \ if (BCOMPILERG(stream) != NULL) { \ BCOMPILER_DEBUG((" STORE: %s \n",bytes)); \ fwrite((char *)bytes, 1, n, (FILE*) BCOMPILERG(stream)); \ } \ } /* LOAD_BYTES: memcpy wrapper, reads from src buffer */ #define LOAD_BYTES(bytes, n) { \ if (php_stream_eof(BCOMPILERG(stream))) { \ php_error(E_WARNING, "bcompiler: Read Past End of File"); \ return; \ } \ BCOMPILERG(buffer) = (char*) erealloc(BCOMPILERG(buffer), n + 1); \ fread(BCOMPILERG(buffer) ,1, n, (FILE*) BCOMPILERG(stream)); \ memcpy((char*)bytes, BCOMPILERG(buffer), n); \ BCOMPILER_DEBUG(("Got: %s\n",(char*)BCOMPILERG(buffer))); \ } #endif /* -------------------- Callbacks for bcompiler_parse() ------------------- */ #define CALLBACK_ADD_STRING(str,strlen) { \ if (BCOMPILERG(callback) != NULL) { \ add_assoc_stringl(BCOMPILERG(callback_value), BCOMPILERG(callback_key), str, strlen , 1); \ } \ } #define CALLBACK_ADD_KEY_STRING(key, str,strlen) { \ if (BCOMPILERG(callback) != NULL) { \ add_assoc_stringl(BCOMPILERG(callback_value), key, str, strlen , 1); \ } \ } #define CALLBACK_ADD_STRING_LONG(str,val) { \ char out[255]; \ int len; \ len = sprintf(out,str,val); \ if (BCOMPILERG(callback) != NULL) { \ add_assoc_stringl(BCOMPILERG(callback_value), BCOMPILERG(callback_key), out, len , 1); \ } \ } #define CALLBACK_ADD_LONG(key, val) { \ if (BCOMPILERG(callback) != NULL) { \ add_assoc_long(BCOMPILERG(callback_value), key, val); \ } \ } #define CALLBACK_ADD_SUB_LONG(kkey, val) { \ char out[255]; \ strcpy(out, BCOMPILERG(callback_key)); \ sprintf(out,"%s.%s",out, kkey); \ if (BCOMPILERG(callback) != NULL) { \ add_assoc_long(BCOMPILERG(callback_value), out, val); \ } \ } #define CALLBACK_ADD_SUB_DOUBLE(kkey, val) { \ char out[255]; \ strcpy(out, BCOMPILERG(callback_key)); \ sprintf(out,"%s.%s",out, kkey); \ if (BCOMPILERG(callback) != NULL) { \ add_assoc_double(BCOMPILERG(callback_value), out, val); \ } \ } #define CALLBACK_ADD_SUB_STRING(kkey, sval,slen) { \ char out[255]; \ strcpy(out, BCOMPILERG(callback_key)); \ sprintf(out,"%s.%s",out, kkey); \ if (BCOMPILERG(callback) != NULL) { \ add_assoc_stringl(BCOMPILERG(callback_value), out, sval ,slen , 1); \ } \ } #define CALLBACK_ADD_DOUBLE(key,val) { \ if (BCOMPILERG(callback) != NULL) { \ add_assoc_double(BCOMPILERG(callback_value), key, val); \ } \ } /* CALLBACK START (opcode) */ #define CALLBACK_START(code) { \ if (BCOMPILERG(callback) != NULL) { \ char *str; \ MAKE_STD_ZVAL(BCOMPILERG(callback_value)); \ array_init(BCOMPILERG(callback_value)); \ /*Optype - */ \ str = (char *) getOpcodeName(code ); \ add_assoc_long(BCOMPILERG(callback_value), "OPCODE", code); \ add_assoc_stringl(BCOMPILERG(callback_value), "OPCODE_STR", str, strlen(str) , 1); \ } \ } #define CALLBACK_END() { \ zval myretval; \ zval *sendval; \ if (BCOMPILERG(callback) != NULL) { \ sendval = BCOMPILERG(callback_value); \ zval_copy_ctor(sendval); \ if(!call_user_function( EG(function_table), NULL, BCOMPILERG(callback), &myretval, 1, &sendval TSRMLS_CC )) { \ zval_dtor(BCOMPILERG(callback_value)); \ } \ } \ } /* ---------------------------------------------------------------------------- * * function defs - putting this in .h doesnt work. * * * ---------------------------------------------------------------------------- */ /* {{{ proto boolean bcompile_write_class(stream out | filehandle, string class_name) Writes compiled data to stream*/ PHP_FUNCTION(bcompile_write_class) { char *class_name = NULL; int class_len; zend_class_entry *ce = NULL; zval *rsrc; void *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &rsrc, &class_name, &class_len) == FAILURE) { return; } #ifdef PHP_HAVE_STREAMS ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_stream()); #else ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_fopen()); #endif zend_str_tolower(class_name, class_len); zend_hash_find(EG(class_table), class_name, class_len+1, (void **)&ce); if (!ce) { RETURN_NULL(); } BCOMPILERG(stream) = stream; BCOMPILERG(callback) = NULL; SERIALIZE_SCALAR(BCOMPILER_CLASS_ENTRY, char) apc_serialize_zend_class_entry(ce TSRMLS_CC); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean bcompile_parse_class(callback, string class_name) Writes compiled data to stream*/ PHP_FUNCTION(bcompile_parse_class) { char *class_name = NULL; int class_len; zend_class_entry *ce = NULL; zval *rsrc; zval *callback = NULL; void *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zs", &callback, &class_name, &class_len) == FAILURE) { return; } zend_str_tolower(class_name, class_len); zend_hash_find(EG(class_table), class_name, class_len+1, (void **)&ce); if (!ce) { RETURN_NULL(); } BCOMPILERG(callback) = callback; BCOMPILERG(stream) = NULL; apc_serialize_zend_class_entry(ce TSRMLS_CC); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean bcompiler_write_header(stream out) Writes the start flag*/ PHP_FUNCTION(bcompile_write_header) { char *class_name = NULL; int class_len; zend_class_entry *ce = NULL; zval *rsrc; void *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &rsrc) == FAILURE) { return; } #ifdef PHP_HAVE_STREAMS ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_stream()); #else ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_fopen()); #endif BCOMPILERG(stream) = stream; apc_serialize_magic(TSRMLS_CC); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean bcompiler_write_end(stream out) Writes the end zero*/ PHP_FUNCTION(bcompile_write_footer) { char *class_name = NULL; int class_len; zend_class_entry *ce = NULL; zval *rsrc; void *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &rsrc) == FAILURE) { return; } #ifdef PHP_HAVE_STREAMS ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_stream()); #else ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_fopen()); #endif BCOMPILERG(stream) = stream; SERIALIZE_SCALAR(0, char); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean bcompile_class(stream out, int start_pos) Writes compiled data to stream*/ PHP_FUNCTION(bcompile_write_exe_footer) { char *class_name = NULL; int class_len; zend_class_entry *ce = NULL; zval *rsrc; int start; void *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &rsrc, &start) == FAILURE) { return; } #ifdef PHP_HAVE_STREAMS ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_stream()); #else ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_fopen()); #endif BCOMPILERG(stream) = stream; SERIALIZE_SCALAR(start, int); apc_serialize_magic(TSRMLS_CC); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean bcompile_read(stream in) Reads compiled data from stream*/ PHP_FUNCTION(bcompile_read) { char *class_name = NULL; int class_len =0; zval *rsrc; int test =0; char item; void *stream; zend_class_entry* zc; zend_class_entry *ce = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &rsrc) == FAILURE) { return; } #ifdef PHP_HAVE_STREAMS ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_stream()); #else ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_fopen()); #endif BCOMPILERG(stream) = stream; test = apc_deserialize_magic(TSRMLS_CC); if (test != 0) { php_error(E_WARNING, "Could not find Magic header in stream"); return; } BCOMPILER_DEBUG(("STARTING CLASS\n")); bcompiler_read( TSRMLS_CC); RETURN_TRUE; } /* {{{ proto boolean bcompile_load(bziped file) Reads compiled data bziped file*/ PHP_FUNCTION(bcompile_load) { void *stream = NULL; int test =0; zval *bzopen_mode; zval *rsrc; zval **args[2]; // used for call array zval *zbzopen; // zval for "bzopen" zval *zfilename; zval *zmode; /* recive args */ char *filename; int filename_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &filename,&filename_len) == FAILURE) { return; } MAKE_STD_ZVAL(zbzopen); #ifdef PHP_HAVE_STREAMS ZVAL_STRING(zbzopen, "bzopen", 1); #else ZVAL_STRING(zbzopen, "fopen", 1); #endif MAKE_STD_ZVAL(zfilename); ZVAL_STRING(zfilename, filename, 1); args[0] = &zfilename; MAKE_STD_ZVAL(zmode); ZVAL_STRING(zmode, "r", 1); args[1] = &zmode; call_user_function_ex(CG(function_table), NULL,zbzopen, &rsrc, 2, args, 0, NULL TSRMLS_CC ); #ifdef PHP_HAVE_STREAMS ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_stream()); #else ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_fopen()); #endif BCOMPILERG(stream) = stream; test = apc_deserialize_magic(TSRMLS_CC); if (test != 0) { php_error(E_WARNING, "Could not find Magic header in stream"); return; } bcompiler_read( TSRMLS_CC); #ifdef PHP_HAVE_STREAMS php_stream_close(stream); #else fclose((FILE *)stream); #endif RETURN_TRUE; } /* }}} */ /* {{{ proto boolean bcompile_load(bziped file) Reads compiled data bziped file*/ PHP_FUNCTION(bcompile_load_exe) { void *stream = NULL; int test =0; zval *bzopen_mode; zval *rsrc; zval *rsrc2; zval **args[2]; // used for call array zval *zbzopen; // zval for "bzopen" zval *zfopen; // zval for "bzopen" zval *zfilename; zval *zmode; /* recive args */ char *filename; int filename_len; long pos; //offset to use if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &filename,&filename_len) == FAILURE) { return; } MAKE_STD_ZVAL(zfopen); ZVAL_STRING(zfopen, "fopen", 1); MAKE_STD_ZVAL(zfilename); ZVAL_STRING(zfilename, filename, 1); args[0] = &zfilename; MAKE_STD_ZVAL(zmode); ZVAL_STRING(zmode, "r", 1); args[1] = &zmode; call_user_function_ex(CG(function_table), NULL, zfopen, &rsrc, 2, args, 0, NULL TSRMLS_CC ); #ifdef PHP_HAVE_STREAMS ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_stream()); #else ZEND_FETCH_RESOURCE(stream, void *, &rsrc, -1, "File-Handle", php_file_le_fopen()); #endif BCOMPILERG(stream) = stream; pos = (long) ((strlen(BCOMPILER_MAGIC_HEADER)+4) * -1); // +4 cause we need to read the string size BCOMPILER_DEBUG(("move to start: %d\n", pos)); #ifdef PHP_HAVE_STREAMS php_stream_seek(stream, pos , SEEK_END); #else fseek((FILE*)stream, pos, SEEK_END); #endif test = apc_deserialize_magic(TSRMLS_CC); if (test != 0) { php_error(E_WARNING, "Could not find Magic header in stream"); return; } /* now read the length */ pos = pos - 4; BCOMPILER_DEBUG(("move to start: %d\n", pos)); #ifdef PHP_HAVE_STREAMS php_stream_seek(stream, pos , SEEK_END); #else fseek((FILE*)stream, pos, SEEK_END); #endif DESERIALIZE_SCALAR(&pos, int); BCOMPILER_DEBUG(("move to start: %d\n", pos)); #ifdef PHP_HAVE_STREAMS php_stream_seek(stream, pos , SEEK_SET); #else fseek((FILE*)stream, pos, SEEK_SET); #endif MAKE_STD_ZVAL(zbzopen); #ifdef PHP_HAVE_STREAMS ZVAL_STRING(zbzopen, "bzopen", 1); #else ZVAL_STRING(zbzopen, "fopen", 1); #endif args[0] = &rsrc; MAKE_STD_ZVAL(zmode); ZVAL_STRING(zmode, "r", 1); args[1] = &zmode; call_user_function_ex(CG(function_table), NULL,zbzopen, &rsrc2, 2, args, 0, NULL TSRMLS_CC ); #ifdef PHP_HAVE_STREAMS ZEND_FETCH_RESOURCE(stream, void *, &rsrc2, -1, "File-Handle", php_file_le_stream()); #else ZEND_FETCH_RESOURCE(stream, void *, &rsrc2, -1, "File-Handle", php_file_le_fopen()); #endif BCOMPILERG(stream) = stream; test = apc_deserialize_magic(TSRMLS_CC); if (test != 0) { php_error(E_WARNING, "Could not find Magic header in stream"); return; } bcompiler_read( TSRMLS_CC); #ifdef PHP_HAVE_STREAMS php_stream_close(stream); #else fclose((FILE *)stream); #endif RETURN_TRUE; } /* }}} */ void bcompiler_read(TSRMLS_DC) { char item; zend_class_entry* zc; zend_class_entry *ce = NULL; DESERIALIZE_SCALAR(&item, char); while (item) { switch (item) { case BCOMPILER_CLASS_ENTRY: BCOMPILER_DEBUG(("STARTING CLASS\n")); apc_create_zend_class_entry(&zc TSRMLS_CC); /* is it in the class table already? */ zend_hash_find(EG(class_table), zc->name, zc->name_length+1, (void **)&ce); if (ce) { php_error(E_WARNING, "Could not redefine class %s", zc->name); efree(zc); } else { (*zc->refcount)++; BCOMPILER_DEBUG(("ADDING %s \n",zc->name)); zend_hash_add(EG(class_table), zc->name, zc->name_length+1, zc, sizeof(zend_class_entry), NULL); } } DESERIALIZE_SCALAR(&item, char); } } /* ---------------------------------------------------------------------------- * * from apc_lib.h -- GENERALLY STUFF that doesnt need GLOBALS! * * * ---------------------------------------------------------------------------- */ char* apclib_vstrdup(const char* s, apc_malloc_t ctor) { int n; char* t; if (s == NULL) { return NULL; } n = strlen(s) + 1; t = (char*) ctor(n); memcpy(t, s, n); return t; } void* apclib_vmemcpy(void* p, int n, apc_malloc_t ctor) { void* q; if (p == NULL) { return NULL; } q = ctor(n); memcpy(q, p, n); return q; } char* apclib_estrdup(const char* s) { int len; char* dup; if (s == NULL) { return NULL; } len = strlen(s); dup = (char*) malloc(len+1); if (dup == NULL) { apc_eprint("apclib_estrdup: malloc failed to allocate %u bytes:", len+1); } memcpy(dup, s, len); dup[len] = '\0'; return dup; } void* apclib_erealloc(void* p, size_t n) { p = realloc(p, n); if (p == NULL) { apc_eprint("apclib_erealloc: realloc failed to allocate %u bytes:", n); } return p; } /* type: string (null-terminated) */ void apclib_free_string(char **string) { if (*string == NULL) return; efree(*string); *string = NULL; } /* expandbuf: resize buffer to be at least minsize bytes in length */ static void apclib_expandbuf(char** bufptr, int* cursize, int minsize) { while (*cursize < minsize) { *cursize *= GROW_FACTOR; } *bufptr = (char*) realloc(*bufptr, *cursize); } int apclib_alignword_int(int x) { typedef union { void* p; int i; } word_t; return sizeof(word_t) * (1 + ((x-1)/sizeof(word_t))); } /* NO IDEA WHAT THIS STUFF IS ABOUT - probably needs sorting out... /* namearray_t is used to record deferred inheritance relationships */ typedef struct namearray_t namearray_t; struct namearray_t { char* strings; /* array of null-terminated names */ int length; /* logical size of strings */ int size; /* physical size of strings */ }; /* namearray_dtor: used to clean up deferred_inheritance table (see below) */ static void namearray_dtor(void* p) { namearray_t* na = (namearray_t*) p; if (na->strings != 0) { free(na->strings); } free(na); } /* ---------------------------------------------------------------------------- * * The name stuff is only really usefull for debugging.... * * * ---------------------------------------------------------------------------- */ static const char* opcodes[] = { "NOP", /* 0 */ "ADD", /* 1 */ "SUB", /* 2 */ "MUL", /* 3 */ "DIV", /* 4 */ "MOD", /* 5 */ "SL", /* 6 */ "SR", /* 7 */ "CONCAT", /* 8 */ "BW_OR", /* 9 */ "BW_AND", /* 10 */ "BW_XOR", /* 11 */ "BW_NOT", /* 12 */ "BOOL_NOT", /* 13 */ "BOOL_XOR", /* 14 */ "IS_IDENTICAL", /* 15 */ "IS_NOT_IDENTICAL", /* 16 */ "IS_EQUAL", /* 17 */ "IS_NOT_EQUAL", /* 18 */ "IS_SMALLER", /* 19 */ "IS_SMALLER_OR_EQUAL", /* 20 */ "CAST", /* 21 */ "QM_ASSIGN", /* 22 */ "ASSIGN_ADD", /* 23 */ "ASSIGN_SUB", /* 24 */ "ASSIGN_MUL", /* 25 */ "ASSIGN_DIV", /* 26 */ "ASSIGN_MOD", /* 27 */ "ASSIGN_SL", /* 28 */ "ASSIGN_SR", /* 29 */ "ASSIGN_CONCAT", /* 30 */ "ASSIGN_BW_OR", /* 31 */ "ASSIGN_BW_AND", /* 32 */ "ASSIGN_BW_XOR", /* 33 */ "PRE_INC", /* 34 */ "PRE_DEC", /* 35 */ "POST_INC", /* 36 */ "POST_DEC", /* 37 */ "ASSIGN", /* 38 */ "ASSIGN_REF", /* 39 */ "ECHO", /* 40 */ "PRINT", /* 41 */ "JMP", /* 42 */ "JMPZ", /* 43 */ "JMPNZ", /* 44 */ "JMPZNZ", /* 45 */ "JMPZ_EX", /* 46 */ "JMPNZ_EX", /* 47 */ "CASE", /* 48 */ "SWITCH_FREE", /* 49 */ "BRK", /* 50 */ "CONT", /* 51 */ "BOOL", /* 52 */ "INIT_STRING", /* 53 */ "ADD_CHAR", /* 54 */ "ADD_STRING", /* 55 */ "ADD_VAR", /* 56 */ "BEGIN_SILENCE", /* 57 */ "END_SILENCE", /* 58 */ "INIT_FCALL_BY_NAME", /* 59 */ "DO_FCALL", /* 60 */ "DO_FCALL_BY_NAME", /* 61 */ "RETURN", /* 62 */ "RECV", /* 63 */ "RECV_INIT", /* 64 */ "SEND_VAL", /* 65 */ "SEND_VAR", /* 66 */ "SEND_REF", /* 67 */ "NEW", /* 68 */ "JMP_NO_CTOR", /* 69 */ "FREE", /* 70 */ "INIT_ARRAY", /* 71 */ "ADD_ARRAY_ELEMENT", /* 72 */ "INCLUDE_OR_EVAL", /* 73 */ "UNSET_VAR", /* 74 */ "UNSET_DIM_OBJ", /* 75 */ "ISSET_ISEMPTY", /* 76 */ "FE_RESET", /* 77 */ "FE_FETCH", /* 78 */ "EXIT", /* 79 */ "FETCH_R", /* 80 */ "FETCH_DIM_R", /* 81 */ "FETCH_OBJ_R", /* 82 */ "FETCH_W", /* 83 */ "FETCH_DIM_W", /* 84 */ "FETCH_OBJ_W", /* 85 */ "FETCH_RW", /* 86 */ "FETCH_DIM_RW", /* 87 */ "FETCH_OBJ_RW", /* 88 */ "FETCH_IS", /* 89 */ "FETCH_DIM_IS", /* 90 */ "FETCH_OBJ_IS", /* 91 */ "FETCH_FUNC_ARG", /* 92 */ "FETCH_DIM_FUNC_ARG", /* 93 */ "FETCH_OBJ_FUNC_ARG", /* 94 */ "FETCH_UNSET", /* 95 */ "FETCH_DIM_UNSET", /* 96 */ "FETCH_OBJ_UNSET", /* 97 */ "FETCH_DIM_TMP_VAR", /* 98 */ "FETCH_CONSTANT", /* 99 */ "DECLARE_FUNCTION_OR_CLASS", /* 100 */ "EXT_STMT", /* 101 */ "EXT_FCALL_BEGIN", /* 102 */ "EXT_FCALL_END", /* 103 */ "EXT_NOP", /* 104 */ "TICKS", /* 105 */ "SEND_VAR_NO_REF", /* 106 */ "BEGIN_CLASS_DEF", /* 107 */ "BEGIN_HASH_DEF", /* 108 */ "OPCODE_ARRAY", /* 109 */ }; #define ZEND_BEGIN_HASH_DEF 108 #define ZEND_OPCODE_ARRAY 109 static const int NUM_OPCODES = sizeof(opcodes) / sizeof(opcodes[0]); const char* getOpcodeName(int op) { if (op < 0 || op >= NUM_OPCODES) { return "(unknown)"; } return opcodes[op]; } /* ---------------------------------------------------------------------------- * * STUFF THAT PROBALY NEEDS DELETING. * * * ---------------------------------------------------------------------------- */ /* inherit: recursively inherit methods from base to all the children * of parent, the children of parent's children, and so on */ /* static void apc_inherit(zend_class_entry* base, zend_class_entry* parent, TSRMLS_DC) { namearray_t* children; // classes derived directly from parent char* child_name; // name of the ith child of parent int i; return; // stuff in here is ignored at present.. // later - // children = apc_nametable_retrieve(deferred_inheritance, parent->name); if (!children) { return; // 'parent' has no children, nothing to do } // For each child of parent, resolve the inheritance from base // to the child. for (i = 0; i < children->length; i += strlen(child_name) + 1) { zend_class_entry* child; int result; child_name = children->strings + i; // look up the child class entry result = zend_hash_find(CG(class_table), child_name, strlen(child_name) + 1, (void**) &child); assert(result == SUCCESS); // FIXME: is this correct? // child inherits from base ZEND_DO_INHERITANCE(child, parent); // all children of child inherit from base apc_inherit(parent, child); } }*/ /* call_inherit */ static void apc_call_inherit(char *key, void *data TSRMLS_DC) { zend_class_entry *ce; if(zend_hash_find(CG(class_table), key, strlen(key) + 1, (void **) &ce) == SUCCESS) { apc_inherit(ce, ce); } } /* ---------------------------------------------------------------------------- * * START STUFF THAT NEEDS GLOBALS.... * * * ---------------------------------------------------------------------------- */ /* First step in deserialization. Sets the size/position of the * serialized buffer */ void apc_init_deserializer(char* input, int size TSRMLS_DC) { } /* apc_serialize_debug: prints information about the source and * destination serialization buffers */ void apc_serialize_debug(char * string TSRMLS_DC) { BCOMPILER_DEBUG(("%s\n", string)); //printf( "src=%p, srcpos=%d, srcsize=%d\n", BCOMPILERG(src), BCOMPILERG(srcpos), BCOMPILERG(srcsize)); //printf( "dst=%p, dstpos=%d, dstsize=%d\n", BCOMPILERG(dst), BCOMPILERG(dstpos), BCOMPILERG(dstsize)); } void apc_serialize_string(char* string TSRMLS_DC) { int len; /* by convention, mark null strings with a length of -1 */ if (string == NULL) { SERIALIZE_SCALAR(-1, int); return; } len = strlen(string); if (len <= 0) { SERIALIZE_SCALAR(-1, int); return; } BCOMPILER_DEBUG(("STRING: len, string : %s\n", string)); SERIALIZE_SCALAR(len, int); STORE_BYTES(string, len); } void apc_serialize_zstring(char* string, int len TSRMLS_DC) { /* by convention, mark null strings with a length of -1 */ if (len <= 0 || string == NULL) { SERIALIZE_SCALAR(-1, int); return; } // len = strlen(string); SERIALIZE_SCALAR(len, int); STORE_BYTES(string, len); } void apc_create_string(char** string TSRMLS_DC) { int len = 0; DESERIALIZE_SCALAR(&len, int); if (len <= 0) { /* by convention, empty marked strings (len is -1) are returned as an empty string */ *string = (char*) emalloc(1); (*string)[0] = '\0'; return; } *string = (char*) emalloc(len + 1); LOAD_BYTES(*string, len); (*string)[len] = '\0'; } void apc_serialize_arg_types(zend_uchar* arg_types TSRMLS_DC) { if (arg_types == NULL) { SERIALIZE_SCALAR(0, char); return; /* arg_types is null */ } SERIALIZE_SCALAR(1, char); SERIALIZE_SCALAR(arg_types[0], zend_uchar); STORE_BYTES(arg_types + 1, arg_types[0]*sizeof(zend_uchar)); } void apc_create_arg_types(zend_uchar** arg_types TSRMLS_DC) { char exists; zend_uchar count; DESERIALIZE_SCALAR(&exists, char); if (!exists) { *arg_types = NULL; return; /* arg_types is null */ } DESERIALIZE_SCALAR(&count, zend_uchar); *arg_types = emalloc(count + 1); (*arg_types)[0] = count; LOAD_BYTES((*arg_types) + 1, count*sizeof(zend_uchar)); } /* precompiler routines */ void apc_serialize_magic(TSRMLS_DC) { apc_serialize_string(BCOMPILER_MAGIC_HEADER TSRMLS_CC); } int apc_deserialize_magic(TSRMLS_DC) { char *tmp; int retval; apc_create_string(&tmp TSRMLS_CC); BCOMPILER_DEBUG(("got %s\n", tmp)); retval = strcmp(tmp,BCOMPILER_MAGIC_HEADER); apclib_free_string(&tmp); // MPB return retval; } /* type: zend_llist */ static void store_zend_llist_element(void* arg, void* data TSRMLS_DC) { int size = *((int*)arg); STORE_BYTES((char*)data, size); } void apc_serialize_zend_llist(zend_llist* list TSRMLS_DC) { char exists; exists = (list != NULL) ? 1 : 0; SERIALIZE_SCALAR(exists, char); // write twice to remove need for peeking. if (!exists) { return; } SERIALIZE_SCALAR(exists, char); SERIALIZE_SCALAR(list->size, size_t); SERIALIZE_SCALAR(list->dtor, void*); SERIALIZE_SCALAR(list->persistent, unsigned char); SERIALIZE_SCALAR(zend_llist_count(list), int); zend_llist_apply_with_argument(list, store_zend_llist_element, &list->size); } void apc_deserialize_zend_llist(zend_llist* list TSRMLS_DC) { char exists; size_t size; void (*dtor)(void*); unsigned char persistent; int count, i; char* data; DESERIALIZE_SCALAR(&exists, char); assert(exists != 0); /* read the list parameters */ DESERIALIZE_SCALAR(&size, size_t); DESERIALIZE_SCALAR(&dtor, void*); DESERIALIZE_SCALAR(&persistent, unsigned char); /* initialize the list */ zend_llist_init(list, size, dtor, persistent); /* insert the list elements */ DESERIALIZE_SCALAR(&count, int); data = (char*) malloc(list->size); for (i = 0; i < count; i++) { LOAD_BYTES(data, list->size); zend_llist_add_element(list, data); } free(data); } void apc_create_zend_llist(zend_llist** list TSRMLS_DC) { char exists; /* Sneak a look one byte ahead to see whether the list exists or not. * If it does, then exists is part of the structure, otherwise it was * a zero-value placeholder byte. */ /*PEEK_SCALAR(&exists, char); */ DESERIALIZE_SCALAR(&exists, char); if (exists) { *list = (zend_llist*) emalloc(sizeof(zend_llist)); apc_deserialize_zend_llist(*list TSRMLS_CC); } else { /* DESERIALIZE_SCALAR(&exists, char); */ *list = 0; } } /* type: HashTable */ /* type: HashTable */ void apc_serialize_hashtable(HashTable* ht, void* funcptr TSRMLS_DC) { char exists; /* for identifying null lists */ Bucket* p; void (*serialize_bucket)(void*); serialize_bucket = (void(*)(void*)) funcptr; exists = (ht != NULL) ? 1 : 0; SERIALIZE_SCALAR(exists, char); if (!exists) { return; } /* Serialize the hash meta-data. */ SERIALIZE_SCALAR(ht->nTableSize, uint); SERIALIZE_SCALAR(ht->pDestructor, void*); SERIALIZE_SCALAR(ht->nNumOfElements, uint); SERIALIZE_SCALAR(ht->persistent, int); /* Iterate through the buckets of the hash, serializing as we go. */ p = ht->pListHead; while(p != NULL) { SERIALIZE_SCALAR(p->h, ulong); SERIALIZE_SCALAR(p->nKeyLength,uint); CALLBACK_START(ZEND_BEGIN_HASH_DEF); CALLBACK_ADD_LONG("LINE", -1); BCOMPILERG(callback_key) = "HASH"; CALLBACK_ADD_STRING(p->arKey, p->nKeyLength); CALLBACK_END(); apc_serialize_zstring(p->arKey, p->nKeyLength TSRMLS_CC); serialize_bucket(p->pData); p = p->pListNext; } } void apc_deserialize_hashtable(HashTable* ht, void* funcptr, void* dptr, int datasize, char exists TSRMLS_DC) { uint nSize; dtor_func_t pDestructor; uint nNumOfElements; int persistent; int j; ulong h; uint nKeyLength; char* arKey; void* pData; int status; void (*deserialize_bucket)(void*); void (*free_bucket)(void*); BCOMPILER_DEBUG(("-----------------------------\nHASH TABLE:\n")); deserialize_bucket = (void(*)(void*)) funcptr; free_bucket = (void(*)(void*)) dptr; assert(exists != 0); DESERIALIZE_SCALAR(&nSize, uint); DESERIALIZE_SCALAR(&pDestructor, void*); DESERIALIZE_SCALAR(&nNumOfElements,uint); DESERIALIZE_SCALAR(&persistent, int); BCOMPILER_DEBUG(("-----------------------------\nBEGIN TABLE:\n")); /* Although the hash is already allocated (we're a deserialize, not a * create), we still need to initialize it. If this fails, something * very very bad happened. */ status = zend_hash_init(ht, nSize, NULL, pDestructor, persistent); assert(status != FAILURE); /* Luckily, the number of elements in a hash is part of its struct, so * we can just deserialize that many hashtable elements. */ for (j = 0; j < nNumOfElements; j++) { DESERIALIZE_SCALAR(&h, ulong); DESERIALIZE_SCALAR(&nKeyLength, uint); apc_create_string(&arKey TSRMLS_CC); deserialize_bucket(&pData); /* If nKeyLength is non-zero, this element is a hashed key/value * pair. Otherwise, it is an array element with a numeric index */ BCOMPILER_DEBUG(("-----------------------------\nFUNC %s\n",arKey)); if (nKeyLength != 0) { if(datasize == sizeof(void*)) { zend_hash_add_or_update(ht, arKey, nKeyLength, &pData, datasize, NULL, HASH_ADD); } else { zend_hash_add_or_update(ht, arKey, nKeyLength, pData, datasize, NULL, HASH_ADD); } } else { /* numeric index, not key string */ if(datasize == sizeof(void*)) { zend_hash_index_update(ht, h, &pData, datasize, NULL); } else { zend_hash_index_update(ht, h, pData, datasize, NULL); } } if (dptr != NULL) { free_bucket(&pData); } // else { // BCOMPILER_DEBUG((stderr, "Do not free: %s\n", arKey)); // } apclib_free_string(&arKey); // ADDED BY MPB } } void apc_create_hashtable(HashTable** ht, void* funcptr, void* dptr, int datasize TSRMLS_DC) { char exists; /* for identifying null hashtables */ /*PEEK_SCALAR(&exists, char); */ DESERIALIZE_SCALAR(&exists, char); if (exists==1) { *ht = (HashTable*) emalloc(sizeof(HashTable)); apc_deserialize_hashtable(*ht, funcptr, dptr, datasize,exists TSRMLS_CC); } else { /* DESERIALIZE_SCALAR(&exists, char); */ *ht = 0; } } /* type: zvalue_value */ void apc_serialize_zvalue_value(zvalue_value* zv, int type TSRMLS_DC) { /* A zvalue_value is a union, and as such we first need to * determine exactly what it's type is, then serialize the * appropriate structure. */ CALLBACK_ADD_SUB_LONG("u.constant.type",type); switch (type) { case IS_RESOURCE: case IS_BOOL: case IS_LONG: CALLBACK_ADD_SUB_LONG("u.constant.val",zv->lval); CALLBACK_ADD_LONG(BCOMPILERG(callback_key),zv->lval); SERIALIZE_SCALAR(zv->lval, long); break; case IS_DOUBLE: CALLBACK_ADD_SUB_DOUBLE("u.constant.val",zv->dval); CALLBACK_ADD_DOUBLE(BCOMPILERG(callback_key),zv->dval); SERIALIZE_SCALAR(zv->dval, double); break; case IS_NULL: /* null value, do nothing */ break; case IS_CONSTANT: case IS_STRING: case FLAG_IS_BC: CALLBACK_ADD_SUB_STRING("u.constant.val",zv->str.val, zv->str.len); CALLBACK_ADD_STRING(zv->str.val, zv->str.len); apc_serialize_zstring(zv->str.val, zv->str.len TSRMLS_CC); SERIALIZE_SCALAR(zv->str.len, int); break; case IS_ARRAY: CALLBACK_ADD_STRING("ARRAY?", 6); apc_serialize_hashtable(zv->ht, apc_serialize_zval_ptr TSRMLS_CC); break; case IS_CONSTANT_ARRAY: CALLBACK_ADD_STRING("CARRAY?", 7); apc_serialize_hashtable(zv->ht, apc_serialize_zval_ptr TSRMLS_CC); break; case IS_OBJECT: CALLBACK_ADD_STRING("OBJECT?", 7); apc_serialize_zend_class_entry(zv->obj.ce TSRMLS_CC); apc_serialize_hashtable(zv->obj.properties, apc_serialize_zval_ptr TSRMLS_CC); break; default: /* The above list enumerates all types. If we get here, * something very very bad has happened. */ assert(0); } } void apc_deserialize_zvalue_value(zvalue_value* zv, int type TSRMLS_DC) { /* We peeked ahead in the calling routine to deserialize the * type. Now we just deserialize. */ switch(type) { case IS_RESOURCE: case IS_BOOL: case IS_LONG: DESERIALIZE_SCALAR(&zv->lval, int); break; case IS_NULL: /* null value, do nothing */ break; case IS_DOUBLE: DESERIALIZE_SCALAR(&zv->dval, double); break; case IS_CONSTANT: case IS_STRING: case FLAG_IS_BC: apc_create_string(&zv->str.val TSRMLS_CC); DESERIALIZE_SCALAR(&zv->str.len, int); break; case IS_ARRAY: apc_create_hashtable(&zv->ht, apc_create_zval, NULL, sizeof(void*) TSRMLS_CC); break; case IS_CONSTANT_ARRAY: apc_create_hashtable(&zv->ht, apc_create_zval, NULL, sizeof(void*) TSRMLS_CC); break; case IS_OBJECT: apc_create_zend_class_entry(&zv->obj.ce TSRMLS_CC); apc_create_hashtable(&zv->obj.properties, apc_create_zval, NULL, sizeof(zval *) TSRMLS_CC); break; default: /* The above list enumerates all types. If we get here, * something very very bad has happened. */ assert(0); } } /* type: zval */ void apc_serialize_zval_ptr(zval** zv TSRMLS_DC) { apc_serialize_zval(*zv TSRMLS_CC); } void apc_serialize_zval(zval* zv TSRMLS_DC) { /* type is the switch for serializing zvalue_value */ SERIALIZE_SCALAR(zv->type, zend_uchar); apc_serialize_zvalue_value(&zv->value, zv->type TSRMLS_CC); SERIALIZE_SCALAR(zv->is_ref, zend_uchar); SERIALIZE_SCALAR(zv->refcount, zend_ushort); } void apc_deserialize_zval(zval* zv TSRMLS_DC) { /* type is the switch for deserializing zvalue_value */ DESERIALIZE_SCALAR(&zv->type, zend_uchar); apc_deserialize_zvalue_value(&zv->value, zv->type TSRMLS_CC); DESERIALIZE_SCALAR(&zv->is_ref, zend_uchar); DESERIALIZE_SCALAR(&zv->refcount, zend_ushort); } void apc_create_zval(zval** zv TSRMLS_DC) { *zv = (zval*) emalloc(sizeof(zval)); apc_deserialize_zval(*zv TSRMLS_CC); } void apc_free_zval(zval** zv TSRMLS_DC) { if (*zv != NULL) { switch((*zv)->type) { case IS_CONSTANT: case IS_STRING: case FLAG_IS_BC: apclib_free_string(&(*zv)->value.str.val); break; } efree(*zv); } *zv = NULL; } /* type: zend_function_entry */ void apc_serialize_zend_function_entry(zend_function_entry* zfe TSRMLS_DC) { apc_serialize_string(zfe->fname TSRMLS_CC); BCOMPILER_DEBUG(("serializing function %s\n",zfe->fname )); SERIALIZE_SCALAR(zfe->handler, void*); apc_serialize_arg_types(zfe->func_arg_types TSRMLS_CC); } void apc_deserialize_zend_function_entry(zend_function_entry* zfe TSRMLS_DC) { apc_create_string(&zfe->fname TSRMLS_CC); DESERIALIZE_SCALAR(&zfe->handler, void*); BCOMPILER_DEBUG(("deserializing function %s\n",zfe->handler)); apc_create_arg_types(&zfe->func_arg_types TSRMLS_CC); } /* type: zend_property_reference */ void apc_serialize_zend_property_reference(zend_property_reference* zpr TSRMLS_DC) { SERIALIZE_SCALAR(zpr->type, int); apc_serialize_zval(zpr->object TSRMLS_CC); apc_serialize_zend_llist(zpr->elements_list TSRMLS_CC); } void apc_deserialize_zend_property_reference(zend_property_reference* zpr TSRMLS_DC) { SERIALIZE_SCALAR(zpr->type, int); apc_deserialize_zval(zpr->object TSRMLS_CC); apc_create_zend_llist(&zpr->elements_list TSRMLS_CC); } /* type: zend_overloaded_element */ void apc_serialize_zend_overloaded_element(zend_overloaded_element* zoe TSRMLS_DC) { SERIALIZE_SCALAR(zoe->type, zend_uchar); apc_serialize_zval(&zoe->element TSRMLS_CC); } void apc_deserialize_zend_overloaded_element(zend_overloaded_element* zoe TSRMLS_DC) { DESERIALIZE_SCALAR(&zoe->type, zend_uchar); apc_deserialize_zval(&zoe->element TSRMLS_CC); } /* type: zend_class_entry */ void apc_serialize_zend_class_entry(zend_class_entry* zce TSRMLS_DC) { /* other than sending to a stream it also does a callback! The Array for a Class entry should look like: NOT::Type? - what is this used for? Name Parent NOT::refcount[0] ?? NOT::constants_updated ?? NOT::call,set etc: - would these point to a 'method?' !! ZEND_DECLARE_FUNCTION_OR_CLASS */ zval token; zval *keyword; zend_function_entry* zfe; int count, i, exists; /*apc_serialize_debug("starting adding class :" TSRMLS_CC); */ BCOMPILER_DEBUG(("adding type : %i\n",zce->type )); SERIALIZE_SCALAR(zce->type, char); apc_serialize_zstring(zce->name, zce->name_length TSRMLS_CC); SERIALIZE_SCALAR(zce->name_length, uint); /*apc_serialize_debug("done name" TSRMLS_CC); */ /* Serialize the name of this class's parent class (if it has one) * so that we can perform inheritance during deserialization (see * apc_deserialize_zend_class_entry). */ exists = (zce->parent != NULL) ? 1 : 0; SERIALIZE_SCALAR(exists, char); if (exists) { /*Parent*/ apc_serialize_zstring(zce->parent->name, zce->parent->name_length TSRMLS_CC); } CALLBACK_START(zce->type); BCOMPILERG(callback_key) = "CLASS"; CALLBACK_ADD_STRING(zce->name, zce->name_length); CALLBACK_END(); /* now callback to class/funct etc. */ /* apc_serialize_debug("done exists?" TSRMLS_CC); */ SERIALIZE_SCALAR(zce->refcount[0], int); SERIALIZE_SCALAR(zce->constants_updated, zend_bool); BCOMPILER_DEBUG(("-----------------------------\nFUNC TABLE:\n")); apc_serialize_hashtable(&zce->function_table, apc_serialize_zend_function TSRMLS_CC); BCOMPILER_DEBUG(("-----------------------------\nVARS:\n")); apc_serialize_hashtable(&zce->default_properties, apc_serialize_zval_ptr TSRMLS_CC); /* zend_class_entry.builtin_functions: this array appears to be * terminated by an element where zend_function_entry.fname is null * First we count the number of elements, then we serialize that count * and all the functions. */ BCOMPILER_DEBUG(("-----------------------------\nBUILTIN:\n")); count = 0; if (zce->builtin_functions) { for (zfe = zce->builtin_functions; zfe->fname != NULL; zfe++) { count++; } } SERIALIZE_SCALAR(count, int); for (i = 0; i < count; i++) { apc_serialize_zend_function_entry(&zce->builtin_functions[i] TSRMLS_CC); } /* apc_serialize_debug("tail stuff" TSRMLS_CC); */ SERIALIZE_SCALAR(zce->handle_function_call, void*); SERIALIZE_SCALAR(zce->handle_property_get, void*); SERIALIZE_SCALAR(zce->handle_property_set, void*); } void apc_deserialize_zend_class_entry(zend_class_entry* zce TSRMLS_DC) { int count, i, exists; DESERIALIZE_SCALAR(&zce->type, char); apc_create_string(&zce->name TSRMLS_CC); DESERIALIZE_SCALAR(&zce->name_length, uint); DESERIALIZE_SCALAR(&exists, char); if (exists) { // This class knows the name of its parent, most likely because // its parent is defined in the same source file. Therefore, we // can simply restore the parent link, and not worry about // manually inheriting methods from the parent (PHP will perform // the inheritance). char* parent_name; // name of parent class apc_create_string(&parent_name TSRMLS_CC); if ((zend_hash_find(CG(class_table), parent_name, strlen(parent_name) + 1, (void**) &zce->parent) == FAILURE)) { php_error(E_ERROR, "unable to inherit %s", parent_name); } } else { zce->parent = NULL; } /* refcount is a pointer to a single int. Don't ask me why, I // just work here. */ zce->refcount = (int*) emalloc(sizeof(int)); DESERIALIZE_SCALAR(zce->refcount, int); DESERIALIZE_SCALAR(&zce->constants_updated, zend_bool); BCOMPILER_DEBUG(("-----------------------------\nFUNC TABLE:\n")); DESERIALIZE_SCALAR(&exists, char); apc_deserialize_hashtable(&zce->function_table, apc_create_zend_function, apc_free_zend_function, sizeof(zend_function) ,exists TSRMLS_CC); BCOMPILER_DEBUG(("-----------------------------\nDEFAYLT PROPS:\n")); DESERIALIZE_SCALAR(&exists, char); apc_deserialize_hashtable(&zce->default_properties, apc_create_zval, NULL, sizeof(zval *), exists TSRMLS_CC); // see apc_serialize_zend_class_entry() for a description of the // zend_class_entry.builtin_functions member DESERIALIZE_SCALAR(&count, int); zce->builtin_functions = NULL; if (count > 0) { zce->builtin_functions = (zend_function_entry*) emalloc((count+1) * sizeof(zend_function_entry)); zce->builtin_functions[count].fname = NULL; for (i = 0; i < count; i++) { apc_deserialize_zend_function_entry(&zce->builtin_functions[i] TSRMLS_CC); } } DESERIALIZE_SCALAR(&zce->handle_function_call, void*); DESERIALIZE_SCALAR(&zce->handle_property_get, void*); DESERIALIZE_SCALAR(&zce->handle_property_set, void*); /* Resolve the inheritance relationships that have been delayed and * are waiting for this class to be created, i.e., every child of * this class that has already been compiled needs to be inherited * from this class. Call inherit() with this class as the base class * (first parameter) and as the current parent class (second parameter). * inherit will recursively resolve every inheritance relationships * in which this class is the base. */ /* apc_inherit(zce, zce TSRMLS_CC); */ /* code from zend_do_inheritance - ignores constructor inheritance currenlty? */ if (zce->parent) { zval *tmp; zend_function tmp_zend_function; zend_hash_merge(&zce->default_properties, &zce->parent->default_properties, (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); zend_hash_merge(&zce->function_table, &zce->parent->function_table, (void (*)(void *)) function_add_ref, &tmp_zend_function, sizeof(zend_function), 0); if (!zce->handle_property_get) zce->handle_property_get = zce->parent->handle_property_get; if (!zce->handle_property_set) zce->handle_property_set = zce->parent->handle_property_set; if (!zce->handle_function_call) zce->handle_function_call = zce->parent->handle_function_call; } } void apc_create_zend_class_entry(zend_class_entry** zce TSRMLS_DC) { *zce = (zend_class_entry*) emalloc(sizeof(zend_class_entry)); apc_deserialize_zend_class_entry(*zce TSRMLS_CC); } /* type: znode */ void apc_serialize_znode(znode* zn TSRMLS_DC) { SERIALIZE_SCALAR(zn->op_type, int); /* If the znode's op_type is IS_CONST, we know precisely what it is. * otherwise, it is too case-dependent (or inscrutable), so we do * a bitwise copy. */ CALLBACK_ADD_SUB_LONG("op_type" ,(long) zn->op_type); CALLBACK_ADD_SUB_LONG("u.fetch_type" ,(int) zn->u.fetch_type); CALLBACK_ADD_SUB_LONG("u.EA.type" ,(int) zn->u.EA.type); switch(zn->op_type) { case IS_CONST: if (&zn->u.fetch_type == ZEND_FETCH_GLOBAL) { CALLBACK_ADD_STRING("**GLOBAL",8); } apc_serialize_zval(&zn->u.constant TSRMLS_CC); break; case IS_VAR: CALLBACK_ADD_SUB_LONG("u.var" ,(long) zn->u.var); CALLBACK_ADD_STRING_LONG("VAR:%i",(long) zn->u.var); STORE_BYTES(&zn->u, sizeof(zn->u)); break; case IS_TMP_VAR: CALLBACK_ADD_SUB_LONG("u.var" ,(long) zn->u.var); CALLBACK_ADD_STRING_LONG("TMPVAR:%i",(long) zn->u.var); STORE_BYTES(&zn->u, sizeof(zn->u)); break; case IS_UNUSED: /* CALLBACK_ADD_STRING("**NOTUSED",9); */ CALLBACK_ADD_SUB_LONG("u.opline_num" ,(long) zn->u.opline_num); STORE_BYTES(&zn->u, sizeof(zn->u)); break; default: CALLBACK_ADD_STRING_LONG("**UNKNOWN",(long) sizeof(zn->u)); STORE_BYTES(&zn->u, sizeof(zn->u)); break; } } void apc_deserialize_znode(znode* zn TSRMLS_DC) { DESERIALIZE_SCALAR(&zn->op_type, int); /* If the znode's op_type is IS_CONST, we know precisely what it is. * otherwise, it is too case-dependent (or inscrutable), so we do * a bitwise copy. */ switch(zn->op_type) { case IS_CONST: apc_deserialize_zval(&zn->u.constant TSRMLS_CC); break; default: LOAD_BYTES(&zn->u, sizeof(zn->u)); break; } } /* type: zend_op */ void apc_serialize_zend_op(int id, zend_op* zo TSRMLS_DC) { /* apc_serialize_debug(getOpcodeName(zo->opcode)); */ //fprintf(stderr, "Outputting %s\n", getOpcodeName(zo->opcode)); CALLBACK_START(zo->opcode); SERIALIZE_SCALAR(zo->opcode, zend_uchar); BCOMPILERG(callback_key)="RESULT"; apc_serialize_znode(&zo->result TSRMLS_CC); BCOMPILERG(callback_key)="OP1"; apc_serialize_znode(&zo->op1 TSRMLS_CC); BCOMPILERG(callback_key)="OP2"; apc_serialize_znode(&zo->op2 TSRMLS_CC); SERIALIZE_SCALAR(zo->extended_value, ulong); if (zo->extended_value != 0) { CALLBACK_ADD_LONG("EXTENDED",(long) zo->extended_value); } CALLBACK_ADD_LONG("LINE",(long) id); /* add some useful info! */ switch (zo->opcode) { case ZEND_JMP: CALLBACK_ADD_LONG("JMP",zo->op1.u.opline_num); break; case ZEND_JMPZ: CALLBACK_ADD_LONG("JMP",zo->op2.u.opline_num); break; } CALLBACK_END(); SERIALIZE_SCALAR(zo->lineno, uint); } void apc_deserialize_zend_op(zend_op* zo TSRMLS_DC) { DESERIALIZE_SCALAR(&zo->opcode, zend_uchar); BCOMPILER_DEBUG(("Outputting %s\n", getOpcodeName(zo->opcode))); apc_deserialize_znode(&zo->result TSRMLS_CC); apc_deserialize_znode(&zo->op1 TSRMLS_CC); apc_deserialize_znode(&zo->op2 TSRMLS_CC); DESERIALIZE_SCALAR(&zo->extended_value, ulong); DESERIALIZE_SCALAR(&zo->lineno, uint); } /* type: zend_op_array */ void apc_serialize_zend_op_array(zend_op_array* zoa TSRMLS_DC) { char exists; int i; CALLBACK_START(ZEND_OPCODE_ARRAY); CALLBACK_ADD_LONG("TYPE",(long) zoa->type); CALLBACK_ADD_LONG("LINE",-1); CALLBACK_ADD_LONG("return_reference",zoa->return_reference); CALLBACK_ADD_KEY_STRING("FUNCTION_NAME",zoa->function_name, strlen(zoa->function_name)); SERIALIZE_SCALAR(zoa->type, zend_uchar); apc_serialize_arg_types(zoa->arg_types TSRMLS_CC); apc_serialize_string(zoa->function_name TSRMLS_CC); SERIALIZE_SCALAR(zoa->refcount[0], zend_uint); SERIALIZE_SCALAR(zoa->last, zend_uint); SERIALIZE_SCALAR(zoa->size, zend_uint); /* If a file 'A' is included twice in a single request, the following * situation can occur: A is deserialized and its functions added to * the global function table. On its next call, A is expired (either * forcibly removed or removed due to an expired ttl). Now when A is * compiled, its functions can't be added to the global function_table * (they are already present) so they are serialized as an opcode * ZEND_DECLARE_FUNCTION_OR_CLASS. This means that the functions will * be declared at execution time. Since they are present in the global * function_table, they will will also be serialized. This will cause * a fatal 'failed to redclare....' error. We avoid this by simulating * the action of the parser and changing all * ZEND_DECLARE_FUNCTION_OR_CLASS opcodes to ZEND_NOPs. */ CALLBACK_ADD_LONG("T",(long) zoa->T); CALLBACK_ADD_LONG("USES_GLOBALS",(long) zoa->uses_globals); CALLBACK_END(); for (i = 0; i < zoa->last; i++) { apc_serialize_zend_op(i, &zoa->opcodes[i] TSRMLS_CC); } SERIALIZE_SCALAR(zoa->T, zend_uint); SERIALIZE_SCALAR(zoa->last_brk_cont, zend_uint); SERIALIZE_SCALAR(zoa->current_brk_cont, zend_uint); SERIALIZE_SCALAR(zoa->uses_globals, zend_bool); exists = (zoa->brk_cont_array != NULL) ? 1 : 0; SERIALIZE_SCALAR(exists, char); if (exists) { STORE_BYTES(zoa->brk_cont_array, zoa->last_brk_cont * sizeof(zend_brk_cont_element)); } apc_serialize_hashtable(zoa->static_variables, apc_serialize_zval_ptr TSRMLS_CC); #ifdef APC_MUST_DEFINE_START_OP /* Introduced in php-4.0.7 */ assert(zoa->start_op == NULL); #endif SERIALIZE_SCALAR(zoa->return_reference, zend_bool); SERIALIZE_SCALAR(zoa->done_pass_two, zend_bool); apc_serialize_string(zoa->filename TSRMLS_CC); CALLBACK_START(ZEND_OPCODE_ARRAY); CALLBACK_ADD_LONG("ISEND",1); CALLBACK_ADD_LONG("LINE",-1); CALLBACK_END(); /* zend_op_array.reserved is not used */ } void apc_deserialize_zend_op_array(zend_op_array* zoa, int master TSRMLS_DC) { char *fname; char exists; int i; DESERIALIZE_SCALAR(&zoa->type, zend_uchar); apc_create_arg_types(&zoa->arg_types TSRMLS_CC); apc_create_string(&zoa->function_name TSRMLS_CC); zoa->refcount = (int*) emalloc(sizeof(zend_uint)); DESERIALIZE_SCALAR(zoa->refcount, zend_uint); DESERIALIZE_SCALAR(&zoa->last, zend_uint); DESERIALIZE_SCALAR(&zoa->size, zend_uint); zoa->opcodes = NULL; if (zoa->last > 0) { zoa->opcodes = (zend_op*) emalloc(zoa->last * sizeof(zend_op)); for (i = 0; i < zoa->last; i++) { apc_deserialize_zend_op(&zoa->opcodes[i] TSRMLS_CC); if(zoa->opcodes[i].opcode == ZEND_DECLARE_FUNCTION_OR_CLASS) { HashTable* table; char* op2str; /* op2str and op2len are for convenience */ int op2len; exists = 1; op2str = zoa->opcodes[i].op2.u.constant.value.str.val; op2len = zoa->opcodes[i].op2.u.constant.value.str.len; switch(zoa->opcodes[i].extended_value) { /* a run-time function declaration */ case ZEND_DECLARE_FUNCTION: { zend_function* function; table = CG(function_table); if (zend_hash_find(table, op2str, op2len + 1, (void**) &function) == SUCCESS) { zval_dtor(&zoa->opcodes[i].op1.u.constant); zval_dtor(&zoa->opcodes[i].op2.u.constant); zoa->opcodes[i].opcode = ZEND_NOP; memset(&zoa->opcodes[i].op1, 0, sizeof(znode)); memset(&zoa->opcodes[i].op2, 0, sizeof(znode)); zoa->opcodes[i].op1.op_type = IS_UNUSED; zoa->opcodes[i].op2.op_type = IS_UNUSED; } } break; /* a run-time class declaration */ case ZEND_DECLARE_CLASS: { zend_class_entry *ce; table = CG(class_table); if (zend_hash_find(table, op2str, op2len + 1, (void**) &ce) == SUCCESS) { zval_dtor(&zoa->opcodes[i].op1.u.constant); zval_dtor(&zoa->opcodes[i].op2.u.constant); zoa->opcodes[i].opcode = ZEND_NOP; memset(&zoa->opcodes[i].op1, 0, sizeof(znode)); memset(&zoa->opcodes[i].op2, 0, sizeof(znode)); zoa->opcodes[i].op1.op_type = IS_UNUSED; zoa->opcodes[i].op2.op_type = IS_UNUSED; } } break; /* a run-time derived class declaration */ case ZEND_DECLARE_INHERITED_CLASS: { zend_class_entry *ce; char* class_name; char* parent_name; int class_name_length; namearray_t* children; int minSize; table = CG(class_table); /* op2str is a class name of the form "base:derived", * where derived is the class being declared and base * is its parent in the class hierarchy. Extract the * two names into parent_name and class_name. */ parent_name = apclib_estrdup(op2str); if ((class_name = strchr(parent_name, ':')) == 0) { zend_error(E_CORE_ERROR,"Invalid runtime class entry"); } *class_name++ = '\0'; /* advance past ':' */ if (zend_hash_find(table, class_name, strlen(class_name)+1, (void**) &ce) == SUCCESS) { zval_dtor(&zoa->opcodes[i].op1.u.constant); zval_dtor(&zoa->opcodes[i].op2.u.constant); zoa->opcodes[i].opcode = ZEND_NOP; memset(&zoa->opcodes[i].op1, 0, sizeof(znode)); memset(&zoa->opcodes[i].op2, 0, sizeof(znode)); zoa->opcodes[i].op1.op_type = IS_UNUSED; zoa->opcodes[i].op2.op_type = IS_UNUSED; } /* The parent class hasn't been compiled yet, most likely * because it is defined in an included file. We must defer * this inheritance until the parent class is created. Add * a tuple for this class and its parent to the deferred * inheritance table */ class_name_length = strlen(class_name); //children = apc_nametable_retrieve(deferred_inheritance, // parent_name TSRMLS_CC); if (children == 0) { /* Create and initialize a new namearray_t for this * class's parent and insert into the deferred * inheritance table. */ children = (namearray_t*) malloc(sizeof(namearray_t)); children->length = 0; children->size = class_name_length + 1; children->strings = (char*) malloc(children->size); //apc_nametable_insert(deferred_inheritance, // parent_name, children TSRMLS_CC); } /* a deferred class can't be a top-level parent */ //apc_nametable_insert(non_inheritors, class_name, NULL TSRMLS_CC); minSize = children->length + class_name_length + 1; if (minSize > children->size) { /* The strings array (children->strings) is not big * enough to store this class name. Expand the array * using an exponential resize. */ while (minSize > children->size) { children->size *= 2; } children->strings = apclib_erealloc(children->strings, children->size); } memcpy(children->strings + children->length, class_name, class_name_length + 1); children->length += class_name_length + 1; } break; default: break; } } } } DESERIALIZE_SCALAR(&zoa->T, zend_uint); DESERIALIZE_SCALAR(&zoa->last_brk_cont, zend_uint); DESERIALIZE_SCALAR(&zoa->current_brk_cont, zend_uint); DESERIALIZE_SCALAR(&zoa->uses_globals, zend_bool); DESERIALIZE_SCALAR(&exists, char); zoa->brk_cont_array = NULL; if (exists) { zoa->brk_cont_array = (zend_brk_cont_element*) emalloc(zoa->last_brk_cont * sizeof(zend_brk_cont_element)); LOAD_BYTES(zoa->brk_cont_array, zoa->last_brk_cont * sizeof(zend_brk_cont_element)); } apc_create_hashtable(&zoa->static_variables, apc_create_zval, NULL, sizeof(zval *) TSRMLS_CC); #ifdef APC_MUST_DEFINE_START_OP /* Introduced in php 4.0.7 */ zoa->start_op = NULL; #endif DESERIALIZE_SCALAR(&zoa->return_reference, zend_bool); DESERIALIZE_SCALAR(&zoa->done_pass_two, zend_bool); apc_create_string(&fname TSRMLS_CC); zoa->filename = zend_set_compiled_filename(fname); apclib_free_string(&fname); if(master) { // apc_nametable_difference(parental_inheritors, non_inheritors TSRMLS_CC); // apc_nametable_apply(parental_inheritors, call_inherit TSRMLS_CC); } } void apc_create_zend_op_array(zend_op_array** zoa TSRMLS_DC) { *zoa = (zend_op_array*) emalloc(sizeof(zend_op_array)); apc_deserialize_zend_op_array(*zoa, 0 TSRMLS_CC); } /* type: zend_internal_function */ void apc_serialize_zend_internal_function(zend_internal_function* zif TSRMLS_DC) { SERIALIZE_SCALAR(zif->type, zend_uchar); apc_serialize_arg_types(zif->arg_types TSRMLS_CC); apc_serialize_string(zif->function_name TSRMLS_CC); SERIALIZE_SCALAR(zif->handler, void*); } void apc_deserialize_zend_internal_function(zend_internal_function* zif TSRMLS_DC) { DESERIALIZE_SCALAR(&zif->type, zend_uchar); apc_create_arg_types(&zif->arg_types TSRMLS_CC); apc_create_string(&zif->function_name TSRMLS_CC); DESERIALIZE_SCALAR(&zif->handler, void*); } /* type: zend_overloaded_function */ void apc_serialize_zend_overloaded_function(zend_overloaded_function* zof TSRMLS_DC) { SERIALIZE_SCALAR(zof->type, zend_uchar); apc_serialize_arg_types(zof->arg_types TSRMLS_CC); apc_serialize_string(zof->function_name TSRMLS_CC); SERIALIZE_SCALAR(zof->var, zend_uint); } void apc_deserialize_zend_overloaded_function(zend_overloaded_function* zof TSRMLS_DC) { DESERIALIZE_SCALAR(&zof->type, zend_uchar); apc_create_arg_types(&zof->arg_types TSRMLS_CC); apc_create_string(&zof->function_name TSRMLS_CC); DESERIALIZE_SCALAR(&zof->var, zend_uint); } /* type: zend_function */ void apc_serialize_zend_function(zend_function* zf TSRMLS_DC) { /* zend_function come in 4 different types with different internal * structs. */ zval retval; SERIALIZE_SCALAR(zf->type, zend_uchar); switch(zf->type) { case ZEND_INTERNAL_FUNCTION: apc_serialize_zend_internal_function(&zf->internal_function TSRMLS_CC); break; case ZEND_OVERLOADED_FUNCTION: apc_serialize_zend_overloaded_function(&zf->overloaded_function TSRMLS_CC); break; case ZEND_USER_FUNCTION: case ZEND_EVAL_CODE: apc_serialize_zend_op_array(&zf->op_array TSRMLS_CC); break; default: /* the above are all valid zend_function types. If we hit this * case something has gone very very wrong. */ assert(0); } } void apc_deserialize_zend_function(zend_function* zf TSRMLS_DC) { /* PEEK_SCALAR(&zf->type, zend_uchar); */ DESERIALIZE_SCALAR(&zf->type, zend_uchar); switch(zf->type) { case ZEND_INTERNAL_FUNCTION: apc_deserialize_zend_internal_function(&zf->internal_function TSRMLS_CC); break; case ZEND_OVERLOADED_FUNCTION: apc_deserialize_zend_overloaded_function(&zf->overloaded_function TSRMLS_CC); break; case ZEND_USER_FUNCTION: case ZEND_EVAL_CODE: apc_deserialize_zend_op_array(&zf->op_array, 0 TSRMLS_CC); break; default: /* the above are all valid zend_function types. If we hit this * case something has gone very very wrong. */ assert(0); } } void apc_create_zend_function(zend_function** zf TSRMLS_DC) { *zf = (zend_function*) emalloc(sizeof(zend_function)); apc_deserialize_zend_function(*zf TSRMLS_CC); } void apc_free_zend_function(zend_function** zf TSRMLS_DC) { if (*zf != NULL) efree(*zf); *zf = NULL; } /* The logic for serialize_class_table and deserialize_class_table * mirror that of the corresponding function_table functions (see * above), with classes in place of functions. */ static int store_class_table(void *element, int num_args, va_list args, zend_hash_key *hash_key TSRMLS_DC) { zend_class_entry* zc; zc = (zend_class_entry*) element; /* do not serialize internal classes */ if (zc->type == ZEND_INTERNAL_CLASS) { return 0; } /* serialize differences */ SERIALIZE_SCALAR(1, char); apc_serialize_zend_class_entry(zc TSRMLS_CC); if(zc->parent != NULL) { //apc_nametable_insert(priv, zc->name, 0); } return 0; } static int store_class_table_ex(void *element, int num_args, va_list args, zend_hash_key *hash_key TSRMLS_DC) { zend_class_entry* zc; zc = (zend_class_entry*) element; /* do not serialize internal classes */ if (zc->type == ZEND_INTERNAL_CLASS) { return 0; } /* serialize differences */ SERIALIZE_SCALAR(1, char); // apc_serialize_zstring(hash_key->arKey, hash_key->nKeyLength); apc_serialize_zend_class_entry(zc TSRMLS_CC); // Think about tracking same-file inheritance return 0; } void apc_serialize_zend_class_table(HashTable* gct TSRMLS_DC) { zend_hash_apply_with_arguments(gct, store_class_table, 0, NULL); SERIALIZE_SCALAR(0, char); } int apc_deserialize_zend_class_table(HashTable* gct TSRMLS_DC) { char exists; int i; zend_class_entry* zc; i = 0; DESERIALIZE_SCALAR(&exists, char); while (exists) { apc_create_zend_class_entry(&zc TSRMLS_CC); if (zend_hash_add(gct, zc->name, zc->name_length + 1, zc, sizeof(zend_class_entry), NULL) == FAILURE) { /* This can validly happen. */ } /* We may only want to do this insert if zc->parent is NULL */ //apc_nametable_insert(parental_inheritors, zc->name, NULL); //apc_nametable_insert(acc, zc->name, 0); //apc_nametable_insert(priv, zc->name, 0); DESERIALIZE_SCALAR(&exists, char); // apc_free_zend_class_entry if (zc != NULL) efree(zc); // ADDED BY MPB i++; } return i; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ Index: pear/PECL/bcompiler/bcompiler.dsp +++ pear/PECL/bcompiler/bcompiler.dsp # Microsoft Developer Studio Project File - Name="bcompiler" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 CFG=bcompiler - Win32 Debug_TS !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "bcompiler.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "bcompiler.mak" CFG="bcompiler - Win32 Debug_TS" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "bcompiler - Win32 Release_TS" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE "bcompiler - Win32 Debug_TS" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe MTL=midl.exe RSC=rc.exe !IF "$(CFG)" == "bcompiler - Win32 Release_TS" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release_TS" # PROP BASE Intermediate_Dir "Release_TS" # PROP BASE Ignore_Export_Lib 0 # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "Release_TS" # PROP Intermediate_Dir "Release_TS" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "TOKENIZER_EXPORTS" /YX /FD /c # ADD CPP /nologo /MD /W3 /GX /O2 /I "..\.." /I "..\..\main" /I "..\..\Zend" /I "..\..\TSRM" /D ZEND_DEBUG=0 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "PHP_EXPORTS" /D "COMPILE_DL_TOKENIZER" /D ZTS=1 /D "ZEND_WIN32" /D "PHP_WIN32" /D HAVE_TOKENIZER=1 /YX /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x407 /d "NDEBUG" # ADD RSC /l 0x407 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 # ADD LINK32 php4ts.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /out:"..\..\Release_TS/php_bcompiler.dll" /libpath:"..\..\Release_TS" /libpath:"..\..\Release_TS_Inline" !ELSEIF "$(CFG)" == "bcompiler - Win32 Debug_TS" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug_TS" # PROP BASE Intermediate_Dir "Debug_TS" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "Debug_TS" # PROP Intermediate_Dir "Debug_TS" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "TOKENIZER_EXPORTS" /YX /FD /GZ /c # ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\.." /I "..\..\main" /I "..\..\Zend" /I "..\..\TSRM" /D ZEND_DEBUG=1 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "PHP_EXPORTS" /D "COMPILE_DL_TOKENIZER" /D ZTS=1 /D "ZEND_WIN32" /D "PHP_WIN32" /D HAVE_TOKENIZER=1 /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x407 /d "_DEBUG" # ADD RSC /l 0x407 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept # ADD LINK32 php4ts_debug.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /out:"..\..\Debug_TS/php_bcompiler.dll" /pdbtype:sept /libpath:"..\..\Debug_TS" !ENDIF # Begin Target # Name "bcompiler - Win32 Release_TS" # Name "bcompiler - Win32 Debug_TS" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE=.\bcompiler.c # End Source File # End Group # Begin Group "Header Files" # PROP Default_Filter "h;hpp;hxx;hm;inl" # Begin Source File SOURCE=.\php_bcompiler.h # End Source File # End Group # End Target # End Project Index: pear/PECL/bcompiler/bcompiler.xml +++ pear/PECL/bcompiler/bcompiler.xml <?xml version="1.0" encoding="iso-8859-1"?> <!-- $Revision: 1.1 $ --> <reference id="pecl.bcompiler"> <title>bcompiler</title> <titleabbrev>bcompiler</titleabbrev> <partintro> &warn.experimental; <sect1 id="pecl.bcompiler.partintro"> <title>Introduction</title> <sect2 id="pecl.bcompiler.intro"> <title>About bcompiler</title> <para> Bcompiler was written for two reasons: <simplelist> <member>To encode some classes in a proprietary php application</member> <member>To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe.</member> <member>To do the feasiblity study for a PHP to C convertor</member> </simplelist> The first of these goals is achieved using the bcompiler_write_header, bcompiler_write_class, bcompiler_write_footer, bcompiler_read, and bcompiler_load functions. The bytecode files can be written as either uncompressed or plain. The bcompiler_load reads a bzip compressed bytecode file, which tends to be 1/3 of the size of the original file. </para> To create EXE type files, bcompiler has to be used with a modified sapi file or a version of php which has been compiled as a shared library. In this scenario, bcompiler reads the compressed bytecode from the end of the exe file. <para> </para> bcompiler is unlikely to improve performance very much, as it only bypasses the compiler stage of the php running process and replaces it with the import process in bcompiler. It also does not do any bytecode optimization, this could be added in the future... <para> </para> in terms of code protection, it is safe to say that it would be impossible to recreate the exact source code that it was built from, and without the accompanying source code comments. It would effectively be useless to use the bcompiler bytecodes to recreate and modify a class. However it is possible to retreive data from a bcompiled bytecode file - so dont put your private passwords or anything in it.. <para> </sect2> <sect2 id="pecl.bcompiler.install"> <title>Installation</title> <para> short installation note: <itemizedlist> <listitem><simpara>You need at least PHP 4.3.</simpara></listitem> <listitem> <simpara> untar the bcompiler.tgz archive into php4/ext (Get it directly from PEAR <ulink url="http://pear.php.net/get/bcompiler">http://pear.php.net/get/bcompiler</ulink>) </simpara> </listitem> <listitem> <simpara> If the new directory is now called something like bcompiler-0.x, then you should rename it to bcompiler (except you only want to build it as self-contained php-module) </simpara> </listitem> <listitem><simpara>run phpize in ext/bcompiler</simpara></listitem> <listitem><simpara>run ./buildconf in php4</simpara></listitem> <listitem> <simpara> run configure with --with-bcompiler (and your other options) </simpara> </listitem> <listitem><simpara>make; make install</simpara></listitem> <listitem><simpara>that's it.</simpara></listitem> </itemizedlist> </para> </sect2> <sect2 id="pecl.bcompiler.contact"> <title>Contact Information</title> <para> ...... </para> <para> If you have comments, bugfixes, enhancements or want to help developping this beast, you can drop me a mail at <ulink url="mailto:alan_k@php.net">alan_k@php.net</ulink>. Any help is very welcome. </para> </sect2> </sect1> </partintro> <!-- header --> <refentry id="pecl.bcompiler.bcompile-write-header"> <refnamediv> <refname>bcompile_write_header</refname> <refpurpose>Writes the bcompiler header</refpurpose> </refnamediv> <refsect1> <title>Description</title> <funcsynopsis> <funcprototype> <funcdef><function>bcompile_write_header</function></funcdef> <paramdef>resource <parameter>filehandle</parameter></paramdef> </funcprototype> </funcsynopsis> &warn.experimental.func; <para> Writes the header part of a bcompiler file. </para> <example> <title><function>bcompile_write_header</function> example</title> <programlisting role="php"> <![CDATA[ <?php $fh = fopen("/tmp/example","w"); bcompile_write_header($fh); bcompile_write_class($fh,"DB"); bcompile_write_footer($fh); fclose($fh); ?> ]]> </programlisting> </example> <para> See also: <function>bcompile_write_class</function>, <function>bcompile_write_footer</function>. </para> </refsect1> </refentry> <!-- footer --> <refentry id="pecl.bcompiler.bcompile-write-footer"> <refnamediv> <refname>bcompile_write_footer</refname> <refpurpose>Writes the a single character \x00 to indicate End of compiled data</refpurpose> </refnamediv> <refsect1> <title>Description</title> <funcsynopsis> <funcprototype> <funcdef><function>bcompile_write_footer</function></funcdef> <paramdef>resource <parameter>filehandle</parameter></paramdef> </funcprototype> </funcsynopsis> &warn.experimental.func; <para> Writes the a single character \x00 to indicate End of compiled data </para> <example> <title><function>bcompile_write_footer</function> example</title> <programlisting role="php"> <![CDATA[ <?php $fh = fopen("/tmp/example","w"); bcompile_write_header($fh); bcompile_write_class($fh,"DB"); bcompile_write_class($fh,"DB_common"); bcompile_write_footer($fh); fclose($fh); ?> ]]> </programlisting> </example> <para> See also: <function>bcompile_write_header</function>, <function>bcompile_write_header</function>. </para> </refsect1> </refentry> <!-- footer --> <refentry id="pecl.bcompiler.bcompile-write-exe-footer"> <refnamediv> <refname>bcompile_write_exe_footer</refname> <refpurpose>Writes the the start pos, and sig to the end of a exe type file</refpurpose> </refnamediv> <refsect1> <title>Description</title> <funcsynopsis> <funcprototype> <funcdef><function>bcompile_write_exe_footer</function></funcdef> <paramdef>resource <parameter>filehandle</parameter></paramdef> <paramdef>int <parameter>startpos</parameter></paramdef> </funcprototype> </funcsynopsis> &warn.experimental.func; <para> An EXE (or self exectutable) file consists of 3 parts, </para> <para> <simplelist> <member>The Exectutable code (eg. a compiled C program that can initiate call the php bcompiler)</member> <member>The Bzip encoded Bytecodes</member> <member>The bcompiler exe footer</member> </simplelist> The startpos is the position of in the file at which the Bzip encoded bytecodes start, and can be obtained using ftell($fh), </para> <example> <title><function>bcompile_write_footer</function> example</title> <programlisting role="php"> <![CDATA[ <?php $fh = fopen("/tmp/example.exe","w"); $size = filesize("/tmp/base.exe"); $fr = fopen("/tmp/base.exe","r"); fwrite($fh,fread($fr,$size),$size); $startpos = ftell($fh); /* write bytecodes compressed */ $fz = bzopen($fh,"w"); bcompile_write_header($fz); bcompile_write_class($fz,"DB"); bcompile_write_class($fz,"DB_common"); bcompile_write_footer($fz); /* write footer exe uncompressed */ bcompiler_write_exe_footer($fh,$startpos); fclose($fh); ?> ]]> </programlisting> </example> <para> See also:<function>bcompile_write_header</function> <function>bcompile_write_class</function>, <function>bcompile_write_footer</function>. </para> </refsect1> </refentry> <!-- read --> <refentry id="pecl.bcompiler.bcompile-read"> <refnamediv> <refname>bcompile_read</refname> <refpurpose>reads and creates classes from a filehandle</refpurpose> </refnamediv> <refsect1> <title>Description</title> <funcsynopsis> <funcprototype> <funcdef><function>bcompile_read</function></funcdef> <paramdef>resource <parameter>filehandle</parameter></paramdef> </funcprototype> </funcsynopsis> &warn.experimental.func; <para> Reads data from a open file handle and creates classes from the bytecodes </para> <example> <title><function>bcompile_read</function> example</title> <programlisting role="php"> <![CDATA[ <?php $fh = fopen("/tmp/example","r"); bcompile_read($fh); fclose($fh); print_r(get_defined_classes()); ?> ]]> </programlisting> </example> </refsect1> </refentry> <!-- load --> <refentry id="pecl.bcompiler.bcompile-load"> <refnamediv> <refname>bcompile_load</refname> <refpurpose>reads and creates classes from a bz compressed file</refpurpose> </refnamediv> <refsect1> <title>Description</title> <funcsynopsis> <funcprototype> <funcdef><function>bcompile_load</function></funcdef> <paramdef>string <parameter>filename</parameter></paramdef> </funcprototype> </funcsynopsis> &warn.experimental.func; <para> Reads data from a bzcompressed file and creates classes from the bytecodes </para> <example> <title><function>bcompile_load</function> example</title> <programlisting role="php"> <![CDATA[ <?php bcompile_load("/tmp/example"); print_r(get_defined_classes()); ?> ]]> </programlisting> </example> </refsect1> </refentry> <!-- load_exe --> <refentry id="pecl.bcompiler.bcompile-load-exe"> <refnamediv> <refname>bcompile_load_exe</refname> <refpurpose>reads and creates classes from a bcompiler exe file</refpurpose> </refnamediv> <refsect1> <title>Description</title> <funcsynopsis> <funcprototype> <funcdef><function>bcompile_load_exe</function></funcdef> <paramdef>string <parameter>filename</parameter></paramdef> </funcprototype> </funcsynopsis> &warn.experimental.func; <para> Reads data from a bcompiler exe file and creates classes from the bytecodes </para> <example> <title><function>bcompile_load</function> example</title> <programlisting role="php"> <![CDATA[ <?php bcompile_load_exe("/tmp/example.exe"); print_r(get_defined_classes()); ?> ]]> </programlisting> </example> </refsect1> </refentry> <!-- parse_class --> <refentry id="pecl.bcompiler.parse_class"> <refnamediv> <refname>bcompile_parse_class</refname> <refpurpose>reads the bytecodes of a class and calls back to a user function</refpurpose> </refnamediv> <refsect1> <title>Description</title> <funcsynopsis> <funcprototype> <funcdef><function>bcompile_parse_class</function></funcdef> <paramdef>string <parameter>class</parameter></paramdef> <paramdef>string <parameter>callback</parameter></paramdef> </funcprototype> </funcsynopsis> &warn.experimental.func; <para> reads the bytecodes of a class and calls back to a user function </para> <example> <title><function>bcompile_parse_class</function> example</title> <programlisting role="php"> <![CDATA[ <?php function readByteCodes($data) { print_r($data); } bcompile_parse_class("DB","readByteCodes"); ?> ]]> </programlisting> </example> </refsect1> </refentry> </reference> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> Index: pear/PECL/bcompiler/config.m4 +++ pear/PECL/bcompiler/config.m4 dnl dnl $Id: config.m4,v 1.1 2002/07/23 06:55:57 alan_k Exp $ dnl PHP_ARG_ENABLE(bcompiler,whether to enable bcompiler support, [ --enable-bcompiler Enable bcompiler support]) if test "$PHP_BCOMPILER" = "yes"; then AC_DEFINE(HAVE_BCOMPILER,1,[Whether you want bcompiler support]) PHP_NEW_EXTENSION(bcompiler, bcompiler.c, $ext_shared) fi Index: pear/PECL/bcompiler/config.m4.old +++ pear/PECL/bcompiler/config.m4.old dnl $Id: config.m4.old,v 1.1 2002/07/23 06:55:57 alan_k Exp $ dnl config.m4 for extension tokenizer dnl Otherwise use enable: PHP_ARG_ENABLE(bcompiler, whether to enable bcompiler support, [ --enable-tokenizer Enable bcompiler support]) if test "$PHP_BCOMPILER" != "no"; then PHP_EXTENSION(bcompiler, $ext_shared) fi Index: pear/PECL/bcompiler/php_bcompiler.h +++ pear/PECL/bcompiler/php_bcompiler.h /* __header_here__ */ #include "ext/standard/file.h" #ifndef PHP_BCOMPILER_H #define PHP_BCOMPILER_H extern zend_module_entry bcompiler_module_entry; #define phpext_bcompiler_ptr &bcompiler_module_entry #ifdef PHP_WIN32 #define PHP_BCOMPILER_API __declspec(dllexport) #else #define PHP_BCOMPILER_API #endif #ifdef ZTS #include "TSRM.h" #endif PHP_MINIT_FUNCTION(bcompiler); PHP_MSHUTDOWN_FUNCTION(bcompiler); PHP_RINIT_FUNCTION(bcompiler); PHP_RSHUTDOWN_FUNCTION(bcompiler); PHP_MINFO_FUNCTION(bcompiler); /* __function_declarations_here__ */ PHP_FUNCTION(confirm_bcompiler_compiled); /* For testing, remove later. */ PHP_FUNCTION(bcompile_write_class); /* Write a class */ PHP_FUNCTION(bcompile_write_header); /* Write the header */ PHP_FUNCTION(bcompile_write_exe_footer); /* Write the end zero byte */ PHP_FUNCTION(bcompile_write_footer); /* Write the tail for a exe type file*/ PHP_FUNCTION(bcompile_read); /* Read a file handle */ PHP_FUNCTION(bcompile_load); /* Read a file handle */ PHP_FUNCTION(bcompile_load_exe); /* Read a file handle */ PHP_FUNCTION(bcompile_parse_class); /* Write a class */ /* Declare any global variables you may need between the BEGIN and END macros here: */ ZEND_BEGIN_MODULE_GLOBALS(bcompiler) void *stream; /* output stream */ char* buffer; /* our read buffer */ zval* callback; /* callback for parser */ zval* callback_value; /* callback for grouped calls */ char* callback_key; /* callback key for associated vals*/ ZEND_END_MODULE_GLOBALS(bcompiler) #include "zend.h" #include "zend_variables.h" // for zval_dtor() /* In every utility function you add that needs to use variables in php_bcompiler_globals, call TSRM_FETCH(); after declaring other variables used by that function, or better yet, pass in TSRMG_CC after the last function argument and declare your utility function with TSRMLS_DC after the last declared argument. Always refer to the globals in your function as COMPILER_G(variable). You are encouraged to rename these macros something shorter, see examples in any other php module directory. */ #ifdef ZTS #define BCOMPILERG(v) TSRMG(bcompiler_globals_id, zend_bcompiler_globals *, v) #else #define BCOMPILERG(v) (bcompiler_globals.v) #endif typedef void* (*apc_malloc_t)(int); /* By convention all apc_serialize_* functions serialize objects of the * specified type to the serialization buffer (dst). The apc_deserialize_* * functions deserialize objects of the specified type from the * deserialization buffer (src). The apc_create_* functions allocate * objects of the specified type, then call the appropriate deserialization * function. */ void bcompiler_read(TSRMLS_DC); /* general */ void apc_serialize_string(char* string TSRMLS_DC); void apc_create_string(char** string TSRMLS_DC); void apc_serialize_zstring(char* string, int len TSRMLS_DC); void apc_create_zstring(char** string TSRMLS_DC); void apc_serialize_arg_types(zend_uchar* arg_types TSRMLS_DC); void apc_create_arg_types(zend_uchar** arg_types TSRMLS_DC); /* pre-bcompiler routines */ void apc_serialize_magic(TSRMLS_DC); int apc_deserialize_magic(TSRMLS_DC); /* routines for handling structures from zend_llist.h */ void apc_serialize_zend_llist(zend_llist* list TSRMLS_DC); void apc_deserialize_zend_llist(zend_llist* list TSRMLS_DC); void apc_create_zend_llist(zend_llist** list TSRMLS_DC); /* routines for handling structures from zend_hash.h */ void apc_serialize_hashtable(HashTable* ht, void* funcptr TSRMLS_DC); void apc_deserialize_hashtable(HashTable* ht, void* funcptr, void* dptr, int datasize, char exists TSRMLS_DC); void apc_create_hashtable(HashTable** ht, void* funcptr, void* dptr, int datasize TSRMLS_DC); /* routines for handling structures from zend.h */ void apc_serialize_zvalue_value(zvalue_value* zvv, int type TSRMLS_DC); void apc_deserialize_zvalue_value(zvalue_value* zvv, int type TSRMLS_DC); void apc_serialize_zval_ptr(zval** zv TSRMLS_DC); void apc_serialize_zval(zval* zv TSRMLS_DC); void apc_deserialize_zval(zval* zv TSRMLS_DC); void apc_create_zval(zval** zv TSRMLS_DC); void apc_free_zval(zval** zv TSRMLS_DC); void apc_serialize_zend_function_entry(zend_function_entry* zfe TSRMLS_DC); void apc_deserialize_zend_function_entry(zend_function_entry* zfe TSRMLS_DC); void apc_serialize_zend_property_reference(zend_property_reference* zpr TSRMLS_DC); void apc_deserialize_zend_property_reference(zend_property_reference* zpr TSRMLS_DC); void apc_serialize_zend_overloaded_element(zend_overloaded_element* zoe TSRMLS_DC); void apc_deserialize_zend_overloaded_element(zend_overloaded_element* zoe TSRMLS_DC); void apc_serialize_zend_class_entry(zend_class_entry* zce TSRMLS_DC); void apc_deserialize_zend_class_entry(zend_class_entry* zce TSRMLS_DC); void apc_create_zend_class_entry(zend_class_entry** zce TSRMLS_DC); /* routines for handling structures from zend_compile.h */ void apc_serialize_znode(znode* zn TSRMLS_DC); void apc_deserialize_znode(znode* zn TSRMLS_DC); void apc_serialize_zend_op(int i, zend_op* zo TSRMLS_DC); void apc_deserialize_zend_op(zend_op* zo TSRMLS_DC); void apc_serialize_zend_op_array(zend_op_array* zoa TSRMLS_DC); void apc_deserialize_zend_op_array(zend_op_array* zoa, int master TSRMLS_DC); void apc_create_zend_op_array(zend_op_array** zoa TSRMLS_DC); void apc_serialize_zend_internal_function(zend_internal_function* zif TSRMLS_DC); void apc_deserialize_zend_internal_function(zend_internal_function* zif TSRMLS_DC); void apc_serialize_zend_overloaded_function(zend_overloaded_function* zof TSRMLS_DC); void apc_deserialize_zend_overloaded_function(zend_overloaded_function* zof TSRMLS_DC); void apc_serialize_zend_function(zend_function* zf TSRMLS_DC); void apc_deserialize_zend_function(zend_function* zf TSRMLS_DC); void apc_create_zend_function(zend_function** zf TSRMLS_DC); void apc_free_zend_function(zend_function** zf TSRMLS_DC); /* special purpose */ void apc_serialize_zend_function_table(HashTable* gft TSRMLS_DC); void apc_deserialize_zend_function_table(HashTable* gft TSRMLS_DC); void apc_serialize_zend_class_table(HashTable* gct TSRMLS_DC); int apc_deserialize_zend_class_table(HashTable* gct TSRMLS_DC); void apc_fixup_opcodes(zend_op* opcodes, int num_ops, apc_malloc_t ctor TSRMLS_DC); void apc_fixup_class_table(HashTable* ht, apc_malloc_t ctor TSRMLS_DC); void apc_free_string(char **ptr TSRMLS_DC); void apc_serialize_debug(char * string TSRMLS_DC); #endif /* PHP_BCOMPILER_H */ /* __footer_here__ */ Index: pear/PECL/bcompiler/examples/bcompiler.php +++ pear/PECL/bcompiler/examples/bcompiler.php <? if(!extension_loaded('bcompiler')) { dl('bcompiler.so'); } require_once('DB.php'); $fh = fopen("/tmp/testcompile","w"); bcompile_write_header($fh); bcompile_write_class($fh,'DB'); bcompile_write_class($fh,'PEAR_error'); bcompile_write_class($fh,'DB_error'); fclose($fh); $fh = bzopen("/tmp/testcompileb","w"); bcompile_write_header($fh); bcompile_write_class($fh,'DB'); bcompile_write_class($fh,'PEAR_error'); bcompile_write_class($fh,'DB_error'); fclose($fh); $fh = fopen("/tmp/testcompile2","w"); $fc = fopen(dirname(__FILE__)."/code","r"); $data = fread($fc,filesize(dirname(__FILE__)."/code")); fwrite($fh,$data, filesize(dirname(__FILE__)."/code")); fclose($fc); $start = ftell($fh); $bz = bzopen($fh,"w"); bcompile_write_header($bz); bcompile_write_class($bz,'DB'); bcompile_write_class($bz,'PEAR_error'); bcompile_write_class($bz,'DB_error'); bcompile_write_footer($bz); fclose($bz); $fh= fopen("/tmp/testcompile2","a"); fseek($fh,0,SEEK_END); bcompile_write_exe_footer($fh,$start); fclose($fh); ?> Done Index: pear/PECL/bcompiler/examples/bcompiler_parse.php +++ pear/PECL/bcompiler/examples/bcompiler_parse.php <? if(!extension_loaded('bcompiler')) { dl('bcompiler.so'); } require_once('DB.php'); define('ZEND_FETCH_GLOBAL', 0); define('ZEND_FETCH_LOCAL', 1); define('ZEND_FETCH_STATIC', 2); /* var status for backpatching */ define('BP_VAR_R', 0); define('BP_VAR_W', 1); define('BP_VAR_RW', 2); define('BP_VAR_IS', 3); define('BP_VAR_NA', 4); /* if not applicable */ define('BP_VAR_FUNC_ARG', 5); define('BP_VAR_UNSET', 6); define('ZEND_IS_CONST' ,1); define('ZEND_IS_TMP_VAR' ,2); define('ZEND_IS_VAR' ,4); define('ZEND_IS_UNUSED' ,8); /* Unused variable */ function test($data) { global $generator; if (@$data['ISEND']) { //print_r($data); if ($generator->_opcodes) { $generator->_pass_two(); } //echo "NEW GENERATOR"; $generator = new generator; } /* echo " "; echo @str_pad($data['LINE'],4) . ":"; echo str_pad($data['OPCODE'],4); echo str_pad($data['OPCODE_STR'],20); if (@$data['HASH'] || @$data['CLASS']) { echo " ".@$data['HASH'] . " ". @$data['CLASS'] ; } echo ":"; echo str_pad(@$data['RESULT'] ,15); echo "= "; echo str_pad(@$data['OP1'] ,15); echo str_pad(@$data['OP2'] ,15); */ $generator->_add_op($data); echo "\n"; //print_r($data); } $generator = new generator; $classname = "vending_omnitor"; bcompile_parse_class('test','DB'); class generator { var $zend_to_realname; var $realname_to_zend; var $args; var $function_name; var $_fcall; // funciton about to be called. var $send_vars = array(); var $_gotos = array(); var $init_opcode; // initilized opcode var $Ts = array(); var $_init_static_vars = FALSE; var $_string_buffer; // deprecieated function op_begin_hash_def($d) { // //$this->function_name = $d['HASH']; } function op_opcode_array($d) { // expects an op array... if (!$d) { return; } global $classname; $this->init_opcode = unserialize(serialize($d)); $this->function_name = $d['FUNCTION_NAME']; $this->_out2("",TRUE); $this->_out2("PHP_FUNCTION({$classname}_".$d['FUNCTION_NAME']. ")\n{"); ## TODO = the base_function stuff needs sorting out - re: pointer or what... $out = " /* dummy op codes */ znode* result= (zend_op*) emalloc(sizeof(znode)); znode* op1= (zend_op*) emalloc(sizeof(znode)); znode* op2= (zend_op*) emalloc(sizeof(znode)); zval* result_zv = (zval*) emalloc(sizeof(zval)); zval* op1_zv = (zval*) emalloc(sizeof(zval)); zval* op2_zv = (zval*) emalloc(sizeof(zval)); zvalue* result_zvalue = (zval*) emalloc(sizeof(zvalue)); zvalue* op1_zvalue = (zval*) emalloc(sizeof(zvalue)); zvalue* op2_zvalue = (zval*) emalloc(sizeof(zvalue)); int extended_value = 0; zend_execute_data execute_data; zend_function base_function; /* not really sure how this is needed.....*/ base_function.type = {$d['TYPE']} ; base_function.function_name = \"{$d['FUNCTION_NAME']}\"; EG(execute_data_ptr) = &execute_data; /* Initialize execute_data */ execute_data.fbc = NULL; execute_data.object.ptr = NULL; execute_data.Ts = (temp_variable *) do_alloca(sizeof(temp_variable)*".$d['T']."); execute_data.original_in_execution=EG(in_execution); EG(in_execution) = 1; /* EG(opline_ptr) = &execute_data.opline; */ execute_data.function_state.function = base_function; EG(function_state_ptr) = &execute_data.function_state; "; $this->_out2($out); if (@$this->args) { $out = " if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \""; $start_optional = FALSE; foreach($this->args as $d) { //print_r($d); if ($d['OPCODE'] == 64) { // RECV_INIT if (!$start_optional) { $out .= "|"; $start_optional = TRUE; } } $out .= "z"; } $out .= "\" "; foreach($this->args as $d) { $out .= ", &". $this->_get_zval_ptr_ptr("RESULT", $d) ; } $out .=")== FAILURE) return;"; $this->_out2($out); /* initialize values */ foreach($this->args as $d) { if ($d['OPCODE'] != 64) { // RECV_INIT continue; } if (($d["OP2.u.constant.type"] == IS_CONSTANT) || ($d["OP2.u.constant.type"]==IS_CONSTANT_ARRAY)) { echo "NOT SUPPORTED YET"; exit; } else { // lets hope it was a string! $this->_out2(" if (ZEND_NUM_ARGS() < {$d['OP1']}) { "); $this->_assign_zval("execute_data.Ts[{$d['RESULT.u.var']}].tmp_var",$d['OP2.u.constant.val']); $this->_out2(" } "); } } } } function op_add_string($d) { list($free,$var) = $this->_get_zval_ptr("OP1",$d); $this->_out2(" add_string_to_string( execute_data.Ts[". $d["RESULT.u.var"]."].tmp_var, ". $var . ", \"". $d["OP2.u.constant.val"] . "\")"); } function op_add_var($d) { list($free, $var2) = $this->_get_zval_ptr("OP2",$d); list($free, $var1) = $this->_get_zval_ptr("OP1",$d); $this->_out2(" { zval var_copy; int use_copy; zval *var = $var2 zend_make_printable_zval(var, &var_copy, &use_copy); if (use_copy) { var = &var_copy; } add_string_to_string( &execute_data.Ts[". $d["RESULT.u.var"]."].tmp_var, $var1, var); if (use_copy) { zval_dtor(var); } } "); // FREE_OP(execute_data.Ts, &EX(opline)->op2, EG(free_op2)); } function op_assign($d) { //print_r($d); /* ??? what if its an int or something? */ //$string_to_use = $this->_string_buffer[$d['OP2']]; //$args_to_use = $this->_string_buffer_args[$d['OP2']]; //$var = $this->zend_to_realname[$d['OP1']]; //$this->_out( " $var = sprintf(\"{$string_to_use}\",". implode(",",$args_to_use).");"); $this->_out2(" { "); $this->_make_opcode("RESULT",$d); $this->_make_opcode("OP1",$d); $this->_make_opcode("OP2",$d); $this->_out2(" zval *value; value = get_zval_ptr(op2, execute_data.Ts, &EG(free_op2), BP_VAR_R); zend_assign_to_variable(result, op1, op2, value, (EG(free_op2)?IS_TMP_VAR:{$d['OP2.op_type']}), execute_data.Ts TSRMLS_CC); } "); } function op_assign_ref($d) { $this->_make_opcode("RESULT",$d); $this->_make_opcode("OP1",$d); $this->_make_opcode("OP2",$d); $this->_out2(" zend_assign_to_variable_reference(result, get_zval_ptr_ptr(&op1, execute_data.Ts, BP_VAR_W), get_zval_ptr_ptr(&op2, execute_data.Ts, BP_VAR_W), execute_data.Ts TSRMLS_CC); "); } function op_bool_not($d) { $this->_make_opcode('OP1',$d); $this->_out2(" EG(unary_op) = get_unary_op({$d['OPCODE']}); EG(unary_op)(&execute_data.Ts[{$d['RESULT.u.var']}].tmp_var, get_zval_ptr(op1, execute_data.Ts, &EG(free_op1), BP_VAR_R) ); FREE_OP(execute_data.Ts, &op1, EG(free_op1)); "); } function op_do_fcall($d) { $this->_make_opcode("OP1",$d); $this->_out2(" { zval *fname = get_zval_ptr(&op1, execute_data.Ts, &EG(free_op1), BP_VAR_R); if (zend_hash_find(EG(function_table), fname->value.str.val, fname->value.str.len+1, (void **) &execute_data.function_state.function)==FAILURE) { zend_error(E_ERROR, \"Unknown function: %s()\n\", fname->value.str.val); } FREE_OP(execute_data.Ts, &op1, EG(free_op1)); zend_ptr_stack_push(&EG(arg_types_stack), execute_data.object.ptr); execute_data.object.ptr = NULL; "); $this->_do_fcall_common($d); $this->_out2(" } "); } function op_do_fcall_by_name($d) { if ($this->_fcall) { /* object + array! */ $this->_out2(" call_user_function_ex(CG(function_table), execute_data.Ts[{$this->_fcall['OP1.u.var']}].var.ptr, \"{$this->_fcall['OP2.u.constant.val']}\", execute_data.Ts[{$d['RESULT.u.var']}].var.ptr, 0, NULL, 0); "); } print_r($d); return; $this->_out2(" execute_data.function_state.function = execute_data.fbc; "); $this->_do_fcall_common($d); } function op_echo($d) { list ($free, $var) = $this->_get_zval_ptr("OP1",$d); //zend_print_variable(get_zval_ptr(&EX(opline)->op1, EX(Ts), &EG(free_op1), BP_VAR_R)); if ($var{0} == '"') { $this->_out2(" zend_write({$var}, ".(strlen($var)-1) ."); "); } else { $this->_out2(" zend_print_variable($var); "); //FREE_OP(EX(Ts), &EX(opline)->op1, EG(free_op1)); } } function op_fetch_w ($d) { // zend_fetch_var_address(EX(opline), execute_data.Ts, BP_VAR_W TSRMLS_CC); // initialize a new variable of type $d[op2].type // result: is set to refer to it.. $this->_fetch_var_address($d, BP_VAR_W); //$this->zend_to_realname[$d['RESULT']] = $d['OP1']; //$this->realname_to_zend[$d['OP1']] = $d['RESULT']; } function op_fetch_r($d) { $this->_fetch_var_address($d, BP_VAR_R); //$this->zend_to_realname[$d['RESULT']] = $d['OP1']; //if (!@$this->realname_to_zend[$d['OP1']]) { // $this->realname_to_zend[$d['OP1']] = $d['RESULT']; //} } function op_fetch_constant($d) { $starterror = $GLOBALS['php_errormsg']; $const = @constant($d['OP1.u.constant.val']); if ($starterror != $GLOBALS['php_errormsg']) { echo "NOT A CONSTANT: {$d['OP1.u.constant.val']}"; exit; } $this->_assign_zval("execute_data.Ts[{$d['RESULT.u.var']}].tmp_var",$const); } function op_init_string($d) { $this->_out2( " execute_data.Ts[". $d['RESULT.u.var'] . "].tmp_var.value.str.val = emalloc(1); execute_data.Ts[". $d['RESULT.u.var'] . "].tmp_var.value.str.val[0] = 0; execute_data.Ts[". $d['RESULT.u.var'] . "].tmp_var.value.str.len = 0; execute_data.Ts[". $d['RESULT.u.var'] . "].tmp_var.refcount = 1; "); } function op_init_fcall_by_name($d) { /* handle these types: */ $this->_fcall = unserialize(serialize($d)); return; $this->_make_opcode("OP1",$d); $this->_make_opcode("OP2",$d); $this->_out2(" zval *function_name; zend_function *function; HashTable *active_function_table; zval tmp; zend_ptr_stack_n_push(&EG(arg_types_stack), 2, execute_data.fbc, execute_data.object.ptr); if ({$d['EXTENDED']} & ZEND_CTOR_CALL) { /* constructor call */ if ({$d['OP1.op_type']} == IS_VAR) { SELECTIVE_PZVAL_LOCK(*execute_data.Ts[{$d['OP1.u.var']}].var.ptr_ptr, &op1); } if ({$d['OP2.op_type']} == IS_VAR) { PZVAL_LOCK(*execute_data.Ts[{$d['OP1.u.var']}].var.ptr_ptr); } } function_name = get_zval_ptr(&op2, execute_data.Ts, &EG(free_op2), BP_VAR_R); tmp = *function_name; zval_copy_ctor(&tmp); convert_to_string(&tmp); function_name = &tmp; zend_str_tolower(tmp.value.str.val, tmp.value.str.len); if ({$d['OP1.op_type']} != IS_UNUSED) { if ({$d['OP1.op_type']}==IS_CONST) { /* used for class_name::function() */ zend_class_entry *ce; zval **object_ptr_ptr; if (zend_hash_find(EG(active_symbol_table), \"this\", sizeof(\"this\"), (void **) &object_ptr_ptr)==FAILURE) { execute_data.object.ptr=NULL; } else { /* We assume that \"this\" is already is_ref and pointing to the object. If it isn't then tough */ execute_data.object.ptr = *object_ptr_ptr; execute_data.object.ptr->refcount++; /* For this pointer */ } if (zend_hash_find(EG(class_table), \"{$d['OP1.u.constant.val']}\", ". (strlen($d['OP1.u.constant.val'])+1). ", (void **) &ce)==FAILURE) { /* class doesn't exist */ zend_error(E_ERROR, \"Undefined class name '%s'\", {$d['OP1.u.constant.val']}); } active_function_table = &ce->function_table; } else { /* used for member function calls */ execute_data.object.ptr = _get_object_zval_ptr(&op1, execute_data.Ts, &EG(free_op1) TSRMLS_CC); if ((!execute_data.object.ptr && execute_data.Ts[{$d['OP1.u.var']}].EA.type==IS_OVERLOADED_OBJECT) || ((execute_data.object.ptr && execute_data.object.ptr->type==IS_OBJECT) && (execute_data.object.ptr->value.obj.ce->handle_function_call))) { /* overloaded function call */ zend_overloaded_element overloaded_element; overloaded_element.element = *function_name; overloaded_element.type = OE_IS_METHOD; if (execute_data.object.ptr) { execute_data.Ts[{$d['OP1.u.var']}].EA.data.overloaded_element.object = execute_data.object.ptr; execute_data.Ts[{$d['OP1.u.var']}].EA.data.overloaded_element.type = BP_VAR_NA; execute_data.Ts[{$d['OP1.u.var']}].EA.data.overloaded_element.elements_list = (zend_llist *) emalloc(sizeof(zend_llist)); zend_llist_init(execute_data.Ts[{$d['OP1.u.var']}].EA.data.overloaded_element.elements_list, sizeof(zend_overloaded_element), NULL, 0); } zend_llist_add_element(execute_data.Ts[{$d['OP1.u.var']}].EA.data.overloaded_element.elements_list, &overloaded_element); execute_data.fbc = (zend_function *) emalloc(sizeof(zend_function)); execute_data.fbc->type = ZEND_OVERLOADED_FUNCTION; execute_data.fbc->common.arg_types = NULL; execute_data.fbc->overloaded_function.var = {$d['OP1.u.var']}; goto overloaded_function_call_cont; } if (!execute_data.object.ptr || execute_data.object.ptr->type != IS_OBJECT) { zend_error(E_ERROR, \"Call to a member function on a non-object\"); } if (!execute_data.object.ptr->is_ref && execute_data.object.ptr->refcount > 1) { zend_error(E_ERROR, \"Bug: Problem in method call\n\"); } execute_data.object.ptr->is_ref=1; execute_data.object.ptr->refcount++; /* For $ this pointer */ active_function_table = &(execute_data.object.ptr->value.obj.ce->function_table); } } else { /* function pointer */ execute_data.object.ptr = NULL; active_function_table = EG(function_table); } if (zend_hash_find(active_function_table, function_name->value.str.val, function_name->value.str.len+1, (void **) &function)==FAILURE) { zend_error(E_ERROR, \"Call to undefined function: %s()\", function_name->value.str.val); } zval_dtor(&tmp); execute_data.fbc = function; overloaded_function_call_cont: FREE_OP(execute_data.Ts, &op2, EG(free_op2)); } "); } function op_include_or_eval($d) { $string_to_use = $this->_string_buffer[$d['OP1']]; $args_to_use = $this->_string_buffer_args[$d['OP1']]; $this->_out2( " /* NOT SUPPORTED !*/"); // $this->_out2( " /*tmpstring = sprintf(\"{$string_to_use}\",". implode(",",$args_to_use).");*/"); $this->_out2( " /* zend_include_file(tmpstring);*/"); $this->_out2( " /* END NOT SUPPORTED */"); } function op_return($d) { //$this->init_opcode['return_reference'] $this->_out2( " { zval *retval_ptr; zval **retval_ptr_ptr; "); if (( $this->init_opcode['return_reference'] == 1) && ($d['OP1.op_type'] != IS_CONST) && ($d['OP1.op_type'] != IS_TMP_VAR)) { $this->_make_opcode("OP1",$d); $this->_out2(" retval_ptr_ptr = get_zval_ptr_ptr(&op1, execute_data.Ts), BP_VAR_W); SEPARATE_ZVAL_TO_MAKE_IS_REF(retval_ptr_ptr); (*retval_ptr_ptr)->refcount++; (*EG(return_value_ptr_ptr)) = (*retval_ptr_ptr); "); } else { $this->_make_opcode("OP1",$d); $this->_out2(" retval_ptr = get_zval_ptr(&op1, execute_data.Ts, &EG(free_op1), BP_VAR_R); if (!EG(free_op1)) { /* Not a temp var */ if (PZVAL_IS_REF(retval_ptr) && retval_ptr->refcount > 0) { ALLOC_ZVAL(*(EG(return_value_ptr_ptr))); **EG(return_value_ptr_ptr) = *retval_ptr; (*EG(return_value_ptr_ptr))->is_ref = 0; (*EG(return_value_ptr_ptr))->refcount = 1; zval_copy_ctor(*EG(return_value_ptr_ptr)); } else { *EG(return_value_ptr_ptr) = retval_ptr; retval_ptr->refcount++; } } else { ALLOC_ZVAL(*(EG(return_value_ptr_ptr))); **EG(return_value_ptr_ptr) = *retval_ptr; (*EG(return_value_ptr_ptr))->refcount = 1; (*EG(return_value_ptr_ptr))->is_ref = 0; } "); } $this->_out2(" free_alloca(execute_data.Ts); EG(in_execution) = execute_data.original_in_execution; return; } "); } function op_jmp($d) { if (($d['JMP']-1) == $d['LINE']) { return; } $this->_gotos[$d['JMP']] = 1; $this->_out( " goto line_".$d['JMP']) ; } function op_jmpz($d) { $this->_make_opcode("OP1",$d); $this->_out2(" if (!i_zend_is_true(get_zval_ptr(op1, execute_data.Ts, &EG(free_op1), BP_VAR_R))) { FREE_OP(execute_data.Ts, op1, EG(free_op1)); goto line_{$d['OP2.u.opline_num']}; } FREE_OP(execute_data.Ts, op1, EG(free_op1)); "); $this->_gotos[$d['JMP']] = 1; } function op_jmp_no_ctor($d) { // jump past object initialization call if it doesnt exist. list($free,$var) = $this->_get_zval_ptr("OP1", $d); $this->_out2(" if (!{$var}->value.obj.ce->handle_function_call && !zend_hash_exists(&{$var}->value.obj.ce->function_table, {$var}->value.obj.ce->name, {$var}->value.obj.ce->name_length+1)) { goto line_{$d['OP2.u.opline_num']}; } "); return; $this->_out2(" { zval *object; "); if ($d['OP1.op_type'] == IS_VAR) { $this->_out2(" PZVAL_LOCK(*execute_data.Ts[{$d['OP1.u.var']}].var.ptr_ptr); "); } $this->_make_opcode("OP1",$d); //print_r($d); //exit; $this->_out2(" object = get_zval_ptr(&op1, execute_data.Ts, &EG(free_op1), BP_VAR_R); if (!object->value.obj.ce->handle_function_call && !zend_hash_exists(&object->value.obj.ce->function_table, object->value.obj.ce->name, object->value.obj.ce->name_length+1)) { goto line_{$d['OP2.u.opline_num']}; } } "); $this->_gotos[$d['OP2.u.opline_num']] = 1; } function op_new($d) { list($free,$var) = $this->_get_zval_ptr("OP1", $d); if ($var{0} == '"') { //echo "GOT STRING $var"; $lvar = strtolower($var); $this->_out2( " { zend_class_entry *ce; zend_hash_find(EG(class_table), $lvar, ".(strlen($var) -1).", (void **) &ce); execute_data.Ts[{$d['RESULT.u.var']}].var.ptr_ptr = &execute_data.Ts[{$d['RESULT.u.var']}].var.ptr; ALLOC_ZVAL(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); object_init_ex(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr, ce); execute_data.Ts[{$d['RESULT.u.var']}].var.ptr->refcount=1; execute_data.Ts[{$d['RESULT.u.var']}].var.ptr->is_ref=1; } "); return; } $this->_make_opcode("OP1", $d); $this->_out2(" { zval *tmp = get_zval_ptr(&op1, execute_data.Ts, &EG(free_op1), BP_VAR_R); zval class_name; zend_class_entry *ce; class_name = *tmp; zval_copy_ctor(&class_name); convert_to_string(&class_name); zend_str_tolower(class_name.value.str.val, class_name.value.str.len); if (zend_hash_find(EG(class_table), class_name.value.str.val, class_name.value.str.len+1, (void **) &ce)==FAILURE) { zend_error(E_ERROR, \"Cannot instantiate non-existent class: %s\", class_name.value.str.val); } execute_data.Ts[{$d['RESULT.u.var']}].var.ptr_ptr = &execute_data.Ts[{$d['RESULT.u.var']}].var.ptr; ALLOC_ZVAL(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); object_init_ex(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr, ce); execute_data.Ts[{$d['RESULT.u.var']}].var.ptr->refcount=1; execute_data.Ts[{$d['RESULT.u.var']}].var.ptr->is_ref=1; zval_dtor(&class_name); FREE_OP(execute_data.Ts, &op1, EG(free_op1)); } "); } function op_recv($d) { //print_r($d); $this->args[$d['OP1.u.constant.val'] ] = $d; } function op_recv_init($d) { $this->args[$d['OP1.u.constant.val'] ] = unserialize(serialize($d)); } function op_send_var($d) { $this->_make_opcode("OP1",$d); $this->_out2(" if (({$d['EXTENDED']} == ZEND_DO_FCALL_BY_NAME) && ARG_SHOULD_BE_SENT_BY_REF({$d['OP2.u.opline_num']}, execute_data.fbc , execute_data.fbc->common.arg_types)) { zval **varptr_ptr; zval *varptr; varptr_ptr = get_zval_ptr_ptr(&op1,execute_data.Ts, BP_VAR_W); if (!varptr_ptr) { zend_error(E_ERROR, \"Only variables can be passed by reference\"); } SEPARATE_ZVAL_TO_MAKE_IS_REF(varptr_ptr); varptr = *varptr_ptr; varptr->refcount++; zend_ptr_stack_push(&EG(argument_stack), varptr); } else { zval *varptr; varptr = get_zval_ptr(&op1, execute_data.Ts, &EG(free_op1), BP_VAR_R); if (varptr == &EG(uninitialized_zval)) { ALLOC_ZVAL(varptr); INIT_ZVAL(*varptr); varptr->refcount = 0; } else if (PZVAL_IS_REF(varptr)) { zval *original_var = varptr; ALLOC_ZVAL(varptr); *varptr = *original_var; varptr->is_ref = 0; varptr->refcount = 0; zval_copy_ctor(varptr); } varptr->refcount++; zend_ptr_stack_push(&EG(argument_stack), varptr); FREE_OP(execute_data.Ts, op1, EG(free_op1)); } "); } function op_send_val($d) { $this->_make_opcode("OP1",$d); $this->_out2(" if ({$d['EXTENDED']} == ZEND_DO_FCALL_BY_NAME && ARG_SHOULD_BE_SENT_BY_REF({$d['OP2.u.opline_num']}, execute_data.fbc , execute_data.fbc->common.arg_types)) { zend_error(E_ERROR, \"Cannot pass parameter %d by reference\", {$d['OP2.u.opline_num']}); } { zval *valptr; zval *value; value = get_zval_ptr(op1, execute_data.Ts, &EG(free_op1), BP_VAR_R); ALLOC_ZVAL(valptr); *valptr = *value; if (!EG(free_op1)) { zval_copy_ctor(valptr); } INIT_PZVAL(valptr); zend_ptr_stack_push(&EG(argument_stack), valptr); } "); } /* ---------------NON OP CODES ------------*/ var $_opcodes = array(); var $_pass = 0; function _add_op($d) { if ($d['LINE'] != -1) { $this->_opcodes[$d['LINE']] = $d; } $this->_do_op($d); } function _do_op($data) { $this->_outComment($data); if (@$this->_gotos[$data['LINE']]) { $this->_out2("line_{$data['LINE']}:",FALSE); } $op = "op_".strtolower(trim($data['OPCODE_STR'])); if (method_exists($this, $op)) { $this->$op($data); } else { if (!$this->_pass) { $this->_out2("/* --TODO--*/"); } } } function _out($s,$do_cr=TRUE) { //if ($this->_pass != 0) { echo $s; if ($do_cr) { echo "\n"; } //} } function _out2($data) { if (!$this->_pass) return; echo "$data\n"; } function _outComment($data) { $this->_out2(" /*". str_pad($data['LINE'],4) . ":" . //str_pad($data['OPCODE'],4) . str_pad($data['OPCODE_STR'],20) . ":". str_pad(@$data['RESULT'] ,15) . "= " . str_pad(@$data['OP1'] ,15) . "," . str_pad(@$data['OP2'] ,15) . "*/" ); } function _pass_two() { echo "\n\n--------------------------------------------------\n\n"; $this->_pass=1; //print_r($this->_opcodes); global $classname; $this->op_opcode_array($this->init_opcode); foreach($this->_opcodes as $data) { $this->_do_op($data); } $this->_out("}"); echo "\n\n--------------------------------------------------\n\n"; } function _set_zendvalue($zend,$real) { $this->zend_to_realname[$zend] = $real; $this->realname_to_zend[$real] = $zend; } function _get_zendvalue($zend) { return @$this->zend_to_realname[$zend]; } function _init_static_vars() { if ($this->_init_static_vars) { return; } $this->_out2(" /* make sure static variables are initialized */ if (!EG(active_op_array)->static_variables) { ALLOC_HASHTABLE(EG(active_op_array)->static_variables); zend_hash_init(EG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } "); $this->_init_static_vars = TRUE; } function _get_zval_ptr($opcode, $d) { switch ($d[$opcode.".op_type"]) { case 1: //ZEND_IS_CONST: /* probably need to make a zval here */ //echo "CONST?".$d[$opcode.".u.constant.val"]; return array(0,"\"".$d[$opcode.".u.constant.val"]."\""); case 2: //ZEND_IS_TMP_VAR: return array(0,"(&execute_data.Ts[".$d[$opcode.".u.var"]."].tmp_var)"); case 4: //ZEND_IS_VAR: //if (@$this->Ts[$d[$opcode.".u.var"]]["var.ptr"]) { /*PZVAL_UNLOCK(Ts[node->u.var].var.ptr); */ return array(0,"(execute_data.Ts[".$d[$opcode.".u.var"]."].var.ptr)"); //} //print_r($d); //echo "\nUNHANDLED VAR : see get_zval_ptr\n"; exit; default: echo "Unknown type ". $d[$opcode.".op_type"]; exit; } } function _get_zval_ptr_ptr($opcode, $d) { return "execute_data.Ts[".((int) $d[$opcode.".u.var"]) ."].var.ptr_ptr"; } function _fetch_var_address($d,$type) { // variable can be string or a $this->_out2('',TRUE); list($free_op1, $varname ) = $this->_get_zval_ptr("OP1",$d); /* determine where to look for variable */ //echo "GOT: :".$varname; switch ($d['OP2.u.fetch_type']) { case 1://ZEND_FETCH_LOCAL: $target_symbol_table = "EG(active_symbol_table)"; break; case 0://ZEND_FETCH_GLOBAL: /* acutal code does some locking? if (opline->op1.op_type == IS_VAR) { PZVAL_LOCK(varname); }*/ $target_symbol_table = "EG(symbol_table)"; break; case 2://ZEND_FETCH_STATIC: $this->_init_static_vars(); $target_symbol_table = "EG(active_op_array)->static_variables"; break; } /* if (varname->type != IS_STRING) { tmp_varname = *varname; zval_copy_ctor(&tmp_varname); convert_to_string(&tmp_varname); varname = &tmp_varname; } */ $varname_str = "{$varname}->value.str.val"; $varname_len = "{$varname}->value.str.len+1"; if ($varname{0} == '"') { $varname_str = $varname; $varname_len = strlen($varname) +1 ; } $this->_out2(" if (zend_hash_find($target_symbol_table, {$varname_str}, {$varname_len}, (void **) &execute_data.Ts[{$d['RESULT.u.var']}].var.ptr_ptr) == FAILURE) {",TRUE); switch($type) { case BP_VAR_R: /*zend_error(E_NOTICE,"Undefined variable: %s", varname->value.str.val); */ /* break missing intentionally */ case BP_VAR_IS: $this->_out2(" execute_data.Ts[{$d['RESULT.u.var']}].var.ptr_ptr = &EG(uninitialized_zval_ptr);",TRUE); break; case BP_VAR_RW: /*zend_error(E_NOTICE,"Undefined variable: %s", varname->value.str.val); */ /* break missing intentionally */ case BP_VAR_W: { $this->_out2(" zval *new_zval = &EG(uninitialized_zval);",TRUE); $this->_out2(" new_zval->refcount++;",TRUE); $this->_out2(" zend_hash_update({$target_symbol_table}, {$varname_str}, {$varname_len}, &new_zval, sizeof(zval *), (void **) &execute_data.Ts[{$d['RESULT.u.var']}].var.ptr_ptr);",TRUE); } break; } $this->_out2( " }",TRUE); if ($d["OP2.u.fetch_type"] == 1) { //ZEND_FETCH_LOCAL //$this->_out( "FREE_OP(Ts, &opline->op1, free_op1); "); } else if ($d["OP2.u.fetch_type"] == 2) { //ZEND_FETCH_STATIC $this->_out2(" zval_update_constant(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr_ptr, (void *) 1 TSRMLS_CC);"); } } function _make_opcode($op,$d) { /* This is the opcode structure!!! znode.op_type // it could be any one of these.... - union is a optional structure thing znode.u.constant //zval znode.u.var znode.u.opline_num znode.u.op_array; // op_array ??? znode.u.EA.var znode.u.EA.type zval.value // zvalue zval.type // uchar zval.is_ref zval.refcount // union! zvalue.lval zvalue.dval zvalue.str.val zvalue.str.len zvalue.ht zvalue.obj */ // make some space available! - do this at the beginning... $opu= strtolower($op); $this->_out2(" {$opu}.op_type = ".$d["{$op}.op_type"].";"); switch ($d["{$op}.op_type"]) { case 1: //ZEND_IS_CONST: $this->_out2(" {$opu}.u.constant = {$opu}_zv;"); $this->_out2(" {$opu}.u.constant.type = ".$d["{$op}.u.constant.type"].";"); $this->_out2(" {$opu}.u.constant.is_ref = ".$d["{$op}.u.constant.is_ref"].";"); $this->_out2(" {$opu}.u.constant.refcount = ".$d["{$op}.u.constant.refcount"].";"); $this->_out2(" {$opu}.u.constant.value = {$opu}_zvalue;"); switch ($d["{$op}.u.constant.type"]) { case 7://IS_RESOURCE: case 6://IS_BOOL: case 1://IS_LONG: $this->_out2(" {$opu}.u.constant.value.lval = ".$d["{$op}.u.constant.val"].";"); break; case 0://IS_NULL: $this->_out2(" {$opu}.u.constant.value.lval = 0;"); /* null value, do nothing - although just do this anyway*/ break; case 2://IS_DOUBLE: $this->_out2(" {$opu}.u.constant.value.dval = ".$d["{$op}.u.constant.val"].";"); break; case 8://IS_CONSTANT: case 3://IS_STRING: case 10://FLAG_IS_BC: $this->_out2(" {$opu}.u.constant.value.str.val = \"".$d["{$op}.u.constant.val"]."\";"); $this->_out2(" {$opu}.u.constant.value.str.len = ".strlen($d["{$op}.u.constant.val"]).";"); break; case 4://IS_ARRAY: case 9://IS_CONSTANT_ARRAY: case 5://IS_OBJECT: default: echo "UNHANDLED: op_type $op";exit; } break; case 2: //ZEND_IS_TMP_VAR: case 4: //ZEND_IS_VAR: $this->_out2(" {$opu}.u.var = ".$d["{$op}.u.var"].";"); break; default: print_r($d); echo "Unknown type $op ". $d[$opcode.".op_type"]; exit; } } function _assign_zval($name,$value) { switch(gettype($value)) { case "NULL"; $this->_out2(" {$name}.type = 0;"); $this->_out2(" {$name}.lval = 0;"); break; case "boolean"; $this->_out2(" {$name}.type = 6;"); $this->_out2(" {$name}.lval = $value;"); break; case "integer"; $this->_out2(" {$name}.type = 1;"); $this->_out2(" {$name}.lval = $value;"); break; case "double"; $this->_out2(" {$name}.type = 2;"); $this->_out2(" {$name}.dval = $value;"); break; case "string"; $this->_out2(" {$name}.type = 3;"); $this->_out2(" {$name}.val = \"$value\";"); $this->_out2(" {$name}.len = ". (strlen($value) +1) .";"); break; default: echo 'Unhandled zval type '. gettype($value) ." : $name : $value "; exit; } } function _do_fcall_common($d) { $this->_out2(" { zval **original_return_value; int return_value_used = (!({$d['RESULT.u.EA.type']} & EXT_TYPE_UNUSED)); zend_ptr_stack_n_push(&EG(argument_stack), 2, (void *) {$d['EXTENDED']}, NULL); execute_data.Ts[{$d['RESULT.u.var']}].var.ptr_ptr = &execute_data.Ts[{$d['RESULT.u.var']}].var.ptr; if (execute_data.function_state.function->type==ZEND_INTERNAL_FUNCTION) { ALLOC_ZVAL(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); INIT_ZVAL(*(execute_data.Ts[{$d['RESULT.u.var']}.var.ptr)); ((zend_internal_function *) execute_data.function_state.function->handler( {$d['EXTENDED']}, execute_data.Ts[{$d['RESULT.u.var']}].var.ptr, execute_data.object.ptr, return_value_used TSRMLS_CC); if (execute_data.object.ptr) { execute_data.object.ptr->refcount--; } execute_data.Ts[{$d['RESULT.u.var']}].var.ptr->is_ref = 0; execute_data.Ts[{$d['RESULT.u.var']}].var.ptr->refcount = 1; if (!return_value_used) { zval_ptr_dtor(&execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); } } else if (execute_data.function_state.function->type==ZEND_USER_FUNCTION) { /* this is probably not needed as it should never call internal user functions! */ HashTable *calling_symbol_table; execute_data.Ts[{$d['RESULT.u.var']}].var.ptr = NULL; if (EG(symtable_cache_ptr)>=EG(symtable_cache)) { execute_data.function_state.function_symbol_table = *(EG(symtable_cache_ptr)--); } else { ALLOC_HASHTABLE(execute_data.function_state.function_symbol_table); zend_hash_init(execute_data.function_state.function_symbol_table, 0, NULL, ZVAL_PTR_DTOR, 0); } calling_symbol_table = EG(active_symbol_table); EG(active_symbol_table) = execute_data.function_state.function_symbol_table; if ({$d['opcode']}==ZEND_DO_FCALL_BY_NAME && execute_data.object.ptr && execute_data.fbc->type!=ZEND_OVERLOADED_FUNCTION) { zval **this_ptr; zval *null_ptr = NULL; zend_hash_update(execute_data.function_state.function_symbol_table, \"this\", sizeof(\"this\"), &null_ptr, sizeof(zval *), (void **) &this_ptr); if (!PZVAL_IS_REF(execute_data.object.ptr)) { zend_error(E_WARNING, \"Problem with method call - please report this bug\"); } *this_ptr = execute_data.object.ptr; execute_data.object.ptr = NULL; } original_return_value = EG(return_value_ptr_ptr); EG(return_value_ptr_ptr) = execute_data.Ts[{$d['RESULT.u.var']}].var.ptr_ptr; EG(active_op_array) = (zend_op_array *) execute_data.function_state.function; zend_execute(EG(active_op_array) TSRMLS_CC); if (return_value_used && !execute_data.Ts[{$d['RESULT.u.var']}].var.ptr) { ALLOC_ZVAL(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); INIT_ZVAL(*execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); } else if (!return_value_used && execute_data.Ts[{$d['RESULT.u.var']}].var.ptr) { zval_ptr_dtor(&execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); } /*EG(opline_ptr) = &EX(opline); EG(active_op_array) = op_array; */ EG(return_value_ptr_ptr)=original_return_value; if (EG(symtable_cache_ptr)>=EG(symtable_cache_limit)) { zend_hash_destroy(execute_data.function_state.function_symbol_table); FREE_HASHTABLE(execute_data.function_state.function_symbol_table); } else { *(++EG(symtable_cache_ptr)) = execute_data.function_state.function_symbol_table; zend_hash_clean(*EG(symtable_cache_ptr)); } EG(active_symbol_table) = calling_symbol_table; } else { /* ZEND_OVERLOADED_FUNCTION */ ALLOC_ZVAL(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); INIT_ZVAL(*(execute_data.Ts[{$d['RESULT.u.var']}].var.ptr)); call_overloaded_function(&execute_data.Ts[execute_data.fbc->overloaded_function.var], {$d['EXTENDED']}, execute_data.Ts[{$d['RESULT.u.var']}].var.ptr TSRMLS_CC); efree(execute_data.fbc); if (!return_value_used) { zval_ptr_dtor(&execute_data.Ts[{$d['RESULT.u.var']}].var.ptr); } } if ({$d['opcode']} == ZEND_DO_FCALL_BY_NAME) { zend_ptr_stack_n_pop(&EG(arg_types_stack), 2, &execute_data.object.ptr, &execute_data.fbc); } else { execute_data.object.ptr = zend_ptr_stack_pop(&EG(arg_types_stack)); } execute_data.function_state.function = base_function; EG(function_state_ptr) = &execute_data.function_state; zend_ptr_stack_clear_multiple(TSRMLS_C); } } "); } } ?> Index: pear/PECL/bcompiler/examples/bcompiler_read.php +++ pear/PECL/bcompiler/examples/bcompiler_read.php <? if(!extension_loaded('bcompiler')) { dl('bcompiler.so'); } echo "\n\n\n"; //$fh = bzopen("/tmp/testcompile","r"); //bcompile_read($fh); //fclose($fh); //bcompile_load("/tmp/testcompile"); bcompile_load_exe("/tmp/testcompile2"); echo "GOT THIS FAR?\n"; print_r(get_class_methods("vending_dba")); print_r(get_declared_classes()); ?>DONE