PageRenderTime 33ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/ext/opcache/shared_alloc_win32.c

http://github.com/php/php-src
C | 393 lines | 308 code | 49 blank | 36 comment | 57 complexity | 4450774aed4e31806a3a74d69e768ba7 MD5 | raw file
Possible License(s): BSD-2-Clause, BSD-3-Clause, MPL-2.0-no-copyleft-exception, LGPL-2.1
  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. | http://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 "SAPI.h"
  27. #include "tsrm_win32.h"
  28. #include "win32/winutil.h"
  29. #include <winbase.h>
  30. #include <process.h>
  31. #include <LMCONS.H>
  32. #define ACCEL_FILEMAP_NAME "ZendOPcache.SharedMemoryArea"
  33. #define ACCEL_MUTEX_NAME "ZendOPcache.SharedMemoryMutex"
  34. #define ACCEL_FILEMAP_BASE_DEFAULT 0x01000000
  35. #define ACCEL_FILEMAP_BASE "ZendOPcache.MemoryBase"
  36. #define ACCEL_EVENT_SOURCE "Zend OPcache"
  37. static HANDLE memfile = NULL, memory_mutex = NULL;
  38. static void *mapping_base;
  39. #define MAX_MAP_RETRIES 25
  40. static void zend_win_error_message(int type, char *msg, int err)
  41. {
  42. HANDLE h;
  43. char *ev_msgs[2];
  44. char *buf = php_win32_error_to_msg(err);
  45. h = RegisterEventSource(NULL, TEXT(ACCEL_EVENT_SOURCE));
  46. ev_msgs[0] = msg;
  47. ev_msgs[1] = buf;
  48. ReportEvent(h, // event log handle
  49. EVENTLOG_ERROR_TYPE, // event type
  50. 0, // category zero
  51. err, // event identifier
  52. NULL, // no user security identifier
  53. 2, // one substitution string
  54. 0, // no data
  55. ev_msgs, // pointer to string array
  56. NULL); // pointer to data
  57. DeregisterEventSource(h);
  58. zend_accel_error(type, "%s", msg);
  59. php_win32_error_msg_free(buf);
  60. }
  61. static char *create_name_with_username(char *name)
  62. {
  63. static char newname[MAXPATHLEN + 32 + 4 + 1 + 32 + 21];
  64. snprintf(newname, sizeof(newname) - 1, "%s@%.32s@%.20s@%.32s", name, accel_uname_id, sapi_module.name, accel_system_id);
  65. return newname;
  66. }
  67. static char *get_mmap_base_file(void)
  68. {
  69. static char windir[MAXPATHLEN+ 32 + 3 + sizeof("\\\\@") + 1 + 32 + 21];
  70. int l;
  71. GetTempPath(MAXPATHLEN, windir);
  72. l = strlen(windir);
  73. if ('\\' == windir[l-1]) {
  74. l--;
  75. }
  76. snprintf(windir + l, sizeof(windir) - l - 1, "\\%s@%.32s@%.20s@%.32s", ACCEL_FILEMAP_BASE, accel_uname_id, sapi_module.name, accel_system_id);
  77. return windir;
  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");
  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. char *mmap_base_file = get_mmap_base_file();
  104. FILE *fp = fopen(mmap_base_file, "r");
  105. MEMORY_BASIC_INFORMATION info;
  106. void *execute_ex_base;
  107. int execute_ex_moved;
  108. if (!fp) {
  109. err = GetLastError();
  110. zend_win_error_message(ACCEL_LOG_WARNING, mmap_base_file, err);
  111. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to open base address file", err);
  112. *error_in="fopen";
  113. return ALLOC_FAILURE;
  114. }
  115. if (!fscanf(fp, "%p", &wanted_mapping_base)) {
  116. err = GetLastError();
  117. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to read base address", err);
  118. *error_in="read mapping base";
  119. fclose(fp);
  120. return ALLOC_FAILURE;
  121. }
  122. if (!fscanf(fp, "%p", &execute_ex_base)) {
  123. err = GetLastError();
  124. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to read execute_ex base address", err);
  125. *error_in="read execute_ex base";
  126. fclose(fp);
  127. return ALLOC_FAILURE;
  128. }
  129. fclose(fp);
  130. if (0 > win32_utime(mmap_base_file, NULL)) {
  131. err = GetLastError();
  132. zend_win_error_message(ACCEL_LOG_WARNING, mmap_base_file, err);
  133. }
  134. execute_ex_moved = (void *)execute_ex != execute_ex_base;
  135. /* Check if execute_ex is at the same address and if the requested address space is free */
  136. if (execute_ex_moved ||
  137. VirtualQuery(wanted_mapping_base, &info, sizeof(info)) == 0 ||
  138. info.State != MEM_FREE ||
  139. info.RegionSize < requested_size) {
  140. #if ENABLE_FILE_CACHE_FALLBACK
  141. if (ZCG(accel_directives).file_cache && ZCG(accel_directives).file_cache_fallback) {
  142. size_t pre_size, wanted_mb_save;
  143. wanted_mb_save = (size_t)wanted_mapping_base;
  144. if (execute_ex_moved) {
  145. err = ERROR_INVALID_ADDRESS;
  146. zend_win_error_message(ACCEL_LOG_WARNING, "Opcode handlers are unusable due to ASLR (fall-back to file cache)", err);
  147. } else {
  148. err = ERROR_INVALID_ADDRESS;
  149. zend_win_error_message(ACCEL_LOG_WARNING, "Base address marks unusable memory region (fall-back to file cache)", err);
  150. }
  151. 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));
  152. /* Map only part of SHM to have access opcache shared globals */
  153. mapping_base = MapViewOfFileEx(memfile, FILE_MAP_ALL_ACCESS, 0, 0, pre_size + ZEND_ALIGNED_SIZE(sizeof(zend_accel_shared_globals)), NULL);
  154. if (mapping_base == NULL) {
  155. err = GetLastError();
  156. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to reattach to opcache shared globals", err);
  157. return ALLOC_FAILURE;
  158. }
  159. accel_shared_globals = (zend_accel_shared_globals *)((char *)((zend_smm_shared_globals *)mapping_base)->app_shared_globals + ((char *)mapping_base - (char *)wanted_mb_save));
  160. return ALLOC_FALLBACK;
  161. }
  162. #endif
  163. if (execute_ex_moved) {
  164. err = ERROR_INVALID_ADDRESS;
  165. 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);
  166. } else {
  167. err = ERROR_INVALID_ADDRESS;
  168. 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);
  169. }
  170. return ALLOC_FAILURE;
  171. }
  172. mapping_base = MapViewOfFileEx(memfile, FILE_MAP_ALL_ACCESS|FILE_MAP_EXECUTE, 0, 0, 0, wanted_mapping_base);
  173. if (mapping_base == NULL) {
  174. err = GetLastError();
  175. if (err == ERROR_INVALID_ADDRESS) {
  176. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to reattach to base address", err);
  177. return ALLOC_FAILURE;
  178. }
  179. return ALLOC_FAIL_MAPPING;
  180. } else {
  181. DWORD old;
  182. if (!VirtualProtect(mapping_base, requested_size, PAGE_READWRITE, &old)) {
  183. err = GetLastError();
  184. zend_win_error_message(ACCEL_LOG_FATAL, "VirtualProtect() failed", err);
  185. return ALLOC_FAIL_MAPPING;
  186. }
  187. }
  188. smm_shared_globals = (zend_smm_shared_globals *) mapping_base;
  189. return SUCCESSFULLY_REATTACHED;
  190. }
  191. static int create_segments(size_t requested_size, zend_shared_segment ***shared_segments_p, int *shared_segments_count, char **error_in)
  192. {
  193. int err = 0, ret;
  194. zend_shared_segment *shared_segment;
  195. int map_retries = 0;
  196. void *default_mapping_base_set[] = { 0, 0 };
  197. /* TODO:
  198. 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
  199. 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
  200. desired. Not done yet, @zend refused but did not remember the exact reason, pls add info here if one of you know why :)
  201. */
  202. #if defined(_WIN64)
  203. void *vista_mapping_base_set[] = { (void *) 0x0000100000000000, (void *) 0x0000200000000000, (void *) 0x0000300000000000, (void *) 0x0000700000000000, 0 };
  204. DWORD size_high = (requested_size >> 32), size_low = (requested_size & 0xffffffff);
  205. #else
  206. void *vista_mapping_base_set[] = { (void *) 0x20000000, (void *) 0x21000000, (void *) 0x30000000, (void *) 0x31000000, (void *) 0x50000000, 0 };
  207. DWORD size_high = 0, size_low = requested_size;
  208. #endif
  209. void **wanted_mapping_base = default_mapping_base_set;
  210. zend_shared_alloc_lock_win32();
  211. /* Mapping retries: When Apache2 restarts, the parent process startup routine
  212. can be called before the child process is killed. In this case, the map will fail
  213. and we have to sleep some time (until the child releases the mapping object) and retry.*/
  214. do {
  215. memfile = OpenFileMapping(FILE_MAP_READ|FILE_MAP_WRITE|FILE_MAP_EXECUTE, 0, create_name_with_username(ACCEL_FILEMAP_NAME));
  216. if (memfile == NULL) {
  217. err = GetLastError();
  218. break;
  219. }
  220. ret = zend_shared_alloc_reattach(requested_size, error_in);
  221. if (ret == ALLOC_FAIL_MAPPING) {
  222. err = GetLastError();
  223. /* Mapping failed, wait for mapping object to get freed and retry */
  224. CloseHandle(memfile);
  225. memfile = NULL;
  226. if (++map_retries >= MAX_MAP_RETRIES) {
  227. break;
  228. }
  229. zend_shared_alloc_unlock_win32();
  230. Sleep(1000 * (map_retries + 1));
  231. zend_shared_alloc_lock_win32();
  232. } else {
  233. zend_shared_alloc_unlock_win32();
  234. return ret;
  235. }
  236. } while (1);
  237. if (map_retries == MAX_MAP_RETRIES) {
  238. zend_shared_alloc_unlock_win32();
  239. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to open file mapping", err);
  240. *error_in = "OpenFileMapping";
  241. return ALLOC_FAILURE;
  242. }
  243. /* creating segment here */
  244. *shared_segments_count = 1;
  245. *shared_segments_p = (zend_shared_segment **) calloc(1, sizeof(zend_shared_segment)+sizeof(void *));
  246. if (!*shared_segments_p) {
  247. err = GetLastError();
  248. zend_shared_alloc_unlock_win32();
  249. zend_win_error_message(ACCEL_LOG_FATAL, "calloc() failed", err);
  250. *error_in = "calloc";
  251. return ALLOC_FAILURE;
  252. }
  253. shared_segment = (zend_shared_segment *)((char *)(*shared_segments_p) + sizeof(void *));
  254. (*shared_segments_p)[0] = shared_segment;
  255. memfile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_EXECUTE_READWRITE | SEC_COMMIT, size_high, size_low,
  256. create_name_with_username(ACCEL_FILEMAP_NAME));
  257. if (memfile == NULL) {
  258. err = GetLastError();
  259. zend_shared_alloc_unlock_win32();
  260. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to create file mapping", err);
  261. *error_in = "CreateFileMapping";
  262. return ALLOC_FAILURE;
  263. }
  264. /* Starting from windows Vista, heap randomization occurs which might cause our mapping base to
  265. be taken (fail to map). So under Vista, we try to map into a hard coded predefined addresses
  266. in high memory. */
  267. if (!ZCG(accel_directives).mmap_base || !*ZCG(accel_directives).mmap_base) {
  268. wanted_mapping_base = vista_mapping_base_set;
  269. } else {
  270. char *s = ZCG(accel_directives).mmap_base;
  271. /* skip leading 0x, %p assumes hexdeciaml format anyway */
  272. if (*s == '0' && *(s + 1) == 'x') {
  273. s += 2;
  274. }
  275. if (sscanf(s, "%p", &default_mapping_base_set[0]) != 1) {
  276. zend_shared_alloc_unlock_win32();
  277. zend_win_error_message(ACCEL_LOG_FATAL, "Bad mapping address specified in opcache.mmap_base", err);
  278. return ALLOC_FAILURE;
  279. }
  280. }
  281. do {
  282. shared_segment->p = mapping_base = MapViewOfFileEx(memfile, FILE_MAP_ALL_ACCESS|FILE_MAP_EXECUTE, 0, 0, 0, *wanted_mapping_base);
  283. if (*wanted_mapping_base == NULL) { /* Auto address (NULL) is the last option on the array */
  284. break;
  285. }
  286. wanted_mapping_base++;
  287. } while (!mapping_base);
  288. if (mapping_base == NULL) {
  289. err = GetLastError();
  290. zend_shared_alloc_unlock_win32();
  291. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to create view for file mapping", err);
  292. *error_in = "MapViewOfFile";
  293. return ALLOC_FAILURE;
  294. } else {
  295. char *mmap_base_file;
  296. void *execute_ex_base = (void *)execute_ex;
  297. FILE *fp;
  298. DWORD old;
  299. if (!VirtualProtect(mapping_base, requested_size, PAGE_READWRITE, &old)) {
  300. err = GetLastError();
  301. zend_win_error_message(ACCEL_LOG_FATAL, "VirtualProtect() failed", err);
  302. return ALLOC_FAILURE;
  303. }
  304. mmap_base_file = get_mmap_base_file();
  305. fp = fopen(mmap_base_file, "w");
  306. if (!fp) {
  307. err = GetLastError();
  308. zend_shared_alloc_unlock_win32();
  309. zend_win_error_message(ACCEL_LOG_WARNING, mmap_base_file, err);
  310. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to write base address", err);
  311. return ALLOC_FAILURE;
  312. }
  313. fprintf(fp, "%p\n", mapping_base);
  314. fprintf(fp, "%p\n", execute_ex_base);
  315. fclose(fp);
  316. }
  317. shared_segment->pos = 0;
  318. shared_segment->size = requested_size;
  319. zend_shared_alloc_unlock_win32();
  320. return ALLOC_SUCCESS;
  321. }
  322. static int detach_segment(zend_shared_segment *shared_segment)
  323. {
  324. zend_shared_alloc_lock_win32();
  325. if (mapping_base) {
  326. UnmapViewOfFile(mapping_base);
  327. mapping_base = NULL;
  328. }
  329. CloseHandle(memfile);
  330. memfile = NULL;
  331. zend_shared_alloc_unlock_win32();
  332. CloseHandle(memory_mutex);
  333. memory_mutex = NULL;
  334. return 0;
  335. }
  336. static size_t segment_type_size(void)
  337. {
  338. return sizeof(zend_shared_segment);
  339. }
  340. zend_shared_memory_handlers zend_alloc_win32_handlers = {
  341. create_segments,
  342. detach_segment,
  343. segment_type_size
  344. };