shared_alloc_win32.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. +----------------------------------------------------------------------+
  3. | Zend OPcache |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1998-2018 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 "ZendAccelerator.h"
  22. #include "zend_shared_alloc.h"
  23. #include "zend_accelerator_util_funcs.h"
  24. #include "zend_execute.h"
  25. #include "SAPI.h"
  26. #include "tsrm_win32.h"
  27. #include <winbase.h>
  28. #include <process.h>
  29. #include <LMCONS.H>
  30. #define ACCEL_FILEMAP_NAME "ZendOPcache.SharedMemoryArea"
  31. #define ACCEL_MUTEX_NAME "ZendOPcache.SharedMemoryMutex"
  32. #define ACCEL_EVENT_SOURCE "Zend OPcache"
  33. /* address of mapping base and address of execute_ex */
  34. #define ACCEL_BASE_POINTER_SIZE (2 * sizeof(void*))
  35. static HANDLE memfile = NULL, memory_mutex = NULL;
  36. static void *mapping_base;
  37. #define MAX_MAP_RETRIES 25
  38. static void zend_win_error_message(int type, char *msg, int err)
  39. {
  40. LPVOID lpMsgBuf;
  41. HANDLE h;
  42. char *ev_msgs[2];
  43. FormatMessage(
  44. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  45. FORMAT_MESSAGE_FROM_SYSTEM |
  46. FORMAT_MESSAGE_IGNORE_INSERTS,
  47. NULL,
  48. err,
  49. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  50. (LPTSTR) &lpMsgBuf,
  51. 0,
  52. NULL
  53. );
  54. h = RegisterEventSource(NULL, TEXT(ACCEL_EVENT_SOURCE));
  55. ev_msgs[0] = msg;
  56. ev_msgs[1] = lpMsgBuf;
  57. ReportEvent(h, // event log handle
  58. EVENTLOG_ERROR_TYPE, // event type
  59. 0, // category zero
  60. err, // event identifier
  61. NULL, // no user security identifier
  62. 2, // one substitution string
  63. 0, // no data
  64. ev_msgs, // pointer to string array
  65. NULL); // pointer to data
  66. DeregisterEventSource(h);
  67. LocalFree( lpMsgBuf );
  68. zend_accel_error(type, "%s", msg);
  69. }
  70. static char *create_name_with_username(char *name)
  71. {
  72. static char newname[MAXPATHLEN + UNLEN + 4 + 1 + 32 + 21];
  73. char *uname;
  74. uname = php_win32_get_username();
  75. if (!uname) {
  76. return NULL;
  77. }
  78. snprintf(newname, sizeof(newname) - 1, "%s@%s@%.20s@%.32s", name, uname, sapi_module.name, ZCG(system_id));
  79. free(uname);
  80. return newname;
  81. }
  82. void zend_shared_alloc_create_lock(void)
  83. {
  84. memory_mutex = CreateMutex(NULL, FALSE, create_name_with_username(ACCEL_MUTEX_NAME));
  85. if (!memory_mutex) {
  86. zend_accel_error(ACCEL_LOG_FATAL, "Cannot create mutex");
  87. return;
  88. }
  89. ReleaseMutex(memory_mutex);
  90. }
  91. void zend_shared_alloc_lock_win32(void)
  92. {
  93. DWORD waitRes = WaitForSingleObject(memory_mutex, INFINITE);
  94. if (waitRes == WAIT_FAILED) {
  95. zend_accel_error(ACCEL_LOG_ERROR, "Cannot lock mutex");
  96. }
  97. }
  98. void zend_shared_alloc_unlock_win32(void)
  99. {
  100. ReleaseMutex(memory_mutex);
  101. }
  102. static int zend_shared_alloc_reattach(size_t requested_size, char **error_in)
  103. {
  104. int err;
  105. void *wanted_mapping_base;
  106. MEMORY_BASIC_INFORMATION info;
  107. void *execute_ex_base;
  108. int execute_ex_moved;
  109. mapping_base = MapViewOfFileEx(memfile, FILE_MAP_ALL_ACCESS, 0, 0, ACCEL_BASE_POINTER_SIZE, NULL);
  110. if (mapping_base == NULL) {
  111. err = GetLastError();
  112. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to read base address", err);
  113. *error_in="read mapping base";
  114. return ALLOC_FAILURE;
  115. }
  116. wanted_mapping_base = ((void**)mapping_base)[0];
  117. execute_ex_base = ((void**)mapping_base)[1];
  118. UnmapViewOfFile(mapping_base);
  119. execute_ex_moved = (void *)execute_ex != execute_ex_base;
  120. /* Check if execute_ex is at the same address and if the requested address space is free */
  121. if (execute_ex_moved ||
  122. VirtualQuery(wanted_mapping_base, &info, sizeof(info)) == 0 ||
  123. info.State != MEM_FREE ||
  124. info.RegionSize < requested_size) {
  125. #if ENABLE_FILE_CACHE_FALLBACK
  126. if (ZCG(accel_directives).file_cache && ZCG(accel_directives).file_cache_fallback) {
  127. size_t pre_size, wanted_mb_save;
  128. wanted_mb_save = (size_t)wanted_mapping_base;
  129. if (execute_ex_moved) {
  130. err = ERROR_INVALID_ADDRESS;
  131. zend_win_error_message(ACCEL_LOG_WARNING, "Opcode handlers are unusable due to ASLR (fall-back to file cache)", err);
  132. } else {
  133. err = ERROR_INVALID_ADDRESS;
  134. zend_win_error_message(ACCEL_LOG_WARNING, "Base address marks unusable memory region (fall-back to file cache)", err);
  135. }
  136. 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));
  137. /* Map only part of SHM to have access opcache shared globals */
  138. mapping_base = MapViewOfFileEx(memfile, FILE_MAP_ALL_ACCESS, 0, 0, pre_size + ZEND_ALIGNED_SIZE(sizeof(zend_accel_shared_globals)), NULL);
  139. if (mapping_base == NULL) {
  140. err = GetLastError();
  141. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to reattach to opcache shared globals", err);
  142. return ALLOC_FAILURE;
  143. }
  144. accel_shared_globals = (zend_accel_shared_globals *)((char *)((zend_smm_shared_globals *)mapping_base)->app_shared_globals + ((char *)mapping_base - (char *)wanted_mb_save));
  145. return ALLOC_FALLBACK;
  146. }
  147. #endif
  148. if (execute_ex_moved) {
  149. err = ERROR_INVALID_ADDRESS;
  150. 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);
  151. } else {
  152. err = ERROR_INVALID_ADDRESS;
  153. 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);
  154. }
  155. return ALLOC_FAILURE;
  156. }
  157. mapping_base = MapViewOfFileEx(memfile, FILE_MAP_ALL_ACCESS, 0, 0, 0, wanted_mapping_base);
  158. if (mapping_base == NULL) {
  159. err = GetLastError();
  160. if (err == ERROR_INVALID_ADDRESS) {
  161. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to reattach to base address", err);
  162. return ALLOC_FAILURE;
  163. }
  164. return ALLOC_FAIL_MAPPING;
  165. }
  166. smm_shared_globals = (zend_smm_shared_globals *) ((char*)mapping_base + ACCEL_BASE_POINTER_SIZE);
  167. return SUCCESSFULLY_REATTACHED;
  168. }
  169. static int create_segments(size_t requested_size, zend_shared_segment ***shared_segments_p, int *shared_segments_count, char **error_in)
  170. {
  171. int err = 0, ret;
  172. zend_shared_segment *shared_segment;
  173. int map_retries = 0;
  174. void *default_mapping_base_set[] = { 0, 0 };
  175. /* TODO:
  176. 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
  177. 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
  178. desired. Not done yet, @zend refused but did not remember the exact reason, pls add info here if one of you know why :)
  179. */
  180. #if defined(_WIN64)
  181. void *vista_mapping_base_set[] = { (void *) 0x0000100000000000, (void *) 0x0000200000000000, (void *) 0x0000300000000000, (void *) 0x0000700000000000, 0 };
  182. DWORD size_high = (requested_size >> 32), size_low = (requested_size & 0xffffffff);
  183. #else
  184. void *vista_mapping_base_set[] = { (void *) 0x20000000, (void *) 0x21000000, (void *) 0x30000000, (void *) 0x31000000, (void *) 0x50000000, 0 };
  185. DWORD size_high = 0, size_low = requested_size;
  186. #endif
  187. void **wanted_mapping_base = default_mapping_base_set;
  188. zend_shared_alloc_lock_win32();
  189. /* Mapping retries: When Apache2 restarts, the parent process startup routine
  190. can be called before the child process is killed. In this case, the map will fail
  191. and we have to sleep some time (until the child releases the mapping object) and retry.*/
  192. do {
  193. memfile = OpenFileMapping(FILE_MAP_WRITE, 0, create_name_with_username(ACCEL_FILEMAP_NAME));
  194. if (memfile == NULL) {
  195. err = GetLastError();
  196. break;
  197. }
  198. ret = zend_shared_alloc_reattach(requested_size, error_in);
  199. if (ret == ALLOC_FAIL_MAPPING) {
  200. err = GetLastError();
  201. /* Mapping failed, wait for mapping object to get freed and retry */
  202. CloseHandle(memfile);
  203. memfile = NULL;
  204. if (++map_retries >= MAX_MAP_RETRIES) {
  205. break;
  206. }
  207. zend_shared_alloc_unlock_win32();
  208. Sleep(1000 * (map_retries + 1));
  209. zend_shared_alloc_lock_win32();
  210. } else {
  211. zend_shared_alloc_unlock_win32();
  212. return ret;
  213. }
  214. } while (1);
  215. if (map_retries == MAX_MAP_RETRIES) {
  216. zend_shared_alloc_unlock_win32();
  217. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to open file mapping", err);
  218. *error_in = "OpenFileMapping";
  219. return ALLOC_FAILURE;
  220. }
  221. /* creating segment here */
  222. *shared_segments_count = 1;
  223. *shared_segments_p = (zend_shared_segment **) calloc(1, sizeof(zend_shared_segment)+sizeof(void *));
  224. if (!*shared_segments_p) {
  225. err = GetLastError();
  226. zend_shared_alloc_unlock_win32();
  227. zend_win_error_message(ACCEL_LOG_FATAL, "calloc() failed", err);
  228. *error_in = "calloc";
  229. return ALLOC_FAILURE;
  230. }
  231. shared_segment = (zend_shared_segment *)((char *)(*shared_segments_p) + sizeof(void *));
  232. (*shared_segments_p)[0] = shared_segment;
  233. memfile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, size_high, size_low,
  234. create_name_with_username(ACCEL_FILEMAP_NAME));
  235. if (memfile == NULL) {
  236. err = GetLastError();
  237. zend_shared_alloc_unlock_win32();
  238. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to create file mapping", err);
  239. *error_in = "CreateFileMapping";
  240. return ALLOC_FAILURE;
  241. }
  242. /* Starting from windows Vista, heap randomization occurs which might cause our mapping base to
  243. be taken (fail to map). So under Vista, we try to map into a hard coded predefined addresses
  244. in high memory. */
  245. if (!ZCG(accel_directives).mmap_base || !*ZCG(accel_directives).mmap_base) {
  246. wanted_mapping_base = vista_mapping_base_set;
  247. } else {
  248. char *s = ZCG(accel_directives).mmap_base;
  249. /* skip leading 0x, %p assumes hexdeciaml format anyway */
  250. if (*s == '0' && *(s + 1) == 'x') {
  251. s += 2;
  252. }
  253. if (sscanf(s, "%p", &default_mapping_base_set[0]) != 1) {
  254. zend_shared_alloc_unlock_win32();
  255. zend_win_error_message(ACCEL_LOG_FATAL, "Bad mapping address specified in opcache.mmap_base", err);
  256. return ALLOC_FAILURE;
  257. }
  258. }
  259. do {
  260. shared_segment->p = mapping_base = MapViewOfFileEx(memfile, FILE_MAP_ALL_ACCESS, 0, 0, 0, *wanted_mapping_base);
  261. if (*wanted_mapping_base == NULL) { /* Auto address (NULL) is the last option on the array */
  262. break;
  263. }
  264. wanted_mapping_base++;
  265. } while (!mapping_base);
  266. if (mapping_base == NULL) {
  267. err = GetLastError();
  268. zend_shared_alloc_unlock_win32();
  269. zend_win_error_message(ACCEL_LOG_FATAL, "Unable to create view for file mapping", err);
  270. *error_in = "MapViewOfFile";
  271. return ALLOC_FAILURE;
  272. } else {
  273. ((void**)mapping_base)[0] = mapping_base;
  274. ((void**)mapping_base)[1] = (void*)execute_ex;
  275. }
  276. shared_segment->pos = ACCEL_BASE_POINTER_SIZE;
  277. shared_segment->size = requested_size - ACCEL_BASE_POINTER_SIZE;
  278. zend_shared_alloc_unlock_win32();
  279. return ALLOC_SUCCESS;
  280. }
  281. static int detach_segment(zend_shared_segment *shared_segment)
  282. {
  283. zend_shared_alloc_lock_win32();
  284. if (mapping_base) {
  285. UnmapViewOfFile(mapping_base);
  286. mapping_base = NULL;
  287. }
  288. CloseHandle(memfile);
  289. memfile = NULL;
  290. zend_shared_alloc_unlock_win32();
  291. CloseHandle(memory_mutex);
  292. memory_mutex = NULL;
  293. return 0;
  294. }
  295. static size_t segment_type_size(void)
  296. {
  297. return sizeof(zend_shared_segment);
  298. }
  299. zend_shared_memory_handlers zend_alloc_win32_handlers = {
  300. create_segments,
  301. detach_segment,
  302. segment_type_size
  303. };