shared_alloc_win32.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /*
  2. +----------------------------------------------------------------------+
  3. | Zend OPcache |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | This source file is subject to version 3.01 of the PHP license, |
  8. | that is bundled with this package in the file LICENSE, and is |
  9. | available through the world-wide-web at the following url: |
  10. | https://www.php.net/license/3_01.txt |
  11. | If you did not receive a copy of the PHP license and are unable to |
  12. | obtain it through the world-wide-web, please send a note to |
  13. | license@php.net so we can mail you a copy immediately. |
  14. +----------------------------------------------------------------------+
  15. | Authors: Andi Gutmans <andi@php.net> |
  16. | Zeev Suraski <zeev@php.net> |
  17. | Stanislav Malyshev <stas@zend.com> |
  18. | Dmitry Stogov <dmitry@php.net> |
  19. +----------------------------------------------------------------------+
  20. */
  21. #include "php.h"
  22. #include "ZendAccelerator.h"
  23. #include "zend_shared_alloc.h"
  24. #include "zend_accelerator_util_funcs.h"
  25. #include "zend_execute.h"
  26. #include "zend_system_id.h"
  27. #include "SAPI.h"
  28. #include "tsrm_win32.h"
  29. #include "win32/winutil.h"
  30. #include <winbase.h>
  31. #include <process.h>
  32. #include <LMCONS.H>
  33. #define ACCEL_FILEMAP_NAME "ZendOPcache.SharedMemoryArea"
  34. #define ACCEL_MUTEX_NAME "ZendOPcache.SharedMemoryMutex"
  35. #define ACCEL_EVENT_SOURCE "Zend OPcache"
  36. /* address of mapping base and address of execute_ex */
  37. #define ACCEL_BASE_POINTER_SIZE (2 * sizeof(void*))
  38. static HANDLE memfile = NULL, memory_mutex = NULL;
  39. static void *mapping_base;
  40. #define MAX_MAP_RETRIES 25
  41. static void zend_win_error_message(int type, char *msg, int err)
  42. {
  43. HANDLE h;
  44. char *ev_msgs[2];
  45. char *buf = php_win32_error_to_msg(err);
  46. h = RegisterEventSource(NULL, TEXT(ACCEL_EVENT_SOURCE));
  47. ev_msgs[0] = msg;
  48. ev_msgs[1] = buf;
  49. ReportEvent(h, // event log handle
  50. EVENTLOG_ERROR_TYPE, // event type
  51. 0, // category zero
  52. err, // event identifier
  53. NULL, // no user security identifier
  54. 2, // one substitution string
  55. 0, // no data
  56. ev_msgs, // pointer to string array
  57. NULL); // pointer to data
  58. DeregisterEventSource(h);
  59. zend_accel_error(type, "%s", msg);
  60. php_win32_error_msg_free(buf);
  61. }
  62. static char *create_name_with_username(char *name)
  63. {
  64. static char newname[MAXPATHLEN + 1 + 32 + 1 + 20 + 1 + 32 + 1];
  65. char *p = newname;
  66. p += strlcpy(newname, name, MAXPATHLEN + 1);
  67. *(p++) = '@';
  68. memcpy(p, accel_uname_id, 32);
  69. p += 32;
  70. *(p++) = '@';
  71. p += strlcpy(p, sapi_module.name, 21);
  72. *(p++) = '@';
  73. memcpy(p, zend_system_id, 32);
  74. p += 32;
  75. *(p++) = '\0';
  76. ZEND_ASSERT(p - newname <= sizeof(newname));
  77. return newname;
  78. }
  79. void zend_shared_alloc_create_lock(void)
  80. {
  81. memory_mutex = CreateMutex(NULL, FALSE, create_name_with_username(ACCEL_MUTEX_NAME));
  82. if (!memory_mutex) {
  83. zend_accel_error(ACCEL_LOG_FATAL, "Cannot create mutex (error %u)", GetLastError());
  84. return;
  85. }
  86. ReleaseMutex(memory_mutex);
  87. }
  88. void zend_shared_alloc_lock_win32(void)
  89. {
  90. DWORD waitRes = WaitForSingleObject(memory_mutex, INFINITE);
  91. if (waitRes == WAIT_FAILED) {
  92. zend_accel_error(ACCEL_LOG_ERROR, "Cannot lock mutex");
  93. }
  94. }
  95. void zend_shared_alloc_unlock_win32(void)
  96. {
  97. ReleaseMutex(memory_mutex);
  98. }
  99. static int zend_shared_alloc_reattach(size_t requested_size, char **error_in)
  100. {
  101. int err;
  102. void *wanted_mapping_base;
  103. MEMORY_BASIC_INFORMATION info;
  104. void *execute_ex_base;
  105. int execute_ex_moved;
  106. mapping_base = MapViewOfFileEx(memfile, FILE_MAP_ALL_ACCESS, 0, 0, ACCEL_BASE_POINTER_SIZE, NULL);
  107. if (mapping_base == NULL) {
  108. err = GetLastError();
  109. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to read base address", err);
  110. *error_in="read mapping base";
  111. return ALLOC_FAILURE;
  112. }
  113. wanted_mapping_base = ((void**)mapping_base)[0];
  114. execute_ex_base = ((void**)mapping_base)[1];
  115. UnmapViewOfFile(mapping_base);
  116. execute_ex_moved = (void *)execute_ex != execute_ex_base;
  117. /* Check if execute_ex is at the same address and if the requested address space is free */
  118. if (execute_ex_moved ||
  119. VirtualQuery(wanted_mapping_base, &info, sizeof(info)) == 0 ||
  120. info.State != MEM_FREE ||
  121. info.RegionSize < requested_size) {
  122. #if ENABLE_FILE_CACHE_FALLBACK
  123. if (ZCG(accel_directives).file_cache && ZCG(accel_directives).file_cache_fallback) {
  124. size_t pre_size, wanted_mb_save;
  125. wanted_mb_save = (size_t)wanted_mapping_base;
  126. if (execute_ex_moved) {
  127. err = ERROR_INVALID_ADDRESS;
  128. zend_win_error_message(ACCEL_LOG_WARNING, "Opcode handlers are unusable due to ASLR (fall-back to file cache)", err);
  129. } else {
  130. err = ERROR_INVALID_ADDRESS;
  131. zend_win_error_message(ACCEL_LOG_WARNING, "Base address marks unusable memory region (fall-back to file cache)", err);
  132. }
  133. pre_size = ZEND_ALIGNED_SIZE(sizeof(zend_smm_shared_globals)) + ZEND_ALIGNED_SIZE(sizeof(zend_shared_segment)) + ZEND_ALIGNED_SIZE(sizeof(void *)) + ZEND_ALIGNED_SIZE(sizeof(int));
  134. /* Map only part of SHM to have access to opcache shared globals */
  135. mapping_base = MapViewOfFileEx(memfile, FILE_MAP_ALL_ACCESS, 0, 0, pre_size + ZEND_ALIGNED_SIZE(sizeof(zend_accel_shared_globals)), NULL);
  136. if (mapping_base == NULL) {
  137. err = GetLastError();
  138. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to reattach to opcache shared globals", err);
  139. return ALLOC_FAILURE;
  140. }
  141. accel_shared_globals = (zend_accel_shared_globals *)((char *)((zend_smm_shared_globals *)mapping_base)->app_shared_globals + ((char *)mapping_base - (char *)wanted_mb_save));
  142. return ALLOC_FALLBACK;
  143. }
  144. #endif
  145. if (execute_ex_moved) {
  146. err = ERROR_INVALID_ADDRESS;
  147. zend_win_error_message(ACCEL_LOG_FATAL, "Opcode handlers are unusable due to ASLR. Please setup opcache.file_cache and opcache.file_cache_fallback directives for more convenient Opcache usage", err);
  148. } else {
  149. err = ERROR_INVALID_ADDRESS;
  150. zend_win_error_message(ACCEL_LOG_FATAL, "Base address marks unusable memory region. Please setup opcache.file_cache and opcache.file_cache_fallback directives for more convenient Opcache usage", err);
  151. }
  152. return ALLOC_FAILURE;
  153. }
  154. mapping_base = MapViewOfFileEx(memfile, FILE_MAP_ALL_ACCESS|FILE_MAP_EXECUTE, 0, 0, 0, wanted_mapping_base);
  155. if (mapping_base == NULL) {
  156. err = GetLastError();
  157. if (err == ERROR_INVALID_ADDRESS) {
  158. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to reattach to base address", err);
  159. return ALLOC_FAILURE;
  160. }
  161. return ALLOC_FAIL_MAPPING;
  162. } else {
  163. DWORD old;
  164. if (!VirtualProtect(mapping_base, requested_size, PAGE_READWRITE, &old)) {
  165. err = GetLastError();
  166. zend_win_error_message(ACCEL_LOG_FATAL, "VirtualProtect() failed", err);
  167. return ALLOC_FAIL_MAPPING;
  168. }
  169. }
  170. smm_shared_globals = (zend_smm_shared_globals *) ((char*)mapping_base + ACCEL_BASE_POINTER_SIZE);
  171. return SUCCESSFULLY_REATTACHED;
  172. }
  173. static int create_segments(size_t requested_size, zend_shared_segment ***shared_segments_p, int *shared_segments_count, char **error_in)
  174. {
  175. int err = 0, ret;
  176. zend_shared_segment *shared_segment;
  177. int map_retries = 0;
  178. void *default_mapping_base_set[] = { 0, 0 };
  179. /* TODO:
  180. improve fixed addresses on x64. It still makes no sense to do it as Windows addresses are virtual per se and can or should be randomized anyway
  181. through Address Space Layout Radomization (ASLR). We can still let the OS do its job and be sure that each process gets the same address if
  182. desired. Not done yet, @zend refused but did not remember the exact reason, pls add info here if one of you know why :)
  183. */
  184. #if defined(_WIN64)
  185. void *vista_mapping_base_set[] = { (void *) 0x0000100000000000, (void *) 0x0000200000000000, (void *) 0x0000300000000000, (void *) 0x0000700000000000, 0 };
  186. DWORD size_high = (requested_size >> 32), size_low = (requested_size & 0xffffffff);
  187. #else
  188. void *vista_mapping_base_set[] = { (void *) 0x20000000, (void *) 0x21000000, (void *) 0x30000000, (void *) 0x31000000, (void *) 0x50000000, 0 };
  189. DWORD size_high = 0, size_low = requested_size;
  190. #endif
  191. void **wanted_mapping_base = default_mapping_base_set;
  192. zend_shared_alloc_lock_win32();
  193. /* Mapping retries: When Apache2 restarts, the parent process startup routine
  194. can be called before the child process is killed. In this case, the mapping will fail
  195. and we have to sleep some time (until the child releases the mapping object) and retry.*/
  196. do {
  197. memfile = OpenFileMapping(FILE_MAP_READ|FILE_MAP_WRITE|FILE_MAP_EXECUTE, 0, create_name_with_username(ACCEL_FILEMAP_NAME));
  198. if (memfile == NULL) {
  199. err = GetLastError();
  200. break;
  201. }
  202. ret = zend_shared_alloc_reattach(requested_size, error_in);
  203. if (ret == ALLOC_FAIL_MAPPING) {
  204. err = GetLastError();
  205. /* Mapping failed, wait for mapping object to get freed and retry */
  206. CloseHandle(memfile);
  207. memfile = NULL;
  208. if (++map_retries >= MAX_MAP_RETRIES) {
  209. break;
  210. }
  211. zend_shared_alloc_unlock_win32();
  212. Sleep(1000 * (map_retries + 1));
  213. zend_shared_alloc_lock_win32();
  214. } else {
  215. zend_shared_alloc_unlock_win32();
  216. return ret;
  217. }
  218. } while (1);
  219. if (map_retries == MAX_MAP_RETRIES) {
  220. zend_shared_alloc_unlock_win32();
  221. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to open file mapping", err);
  222. *error_in = "OpenFileMapping";
  223. return ALLOC_FAILURE;
  224. }
  225. /* creating segment here */
  226. *shared_segments_count = 1;
  227. *shared_segments_p = (zend_shared_segment **) calloc(1, sizeof(zend_shared_segment)+sizeof(void *));
  228. if (!*shared_segments_p) {
  229. err = GetLastError();
  230. zend_shared_alloc_unlock_win32();
  231. zend_win_error_message(ACCEL_LOG_FATAL, "calloc() failed", err);
  232. *error_in = "calloc";
  233. return ALLOC_FAILURE;
  234. }
  235. shared_segment = (zend_shared_segment *)((char *)(*shared_segments_p) + sizeof(void *));
  236. (*shared_segments_p)[0] = shared_segment;
  237. memfile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_EXECUTE_READWRITE | SEC_COMMIT, size_high, size_low,
  238. create_name_with_username(ACCEL_FILEMAP_NAME));
  239. if (memfile == NULL) {
  240. err = GetLastError();
  241. zend_shared_alloc_unlock_win32();
  242. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to create file mapping", err);
  243. *error_in = "CreateFileMapping";
  244. return ALLOC_FAILURE;
  245. }
  246. /* Starting from Windows Vista, heap randomization occurs which might cause our mapping base to
  247. be taken (fail to map). So we try to map into one of the hard coded predefined addresses
  248. in high memory. */
  249. if (!ZCG(accel_directives).mmap_base || !*ZCG(accel_directives).mmap_base) {
  250. wanted_mapping_base = vista_mapping_base_set;
  251. } else {
  252. char *s = ZCG(accel_directives).mmap_base;
  253. /* skip leading 0x, %p assumes hexdecimal format anyway */
  254. if (*s == '0' && *(s + 1) == 'x') {
  255. s += 2;
  256. }
  257. if (sscanf(s, "%p", &default_mapping_base_set[0]) != 1) {
  258. zend_shared_alloc_unlock_win32();
  259. zend_win_error_message(ACCEL_LOG_FATAL, "Bad mapping address specified in opcache.mmap_base", err);
  260. return ALLOC_FAILURE;
  261. }
  262. }
  263. do {
  264. shared_segment->p = mapping_base = MapViewOfFileEx(memfile, FILE_MAP_ALL_ACCESS|FILE_MAP_EXECUTE, 0, 0, 0, *wanted_mapping_base);
  265. if (*wanted_mapping_base == NULL) { /* Auto address (NULL) is the last option on the array */
  266. break;
  267. }
  268. wanted_mapping_base++;
  269. } while (!mapping_base);
  270. if (mapping_base == NULL) {
  271. err = GetLastError();
  272. zend_shared_alloc_unlock_win32();
  273. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to create view for file mapping", err);
  274. *error_in = "MapViewOfFile";
  275. return ALLOC_FAILURE;
  276. } else {
  277. DWORD old;
  278. if (!VirtualProtect(mapping_base, requested_size, PAGE_READWRITE, &old)) {
  279. err = GetLastError();
  280. zend_win_error_message(ACCEL_LOG_FATAL, "VirtualProtect() failed", err);
  281. return ALLOC_FAILURE;
  282. }
  283. ((void**)mapping_base)[0] = mapping_base;
  284. ((void**)mapping_base)[1] = (void*)execute_ex;
  285. }
  286. shared_segment->pos = ACCEL_BASE_POINTER_SIZE;
  287. shared_segment->size = requested_size - ACCEL_BASE_POINTER_SIZE;
  288. zend_shared_alloc_unlock_win32();
  289. return ALLOC_SUCCESS;
  290. }
  291. static int detach_segment(zend_shared_segment *shared_segment)
  292. {
  293. zend_shared_alloc_lock_win32();
  294. if (mapping_base) {
  295. UnmapViewOfFile(mapping_base);
  296. mapping_base = NULL;
  297. }
  298. CloseHandle(memfile);
  299. memfile = NULL;
  300. zend_shared_alloc_unlock_win32();
  301. CloseHandle(memory_mutex);
  302. memory_mutex = NULL;
  303. return 0;
  304. }
  305. static size_t segment_type_size(void)
  306. {
  307. return sizeof(zend_shared_segment);
  308. }
  309. zend_shared_memory_handlers zend_alloc_win32_handlers = {
  310. create_segments,
  311. detach_segment,
  312. segment_type_size
  313. };