1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 #include "protobuf.h"
32 
33 #include <php.h>
34 #include <Zend/zend_interfaces.h>
35 
36 #include "arena.h"
37 #include "array.h"
38 #include "convert.h"
39 #include "def.h"
40 #include "map.h"
41 #include "message.h"
42 #include "names.h"
43 
44 // -----------------------------------------------------------------------------
45 // Module "globals"
46 // -----------------------------------------------------------------------------
47 
48 // Despite the name, module "globals" are really thread-locals:
49 //  * PROTOBUF_G(var) accesses the thread-local variable for 'var'. Either:
50 //    * PROTOBUF_G(var) -> protobuf_globals.var (Non-ZTS / non-thread-safe)
51 //    * PROTOBUF_G(var) -> <Zend magic>         (ZTS / thread-safe builds)
52 
53 #define PROTOBUF_G(v) ZEND_MODULE_GLOBALS_ACCESSOR(protobuf, v)
54 
55 ZEND_BEGIN_MODULE_GLOBALS(protobuf)
56   // Set by the user to make the descriptor pool persist between requests.
57   zend_bool keep_descriptor_pool_after_request;
58 
59   // Currently we make the generated pool a "global", which means that if a user
60   // does explicitly create threads within their request, the other threads will
61   // get different results from DescriptorPool::getGeneratedPool(). We require
62   // that all descriptors are loaded from the main thread.
63   zval generated_pool;
64 
65   // A upb_symtab that we are saving for the next request so that we don't have
66   // to rebuild it from scratch. When keep_descriptor_pool_after_request==true,
67   // we steal the upb_symtab from the global DescriptorPool object just before
68   // destroying it.
69   upb_symtab *global_symtab;
70 
71   // Object cache (see interface in protobuf.h).
72   HashTable object_cache;
73 
74   // Name cache (see interface in protobuf.h).
75   HashTable name_msg_cache;
76   HashTable name_enum_cache;
77 
78   // An array of descriptor objects constructed during this request. These are
79   // logically referenced by the corresponding class entry, but since we can't
80   // actually write a class entry destructor, we reference them here, to be
81   // destroyed on request shutdown.
82   HashTable descriptors;
ZEND_END_MODULE_GLOBALS(protobuf)83 ZEND_END_MODULE_GLOBALS(protobuf)
84 
85 void free_protobuf_globals(zend_protobuf_globals *globals) {
86   zend_hash_destroy(&globals->name_msg_cache);
87   zend_hash_destroy(&globals->name_enum_cache);
88   upb_symtab_free(globals->global_symtab);
89   globals->global_symtab = NULL;
90 }
91 
ZEND_DECLARE_MODULE_GLOBALS(protobuf)92 ZEND_DECLARE_MODULE_GLOBALS(protobuf)
93 
94 const zval *get_generated_pool() {
95   return &PROTOBUF_G(generated_pool);
96 }
97 
98 // This is a PHP extension (not a Zend extension). What follows is a summary of
99 // a PHP extension's lifetime and when various handlers are called.
100 //
101 //  * PHP_GINIT_FUNCTION(protobuf) / PHP_GSHUTDOWN_FUNCTION(protobuf)
102 //    are the constructor/destructor for the globals. The sequence over the
103 //    course of a process lifetime is:
104 //
105 //    # Process startup
106 //    GINIT(<Main Thread Globals>)
107 //    MINIT
108 //
109 //    foreach request:
110 //      RINIT
111 //        # Request is processed here.
112 //      RSHUTDOWN
113 //
114 //    foreach thread:
115 //      GINIT(<This Thread Globals>)
116 //        # Code for the thread runs here.
117 //      GSHUTDOWN(<This Thread Globals>)
118 //
119 //    # Process Shutdown
120 //    #
121 //    # These should be running per the docs, but I have not been able to
122 //    # actually get the process-wide shutdown functions to run.
123 //    #
124 //    # MSHUTDOWN
125 //    # GSHUTDOWN(<Main Thread Globals>)
126 //
127 //  * Threads can be created either explicitly by the user, inside a request,
128 //    or implicitly by the runtime, to process multiple requests concurrently.
129 //    If the latter is being used, then the "foreach thread" block above
130 //    actually looks like this:
131 //
132 //    foreach thread:
133 //      GINIT(<This Thread Globals>)
134 //      # A non-main thread will only receive requests when using a threaded
135 //      # MPM with Apache
136 //      foreach request:
137 //        RINIT
138 //          # Request is processed here.
139 //        RSHUTDOWN
140 //      GSHUTDOWN(<This Thread Globals>)
141 //
142 // That said, it appears that few people use threads with PHP:
143 //   * The pthread package documented at
144 //     https://www.php.net/manual/en/class.thread.php nas not been released
145 //     since 2016, and the current release fails to compile against any PHP
146 //     newer than 7.0.33.
147 //     * The GitHub master branch supports 7.2+, but this has not been released
148 //       to PECL.
149 //     * Its owner has disavowed it as "broken by design" and "in an untenable
150 //       position for the future": https://github.com/krakjoe/pthreads/issues/929
151 //   * The only way to use PHP with requests in different threads is to use the
152 //     Apache 2 mod_php with the "worker" MPM. But this is explicitly
153 //     discouraged by the documentation: https://serverfault.com/a/231660
154 
PHP_GSHUTDOWN_FUNCTION(protobuf)155 static PHP_GSHUTDOWN_FUNCTION(protobuf) {
156   if (protobuf_globals->global_symtab) {
157     free_protobuf_globals(protobuf_globals);
158   }
159 }
160 
PHP_GINIT_FUNCTION(protobuf)161 static PHP_GINIT_FUNCTION(protobuf) {
162   ZVAL_NULL(&protobuf_globals->generated_pool);
163   protobuf_globals->global_symtab = NULL;
164 }
165 
166 /**
167  * PHP_RINIT_FUNCTION(protobuf)
168  *
169  * This function is run at the beginning of processing each request.
170  */
PHP_RINIT_FUNCTION(protobuf)171 static PHP_RINIT_FUNCTION(protobuf) {
172   // Create the global generated pool.
173   // Reuse the symtab (if any) left to us by the last request.
174   upb_symtab *symtab = PROTOBUF_G(global_symtab);
175   if (!symtab) {
176     PROTOBUF_G(global_symtab) = symtab = upb_symtab_new();
177     zend_hash_init(&PROTOBUF_G(name_msg_cache), 64, NULL, NULL, 0);
178     zend_hash_init(&PROTOBUF_G(name_enum_cache), 64, NULL, NULL, 0);
179   }
180   DescriptorPool_CreateWithSymbolTable(&PROTOBUF_G(generated_pool), symtab);
181 
182   zend_hash_init(&PROTOBUF_G(object_cache), 64, NULL, NULL, 0);
183   zend_hash_init(&PROTOBUF_G(descriptors), 64, NULL, ZVAL_PTR_DTOR, 0);
184 
185   return SUCCESS;
186 }
187 
188 /**
189  * PHP_RSHUTDOWN_FUNCTION(protobuf)
190  *
191  * This function is run at the end of processing each request.
192  */
PHP_RSHUTDOWN_FUNCTION(protobuf)193 static PHP_RSHUTDOWN_FUNCTION(protobuf) {
194   // Preserve the symtab if requested.
195   if (!PROTOBUF_G(keep_descriptor_pool_after_request)) {
196     free_protobuf_globals(ZEND_MODULE_GLOBALS_BULK(protobuf));
197   }
198 
199   zval_dtor(&PROTOBUF_G(generated_pool));
200   zend_hash_destroy(&PROTOBUF_G(object_cache));
201   zend_hash_destroy(&PROTOBUF_G(descriptors));
202 
203   return SUCCESS;
204 }
205 
206 // -----------------------------------------------------------------------------
207 // Object Cache.
208 // -----------------------------------------------------------------------------
209 
Descriptors_Add(zend_object * desc)210 void Descriptors_Add(zend_object *desc) {
211   // The hash table will own a ref (it will destroy it when the table is
212   // destroyed), but for some reason the insert operation does not add a ref, so
213   // we do that here with ZVAL_OBJ_COPY().
214   zval zv;
215   ZVAL_OBJ_COPY(&zv, desc);
216   zend_hash_next_index_insert(&PROTOBUF_G(descriptors), &zv);
217 }
218 
ObjCache_Add(const void * upb_obj,zend_object * php_obj)219 void ObjCache_Add(const void *upb_obj, zend_object *php_obj) {
220   zend_ulong k = (zend_ulong)upb_obj;
221   zend_hash_index_add_ptr(&PROTOBUF_G(object_cache), k, php_obj);
222 }
223 
ObjCache_Delete(const void * upb_obj)224 void ObjCache_Delete(const void *upb_obj) {
225   if (upb_obj) {
226     zend_ulong k = (zend_ulong)upb_obj;
227     int ret = zend_hash_index_del(&PROTOBUF_G(object_cache), k);
228     PBPHP_ASSERT(ret == SUCCESS);
229   }
230 }
231 
ObjCache_Get(const void * upb_obj,zval * val)232 bool ObjCache_Get(const void *upb_obj, zval *val) {
233   zend_ulong k = (zend_ulong)upb_obj;
234   zend_object *obj = zend_hash_index_find_ptr(&PROTOBUF_G(object_cache), k);
235 
236   if (obj) {
237     ZVAL_OBJ_COPY(val, obj);
238     return true;
239   } else {
240     ZVAL_NULL(val);
241     return false;
242   }
243 }
244 
245 // -----------------------------------------------------------------------------
246 // Name Cache.
247 // -----------------------------------------------------------------------------
248 
NameMap_AddMessage(const upb_msgdef * m)249 void NameMap_AddMessage(const upb_msgdef *m) {
250   char *k = GetPhpClassname(upb_msgdef_file(m), upb_msgdef_fullname(m));
251   zend_hash_str_add_ptr(&PROTOBUF_G(name_msg_cache), k, strlen(k), (void*)m);
252   free(k);
253 }
254 
NameMap_AddEnum(const upb_enumdef * e)255 void NameMap_AddEnum(const upb_enumdef *e) {
256   char *k = GetPhpClassname(upb_enumdef_file(e), upb_enumdef_fullname(e));
257   zend_hash_str_add_ptr(&PROTOBUF_G(name_enum_cache), k, strlen(k), (void*)e);
258   free(k);
259 }
260 
NameMap_GetMessage(zend_class_entry * ce)261 const upb_msgdef *NameMap_GetMessage(zend_class_entry *ce) {
262   const upb_msgdef *ret =
263       zend_hash_find_ptr(&PROTOBUF_G(name_msg_cache), ce->name);
264 
265   if (!ret && ce->create_object) {
266 #if PHP_VERSION_ID < 80000
267     zval tmp;
268     zval zv;
269     ZVAL_OBJ(&tmp, ce->create_object(ce));
270     zend_call_method_with_0_params(&tmp, ce, NULL, "__construct", &zv);
271     zval_ptr_dtor(&tmp);
272 #else
273     zval zv;
274     zend_object *tmp = ce->create_object(ce);
275     zend_call_method_with_0_params(tmp, ce, NULL, "__construct", &zv);
276     OBJ_RELEASE(tmp);
277 #endif
278     zval_ptr_dtor(&zv);
279     ret = zend_hash_find_ptr(&PROTOBUF_G(name_msg_cache), ce->name);
280   }
281 
282   return ret;
283 }
284 
NameMap_GetEnum(zend_class_entry * ce)285 const upb_enumdef *NameMap_GetEnum(zend_class_entry *ce) {
286   const upb_enumdef *ret =
287       zend_hash_find_ptr(&PROTOBUF_G(name_enum_cache), ce->name);
288   return ret;
289 }
290 
291 // -----------------------------------------------------------------------------
292 // Module init.
293 // -----------------------------------------------------------------------------
294 
295 zend_function_entry protobuf_functions[] = {
296   ZEND_FE_END
297 };
298 
299 static const zend_module_dep protobuf_deps[] = {
300   ZEND_MOD_OPTIONAL("date")
301   ZEND_MOD_END
302 };
303 
304 PHP_INI_BEGIN()
305 STD_PHP_INI_ENTRY("protobuf.keep_descriptor_pool_after_request", "0",
306                   PHP_INI_ALL, OnUpdateBool,
307                   keep_descriptor_pool_after_request, zend_protobuf_globals,
308                   protobuf_globals)
PHP_INI_END()309 PHP_INI_END()
310 
311 static PHP_MINIT_FUNCTION(protobuf) {
312   REGISTER_INI_ENTRIES();
313   Arena_ModuleInit();
314   Array_ModuleInit();
315   Convert_ModuleInit();
316   Def_ModuleInit();
317   Map_ModuleInit();
318   Message_ModuleInit();
319   return SUCCESS;
320 }
321 
PHP_MSHUTDOWN_FUNCTION(protobuf)322 static PHP_MSHUTDOWN_FUNCTION(protobuf) {
323   UNREGISTER_INI_ENTRIES();
324   return SUCCESS;
325 }
326 
327 zend_module_entry protobuf_module_entry = {
328   STANDARD_MODULE_HEADER_EX,
329   NULL,
330   protobuf_deps,
331   "protobuf",               // extension name
332   protobuf_functions,       // function list
333   PHP_MINIT(protobuf),      // process startup
334   PHP_MSHUTDOWN(protobuf),  // process shutdown
335   PHP_RINIT(protobuf),      // request shutdown
336   PHP_RSHUTDOWN(protobuf),  // request shutdown
337   NULL,                     // extension info
338   PHP_PROTOBUF_VERSION,     // extension version
339   PHP_MODULE_GLOBALS(protobuf),  // globals descriptor
340   PHP_GINIT(protobuf),      // globals ctor
341   PHP_GSHUTDOWN(protobuf),  // globals dtor
342   NULL,                     // post deactivate
343   STANDARD_MODULE_PROPERTIES_EX
344 };
345 
346 ZEND_GET_MODULE(protobuf)
347