mmapmodule.c 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763
  1. /*
  2. / Author: Sam Rushing <rushing@nightmare.com>
  3. / Hacked for Unix by AMK
  4. / $Id$
  5. / Modified to support mmap with offset - to map a 'window' of a file
  6. / Author: Yotam Medini yotamm@mellanox.co.il
  7. /
  8. / mmapmodule.cpp -- map a view of a file into memory
  9. /
  10. / todo: need permission flags, perhaps a 'chsize' analog
  11. / not all functions check range yet!!!
  12. /
  13. /
  14. / This version of mmapmodule.c has been changed significantly
  15. / from the original mmapfile.c on which it was based.
  16. / The original version of mmapfile is maintained by Sam at
  17. / ftp://squirl.nightmare.com/pub/python/python-ext.
  18. */
  19. #ifndef Py_BUILD_CORE_BUILTIN
  20. # define Py_BUILD_CORE_MODULE 1
  21. #endif
  22. #define PY_SSIZE_T_CLEAN
  23. #include <Python.h>
  24. #include "pycore_bytesobject.h" // _PyBytes_Find()
  25. #include "pycore_fileutils.h" // _Py_stat_struct
  26. #include "structmember.h" // PyMemberDef
  27. #include <stddef.h> // offsetof()
  28. #ifndef MS_WINDOWS
  29. #define UNIX
  30. # ifdef HAVE_FCNTL_H
  31. # include <fcntl.h>
  32. # endif /* HAVE_FCNTL_H */
  33. #endif
  34. #ifdef MS_WINDOWS
  35. #include <windows.h>
  36. static int
  37. my_getpagesize(void)
  38. {
  39. SYSTEM_INFO si;
  40. GetSystemInfo(&si);
  41. return si.dwPageSize;
  42. }
  43. static int
  44. my_getallocationgranularity (void)
  45. {
  46. SYSTEM_INFO si;
  47. GetSystemInfo(&si);
  48. return si.dwAllocationGranularity;
  49. }
  50. #endif
  51. #ifdef UNIX
  52. #include <sys/mman.h>
  53. #include <sys/stat.h>
  54. #if defined(HAVE_SYSCONF) && defined(_SC_PAGESIZE)
  55. static int
  56. my_getpagesize(void)
  57. {
  58. return sysconf(_SC_PAGESIZE);
  59. }
  60. #define my_getallocationgranularity my_getpagesize
  61. #else
  62. #define my_getpagesize getpagesize
  63. #endif
  64. #endif /* UNIX */
  65. #include <string.h>
  66. #ifdef HAVE_SYS_TYPES_H
  67. #include <sys/types.h>
  68. #endif /* HAVE_SYS_TYPES_H */
  69. /* Prefer MAP_ANONYMOUS since MAP_ANON is deprecated according to man page. */
  70. #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
  71. # define MAP_ANONYMOUS MAP_ANON
  72. #endif
  73. typedef enum
  74. {
  75. ACCESS_DEFAULT,
  76. ACCESS_READ,
  77. ACCESS_WRITE,
  78. ACCESS_COPY
  79. } access_mode;
  80. typedef struct {
  81. PyObject_HEAD
  82. char * data;
  83. Py_ssize_t size;
  84. Py_ssize_t pos; /* relative to offset */
  85. #ifdef MS_WINDOWS
  86. long long offset;
  87. #else
  88. off_t offset;
  89. #endif
  90. Py_ssize_t exports;
  91. #ifdef MS_WINDOWS
  92. HANDLE map_handle;
  93. HANDLE file_handle;
  94. wchar_t * tagname;
  95. #endif
  96. #ifdef UNIX
  97. int fd;
  98. #endif
  99. PyObject *weakreflist;
  100. access_mode access;
  101. } mmap_object;
  102. static int
  103. mmap_object_traverse(mmap_object *m_obj, visitproc visit, void *arg)
  104. {
  105. Py_VISIT(Py_TYPE(m_obj));
  106. return 0;
  107. }
  108. static void
  109. mmap_object_dealloc(mmap_object *m_obj)
  110. {
  111. PyTypeObject *tp = Py_TYPE(m_obj);
  112. PyObject_GC_UnTrack(m_obj);
  113. #ifdef MS_WINDOWS
  114. Py_BEGIN_ALLOW_THREADS
  115. if (m_obj->data != NULL)
  116. UnmapViewOfFile (m_obj->data);
  117. if (m_obj->map_handle != NULL)
  118. CloseHandle (m_obj->map_handle);
  119. if (m_obj->file_handle != INVALID_HANDLE_VALUE)
  120. CloseHandle (m_obj->file_handle);
  121. Py_END_ALLOW_THREADS
  122. if (m_obj->tagname)
  123. PyMem_Free(m_obj->tagname);
  124. #endif /* MS_WINDOWS */
  125. #ifdef UNIX
  126. Py_BEGIN_ALLOW_THREADS
  127. if (m_obj->fd >= 0)
  128. (void) close(m_obj->fd);
  129. if (m_obj->data!=NULL) {
  130. munmap(m_obj->data, m_obj->size);
  131. }
  132. Py_END_ALLOW_THREADS
  133. #endif /* UNIX */
  134. if (m_obj->weakreflist != NULL)
  135. PyObject_ClearWeakRefs((PyObject *) m_obj);
  136. tp->tp_free(m_obj);
  137. Py_DECREF(tp);
  138. }
  139. static PyObject *
  140. mmap_close_method(mmap_object *self, PyObject *unused)
  141. {
  142. if (self->exports > 0) {
  143. PyErr_SetString(PyExc_BufferError, "cannot close "\
  144. "exported pointers exist");
  145. return NULL;
  146. }
  147. #ifdef MS_WINDOWS
  148. /* For each resource we maintain, we need to check
  149. the value is valid, and if so, free the resource
  150. and set the member value to an invalid value so
  151. the dealloc does not attempt to resource clearing
  152. again.
  153. TODO - should we check for errors in the close operations???
  154. */
  155. HANDLE map_handle = self->map_handle;
  156. HANDLE file_handle = self->file_handle;
  157. char *data = self->data;
  158. self->map_handle = NULL;
  159. self->file_handle = INVALID_HANDLE_VALUE;
  160. self->data = NULL;
  161. Py_BEGIN_ALLOW_THREADS
  162. if (data != NULL) {
  163. UnmapViewOfFile(data);
  164. }
  165. if (map_handle != NULL) {
  166. CloseHandle(map_handle);
  167. }
  168. if (file_handle != INVALID_HANDLE_VALUE) {
  169. CloseHandle(file_handle);
  170. }
  171. Py_END_ALLOW_THREADS
  172. #endif /* MS_WINDOWS */
  173. #ifdef UNIX
  174. int fd = self->fd;
  175. char *data = self->data;
  176. self->fd = -1;
  177. self->data = NULL;
  178. Py_BEGIN_ALLOW_THREADS
  179. if (0 <= fd)
  180. (void) close(fd);
  181. if (data != NULL) {
  182. munmap(data, self->size);
  183. }
  184. Py_END_ALLOW_THREADS
  185. #endif
  186. Py_RETURN_NONE;
  187. }
  188. #ifdef MS_WINDOWS
  189. #define CHECK_VALID(err) \
  190. do { \
  191. if (self->map_handle == NULL) { \
  192. PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \
  193. return err; \
  194. } \
  195. } while (0)
  196. #define CHECK_VALID_OR_RELEASE(err, buffer) \
  197. do { \
  198. if (self->map_handle == NULL) { \
  199. PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \
  200. PyBuffer_Release(&(buffer)); \
  201. return (err); \
  202. } \
  203. } while (0)
  204. #endif /* MS_WINDOWS */
  205. #ifdef UNIX
  206. #define CHECK_VALID(err) \
  207. do { \
  208. if (self->data == NULL) { \
  209. PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \
  210. return err; \
  211. } \
  212. } while (0)
  213. #define CHECK_VALID_OR_RELEASE(err, buffer) \
  214. do { \
  215. if (self->data == NULL) { \
  216. PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \
  217. PyBuffer_Release(&(buffer)); \
  218. return (err); \
  219. } \
  220. } while (0)
  221. #endif /* UNIX */
  222. static PyObject *
  223. mmap_read_byte_method(mmap_object *self,
  224. PyObject *unused)
  225. {
  226. CHECK_VALID(NULL);
  227. if (self->pos >= self->size) {
  228. PyErr_SetString(PyExc_ValueError, "read byte out of range");
  229. return NULL;
  230. }
  231. return PyLong_FromLong((unsigned char)self->data[self->pos++]);
  232. }
  233. static PyObject *
  234. mmap_read_line_method(mmap_object *self,
  235. PyObject *unused)
  236. {
  237. Py_ssize_t remaining;
  238. char *start, *eol;
  239. PyObject *result;
  240. CHECK_VALID(NULL);
  241. remaining = (self->pos < self->size) ? self->size - self->pos : 0;
  242. if (!remaining)
  243. return PyBytes_FromString("");
  244. start = self->data + self->pos;
  245. eol = memchr(start, '\n', remaining);
  246. if (!eol)
  247. eol = self->data + self->size;
  248. else
  249. ++eol; /* advance past newline */
  250. result = PyBytes_FromStringAndSize(start, (eol - start));
  251. self->pos += (eol - start);
  252. return result;
  253. }
  254. static PyObject *
  255. mmap_read_method(mmap_object *self,
  256. PyObject *args)
  257. {
  258. Py_ssize_t num_bytes = PY_SSIZE_T_MAX, remaining;
  259. PyObject *result;
  260. CHECK_VALID(NULL);
  261. if (!PyArg_ParseTuple(args, "|O&:read", _Py_convert_optional_to_ssize_t, &num_bytes))
  262. return NULL;
  263. CHECK_VALID(NULL);
  264. /* silently 'adjust' out-of-range requests */
  265. remaining = (self->pos < self->size) ? self->size - self->pos : 0;
  266. if (num_bytes < 0 || num_bytes > remaining)
  267. num_bytes = remaining;
  268. result = PyBytes_FromStringAndSize(&self->data[self->pos], num_bytes);
  269. self->pos += num_bytes;
  270. return result;
  271. }
  272. static PyObject *
  273. mmap_gfind(mmap_object *self,
  274. PyObject *args,
  275. int reverse)
  276. {
  277. Py_ssize_t start = self->pos;
  278. Py_ssize_t end = self->size;
  279. Py_buffer view;
  280. CHECK_VALID(NULL);
  281. if (!PyArg_ParseTuple(args, reverse ? "y*|nn:rfind" : "y*|nn:find",
  282. &view, &start, &end)) {
  283. return NULL;
  284. }
  285. else {
  286. if (start < 0)
  287. start += self->size;
  288. if (start < 0)
  289. start = 0;
  290. else if (start > self->size)
  291. start = self->size;
  292. if (end < 0)
  293. end += self->size;
  294. if (end < 0)
  295. end = 0;
  296. else if (end > self->size)
  297. end = self->size;
  298. Py_ssize_t res;
  299. CHECK_VALID_OR_RELEASE(NULL, view);
  300. if (end < start) {
  301. res = -1;
  302. }
  303. else if (reverse) {
  304. assert(0 <= start && start <= end && end <= self->size);
  305. res = _PyBytes_ReverseFind(
  306. self->data + start, end - start,
  307. view.buf, view.len, start);
  308. }
  309. else {
  310. assert(0 <= start && start <= end && end <= self->size);
  311. res = _PyBytes_Find(
  312. self->data + start, end - start,
  313. view.buf, view.len, start);
  314. }
  315. PyBuffer_Release(&view);
  316. return PyLong_FromSsize_t(res);
  317. }
  318. }
  319. static PyObject *
  320. mmap_find_method(mmap_object *self,
  321. PyObject *args)
  322. {
  323. return mmap_gfind(self, args, 0);
  324. }
  325. static PyObject *
  326. mmap_rfind_method(mmap_object *self,
  327. PyObject *args)
  328. {
  329. return mmap_gfind(self, args, 1);
  330. }
  331. static int
  332. is_writable(mmap_object *self)
  333. {
  334. if (self->access != ACCESS_READ)
  335. return 1;
  336. PyErr_Format(PyExc_TypeError, "mmap can't modify a readonly memory map.");
  337. return 0;
  338. }
  339. static int
  340. is_resizeable(mmap_object *self)
  341. {
  342. if (self->exports > 0) {
  343. PyErr_SetString(PyExc_BufferError,
  344. "mmap can't resize with extant buffers exported.");
  345. return 0;
  346. }
  347. if ((self->access == ACCESS_WRITE) || (self->access == ACCESS_DEFAULT))
  348. return 1;
  349. PyErr_Format(PyExc_TypeError,
  350. "mmap can't resize a readonly or copy-on-write memory map.");
  351. return 0;
  352. }
  353. static PyObject *
  354. mmap_write_method(mmap_object *self,
  355. PyObject *args)
  356. {
  357. Py_buffer data;
  358. CHECK_VALID(NULL);
  359. if (!PyArg_ParseTuple(args, "y*:write", &data))
  360. return NULL;
  361. if (!is_writable(self)) {
  362. PyBuffer_Release(&data);
  363. return NULL;
  364. }
  365. if (self->pos > self->size || self->size - self->pos < data.len) {
  366. PyBuffer_Release(&data);
  367. PyErr_SetString(PyExc_ValueError, "data out of range");
  368. return NULL;
  369. }
  370. CHECK_VALID_OR_RELEASE(NULL, data);
  371. memcpy(&self->data[self->pos], data.buf, data.len);
  372. self->pos += data.len;
  373. PyBuffer_Release(&data);
  374. return PyLong_FromSsize_t(data.len);
  375. }
  376. static PyObject *
  377. mmap_write_byte_method(mmap_object *self,
  378. PyObject *args)
  379. {
  380. char value;
  381. CHECK_VALID(NULL);
  382. if (!PyArg_ParseTuple(args, "b:write_byte", &value))
  383. return(NULL);
  384. if (!is_writable(self))
  385. return NULL;
  386. CHECK_VALID(NULL);
  387. if (self->pos < self->size) {
  388. self->data[self->pos++] = value;
  389. Py_RETURN_NONE;
  390. }
  391. else {
  392. PyErr_SetString(PyExc_ValueError, "write byte out of range");
  393. return NULL;
  394. }
  395. }
  396. static PyObject *
  397. mmap_size_method(mmap_object *self,
  398. PyObject *unused)
  399. {
  400. CHECK_VALID(NULL);
  401. #ifdef MS_WINDOWS
  402. if (self->file_handle != INVALID_HANDLE_VALUE) {
  403. DWORD low,high;
  404. long long size;
  405. low = GetFileSize(self->file_handle, &high);
  406. if (low == INVALID_FILE_SIZE) {
  407. /* It might be that the function appears to have failed,
  408. when indeed its size equals INVALID_FILE_SIZE */
  409. DWORD error = GetLastError();
  410. if (error != NO_ERROR)
  411. return PyErr_SetFromWindowsErr(error);
  412. }
  413. if (!high && low < LONG_MAX)
  414. return PyLong_FromLong((long)low);
  415. size = (((long long)high)<<32) + low;
  416. return PyLong_FromLongLong(size);
  417. } else {
  418. return PyLong_FromSsize_t(self->size);
  419. }
  420. #endif /* MS_WINDOWS */
  421. #ifdef UNIX
  422. {
  423. struct _Py_stat_struct status;
  424. if (_Py_fstat(self->fd, &status) == -1)
  425. return NULL;
  426. #ifdef HAVE_LARGEFILE_SUPPORT
  427. return PyLong_FromLongLong(status.st_size);
  428. #else
  429. return PyLong_FromLong(status.st_size);
  430. #endif
  431. }
  432. #endif /* UNIX */
  433. }
  434. /* This assumes that you want the entire file mapped,
  435. / and when recreating the map will make the new file
  436. / have the new size
  437. /
  438. / Is this really necessary? This could easily be done
  439. / from python by just closing and re-opening with the
  440. / new size?
  441. */
  442. static PyObject *
  443. mmap_resize_method(mmap_object *self,
  444. PyObject *args)
  445. {
  446. Py_ssize_t new_size;
  447. CHECK_VALID(NULL);
  448. if (!PyArg_ParseTuple(args, "n:resize", &new_size) ||
  449. !is_resizeable(self)) {
  450. return NULL;
  451. }
  452. if (new_size < 0 || PY_SSIZE_T_MAX - new_size < self->offset) {
  453. PyErr_SetString(PyExc_ValueError, "new size out of range");
  454. return NULL;
  455. }
  456. {
  457. #ifdef MS_WINDOWS
  458. DWORD error = 0, file_resize_error = 0;
  459. char* old_data = self->data;
  460. LARGE_INTEGER offset, max_size;
  461. offset.QuadPart = self->offset;
  462. max_size.QuadPart = self->offset + new_size;
  463. /* close the file mapping */
  464. CloseHandle(self->map_handle);
  465. /* if the file mapping still exists, it cannot be resized. */
  466. if (self->tagname) {
  467. self->map_handle = OpenFileMappingW(FILE_MAP_WRITE, FALSE,
  468. self->tagname);
  469. if (self->map_handle) {
  470. PyErr_SetFromWindowsErr(ERROR_USER_MAPPED_FILE);
  471. return NULL;
  472. }
  473. } else {
  474. self->map_handle = NULL;
  475. }
  476. /* if it's not the paging file, unmap the view and resize the file */
  477. if (self->file_handle != INVALID_HANDLE_VALUE) {
  478. if (!UnmapViewOfFile(self->data)) {
  479. return PyErr_SetFromWindowsErr(GetLastError());
  480. };
  481. self->data = NULL;
  482. /* resize the file */
  483. if (!SetFilePointerEx(self->file_handle, max_size, NULL,
  484. FILE_BEGIN) ||
  485. !SetEndOfFile(self->file_handle)) {
  486. /* resizing failed. try to remap the file */
  487. file_resize_error = GetLastError();
  488. max_size.QuadPart = self->size;
  489. new_size = self->size;
  490. }
  491. }
  492. /* create a new file mapping and map a new view */
  493. /* FIXME: call CreateFileMappingW with wchar_t tagname */
  494. self->map_handle = CreateFileMappingW(
  495. self->file_handle,
  496. NULL,
  497. PAGE_READWRITE,
  498. max_size.HighPart,
  499. max_size.LowPart,
  500. self->tagname);
  501. error = GetLastError();
  502. /* ERROR_ALREADY_EXISTS implies that between our closing the handle above and
  503. calling CreateFileMapping here, someone's created a different mapping with
  504. the same name. There's nothing we can usefully do so we invalidate our
  505. mapping and error out.
  506. */
  507. if (error == ERROR_ALREADY_EXISTS) {
  508. CloseHandle(self->map_handle);
  509. self->map_handle = NULL;
  510. }
  511. else if (self->map_handle != NULL) {
  512. self->data = MapViewOfFile(self->map_handle,
  513. FILE_MAP_WRITE,
  514. offset.HighPart,
  515. offset.LowPart,
  516. new_size);
  517. if (self->data != NULL) {
  518. /* copy the old view if using the paging file */
  519. if (self->file_handle == INVALID_HANDLE_VALUE) {
  520. memcpy(self->data, old_data,
  521. self->size < new_size ? self->size : new_size);
  522. if (!UnmapViewOfFile(old_data)) {
  523. error = GetLastError();
  524. }
  525. }
  526. self->size = new_size;
  527. }
  528. else {
  529. error = GetLastError();
  530. CloseHandle(self->map_handle);
  531. self->map_handle = NULL;
  532. }
  533. }
  534. if (error) {
  535. return PyErr_SetFromWindowsErr(error);
  536. return NULL;
  537. }
  538. /* It's possible for a resize to fail, typically because another mapping
  539. is still held against the same underlying file. Even if nothing has
  540. failed -- ie we're still returning a valid file mapping -- raise the
  541. error as an exception as the resize won't have happened
  542. */
  543. if (file_resize_error) {
  544. PyErr_SetFromWindowsErr(file_resize_error);
  545. return NULL;
  546. }
  547. Py_RETURN_NONE;
  548. #endif /* MS_WINDOWS */
  549. #ifdef UNIX
  550. #ifndef HAVE_MREMAP
  551. PyErr_SetString(PyExc_SystemError,
  552. "mmap: resizing not available--no mremap()");
  553. return NULL;
  554. #else
  555. void *newmap;
  556. if (self->fd != -1 && ftruncate(self->fd, self->offset + new_size) == -1) {
  557. PyErr_SetFromErrno(PyExc_OSError);
  558. return NULL;
  559. }
  560. #ifdef MREMAP_MAYMOVE
  561. newmap = mremap(self->data, self->size, new_size, MREMAP_MAYMOVE);
  562. #else
  563. #if defined(__NetBSD__)
  564. newmap = mremap(self->data, self->size, self->data, new_size, 0);
  565. #else
  566. newmap = mremap(self->data, self->size, new_size, 0);
  567. #endif /* __NetBSD__ */
  568. #endif
  569. if (newmap == (void *)-1)
  570. {
  571. PyErr_SetFromErrno(PyExc_OSError);
  572. return NULL;
  573. }
  574. self->data = newmap;
  575. self->size = new_size;
  576. Py_RETURN_NONE;
  577. #endif /* HAVE_MREMAP */
  578. #endif /* UNIX */
  579. }
  580. }
  581. static PyObject *
  582. mmap_tell_method(mmap_object *self, PyObject *unused)
  583. {
  584. CHECK_VALID(NULL);
  585. return PyLong_FromSize_t(self->pos);
  586. }
  587. static PyObject *
  588. mmap_flush_method(mmap_object *self, PyObject *args)
  589. {
  590. Py_ssize_t offset = 0;
  591. Py_ssize_t size = self->size;
  592. CHECK_VALID(NULL);
  593. if (!PyArg_ParseTuple(args, "|nn:flush", &offset, &size))
  594. return NULL;
  595. if (size < 0 || offset < 0 || self->size - offset < size) {
  596. PyErr_SetString(PyExc_ValueError, "flush values out of range");
  597. return NULL;
  598. }
  599. if (self->access == ACCESS_READ || self->access == ACCESS_COPY)
  600. Py_RETURN_NONE;
  601. #if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_APP) || defined(MS_WINDOWS_SYSTEM)
  602. if (!FlushViewOfFile(self->data+offset, size)) {
  603. PyErr_SetFromWindowsErr(GetLastError());
  604. return NULL;
  605. }
  606. Py_RETURN_NONE;
  607. #elif defined(UNIX)
  608. /* XXX flags for msync? */
  609. if (-1 == msync(self->data + offset, size, MS_SYNC)) {
  610. PyErr_SetFromErrno(PyExc_OSError);
  611. return NULL;
  612. }
  613. Py_RETURN_NONE;
  614. #else
  615. PyErr_SetString(PyExc_ValueError, "flush not supported on this system");
  616. return NULL;
  617. #endif
  618. }
  619. static PyObject *
  620. mmap_seek_method(mmap_object *self, PyObject *args)
  621. {
  622. Py_ssize_t dist;
  623. int how=0;
  624. CHECK_VALID(NULL);
  625. if (!PyArg_ParseTuple(args, "n|i:seek", &dist, &how))
  626. return NULL;
  627. else {
  628. Py_ssize_t where;
  629. switch (how) {
  630. case 0: /* relative to start */
  631. where = dist;
  632. break;
  633. case 1: /* relative to current position */
  634. if (PY_SSIZE_T_MAX - self->pos < dist)
  635. goto onoutofrange;
  636. where = self->pos + dist;
  637. break;
  638. case 2: /* relative to end */
  639. if (PY_SSIZE_T_MAX - self->size < dist)
  640. goto onoutofrange;
  641. where = self->size + dist;
  642. break;
  643. default:
  644. PyErr_SetString(PyExc_ValueError, "unknown seek type");
  645. return NULL;
  646. }
  647. if (where > self->size || where < 0)
  648. goto onoutofrange;
  649. self->pos = where;
  650. Py_RETURN_NONE;
  651. }
  652. onoutofrange:
  653. PyErr_SetString(PyExc_ValueError, "seek out of range");
  654. return NULL;
  655. }
  656. static PyObject *
  657. mmap_move_method(mmap_object *self, PyObject *args)
  658. {
  659. Py_ssize_t dest, src, cnt;
  660. CHECK_VALID(NULL);
  661. if (!PyArg_ParseTuple(args, "nnn:move", &dest, &src, &cnt) ||
  662. !is_writable(self)) {
  663. return NULL;
  664. } else {
  665. /* bounds check the values */
  666. if (dest < 0 || src < 0 || cnt < 0)
  667. goto bounds;
  668. if (self->size - dest < cnt || self->size - src < cnt)
  669. goto bounds;
  670. CHECK_VALID(NULL);
  671. memmove(&self->data[dest], &self->data[src], cnt);
  672. Py_RETURN_NONE;
  673. bounds:
  674. PyErr_SetString(PyExc_ValueError,
  675. "source, destination, or count out of range");
  676. return NULL;
  677. }
  678. }
  679. static PyObject *
  680. mmap_closed_get(mmap_object *self, void *Py_UNUSED(ignored))
  681. {
  682. #ifdef MS_WINDOWS
  683. return PyBool_FromLong(self->map_handle == NULL ? 1 : 0);
  684. #elif defined(UNIX)
  685. return PyBool_FromLong(self->data == NULL ? 1 : 0);
  686. #endif
  687. }
  688. static PyObject *
  689. mmap__enter__method(mmap_object *self, PyObject *args)
  690. {
  691. CHECK_VALID(NULL);
  692. return Py_NewRef(self);
  693. }
  694. static PyObject *
  695. mmap__exit__method(PyObject *self, PyObject *args)
  696. {
  697. return mmap_close_method((mmap_object *)self, NULL);
  698. }
  699. static PyObject *
  700. mmap__repr__method(PyObject *self)
  701. {
  702. mmap_object *mobj = (mmap_object *)self;
  703. #ifdef MS_WINDOWS
  704. #define _Py_FORMAT_OFFSET "lld"
  705. if (mobj->map_handle == NULL)
  706. #elif defined(UNIX)
  707. # ifdef HAVE_LARGEFILE_SUPPORT
  708. # define _Py_FORMAT_OFFSET "lld"
  709. # else
  710. # define _Py_FORMAT_OFFSET "ld"
  711. # endif
  712. if (mobj->data == NULL)
  713. #endif
  714. {
  715. return PyUnicode_FromFormat("<%s closed=True>", Py_TYPE(self)->tp_name);
  716. } else {
  717. const char *access_str;
  718. switch (mobj->access) {
  719. case ACCESS_DEFAULT:
  720. access_str = "ACCESS_DEFAULT";
  721. break;
  722. case ACCESS_READ:
  723. access_str = "ACCESS_READ";
  724. break;
  725. case ACCESS_WRITE:
  726. access_str = "ACCESS_WRITE";
  727. break;
  728. case ACCESS_COPY:
  729. access_str = "ACCESS_COPY";
  730. break;
  731. default:
  732. Py_UNREACHABLE();
  733. }
  734. return PyUnicode_FromFormat("<%s closed=False, access=%s, length=%zd, "
  735. "pos=%zd, offset=%" _Py_FORMAT_OFFSET ">",
  736. Py_TYPE(self)->tp_name, access_str,
  737. mobj->size, mobj->pos, mobj->offset);
  738. }
  739. }
  740. #ifdef MS_WINDOWS
  741. static PyObject *
  742. mmap__sizeof__method(mmap_object *self, void *unused)
  743. {
  744. size_t res = _PyObject_SIZE(Py_TYPE(self));
  745. if (self->tagname) {
  746. res += (wcslen(self->tagname) + 1) * sizeof(self->tagname[0]);
  747. }
  748. return PyLong_FromSize_t(res);
  749. }
  750. #endif
  751. #ifdef HAVE_MADVISE
  752. static PyObject *
  753. mmap_madvise_method(mmap_object *self, PyObject *args)
  754. {
  755. int option;
  756. Py_ssize_t start = 0, length;
  757. CHECK_VALID(NULL);
  758. length = self->size;
  759. if (!PyArg_ParseTuple(args, "i|nn:madvise", &option, &start, &length)) {
  760. return NULL;
  761. }
  762. if (start < 0 || start >= self->size) {
  763. PyErr_SetString(PyExc_ValueError, "madvise start out of bounds");
  764. return NULL;
  765. }
  766. if (length < 0) {
  767. PyErr_SetString(PyExc_ValueError, "madvise length invalid");
  768. return NULL;
  769. }
  770. if (PY_SSIZE_T_MAX - start < length) {
  771. PyErr_SetString(PyExc_OverflowError, "madvise length too large");
  772. return NULL;
  773. }
  774. if (start + length > self->size) {
  775. length = self->size - start;
  776. }
  777. CHECK_VALID(NULL);
  778. if (madvise(self->data + start, length, option) != 0) {
  779. PyErr_SetFromErrno(PyExc_OSError);
  780. return NULL;
  781. }
  782. Py_RETURN_NONE;
  783. }
  784. #endif // HAVE_MADVISE
  785. static struct PyMemberDef mmap_object_members[] = {
  786. {"__weaklistoffset__", T_PYSSIZET, offsetof(mmap_object, weakreflist), READONLY},
  787. {NULL},
  788. };
  789. static struct PyMethodDef mmap_object_methods[] = {
  790. {"close", (PyCFunction) mmap_close_method, METH_NOARGS},
  791. {"find", (PyCFunction) mmap_find_method, METH_VARARGS},
  792. {"rfind", (PyCFunction) mmap_rfind_method, METH_VARARGS},
  793. {"flush", (PyCFunction) mmap_flush_method, METH_VARARGS},
  794. #ifdef HAVE_MADVISE
  795. {"madvise", (PyCFunction) mmap_madvise_method, METH_VARARGS},
  796. #endif
  797. {"move", (PyCFunction) mmap_move_method, METH_VARARGS},
  798. {"read", (PyCFunction) mmap_read_method, METH_VARARGS},
  799. {"read_byte", (PyCFunction) mmap_read_byte_method, METH_NOARGS},
  800. {"readline", (PyCFunction) mmap_read_line_method, METH_NOARGS},
  801. {"resize", (PyCFunction) mmap_resize_method, METH_VARARGS},
  802. {"seek", (PyCFunction) mmap_seek_method, METH_VARARGS},
  803. {"size", (PyCFunction) mmap_size_method, METH_NOARGS},
  804. {"tell", (PyCFunction) mmap_tell_method, METH_NOARGS},
  805. {"write", (PyCFunction) mmap_write_method, METH_VARARGS},
  806. {"write_byte", (PyCFunction) mmap_write_byte_method, METH_VARARGS},
  807. {"__enter__", (PyCFunction) mmap__enter__method, METH_NOARGS},
  808. {"__exit__", (PyCFunction) mmap__exit__method, METH_VARARGS},
  809. #ifdef MS_WINDOWS
  810. {"__sizeof__", (PyCFunction) mmap__sizeof__method, METH_NOARGS},
  811. #endif
  812. {NULL, NULL} /* sentinel */
  813. };
  814. static PyGetSetDef mmap_object_getset[] = {
  815. {"closed", (getter) mmap_closed_get, NULL, NULL},
  816. {NULL}
  817. };
  818. /* Functions for treating an mmap'ed file as a buffer */
  819. static int
  820. mmap_buffer_getbuf(mmap_object *self, Py_buffer *view, int flags)
  821. {
  822. CHECK_VALID(-1);
  823. if (PyBuffer_FillInfo(view, (PyObject*)self, self->data, self->size,
  824. (self->access == ACCESS_READ), flags) < 0)
  825. return -1;
  826. self->exports++;
  827. return 0;
  828. }
  829. static void
  830. mmap_buffer_releasebuf(mmap_object *self, Py_buffer *view)
  831. {
  832. self->exports--;
  833. }
  834. static Py_ssize_t
  835. mmap_length(mmap_object *self)
  836. {
  837. CHECK_VALID(-1);
  838. return self->size;
  839. }
  840. static PyObject *
  841. mmap_item(mmap_object *self, Py_ssize_t i)
  842. {
  843. CHECK_VALID(NULL);
  844. if (i < 0 || i >= self->size) {
  845. PyErr_SetString(PyExc_IndexError, "mmap index out of range");
  846. return NULL;
  847. }
  848. return PyBytes_FromStringAndSize(self->data + i, 1);
  849. }
  850. static PyObject *
  851. mmap_subscript(mmap_object *self, PyObject *item)
  852. {
  853. CHECK_VALID(NULL);
  854. if (PyIndex_Check(item)) {
  855. Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  856. if (i == -1 && PyErr_Occurred())
  857. return NULL;
  858. if (i < 0)
  859. i += self->size;
  860. if (i < 0 || i >= self->size) {
  861. PyErr_SetString(PyExc_IndexError,
  862. "mmap index out of range");
  863. return NULL;
  864. }
  865. CHECK_VALID(NULL);
  866. return PyLong_FromLong(Py_CHARMASK(self->data[i]));
  867. }
  868. else if (PySlice_Check(item)) {
  869. Py_ssize_t start, stop, step, slicelen;
  870. if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
  871. return NULL;
  872. }
  873. slicelen = PySlice_AdjustIndices(self->size, &start, &stop, step);
  874. CHECK_VALID(NULL);
  875. if (slicelen <= 0)
  876. return PyBytes_FromStringAndSize("", 0);
  877. else if (step == 1)
  878. return PyBytes_FromStringAndSize(self->data + start,
  879. slicelen);
  880. else {
  881. char *result_buf = (char *)PyMem_Malloc(slicelen);
  882. size_t cur;
  883. Py_ssize_t i;
  884. PyObject *result;
  885. if (result_buf == NULL)
  886. return PyErr_NoMemory();
  887. for (cur = start, i = 0; i < slicelen;
  888. cur += step, i++) {
  889. result_buf[i] = self->data[cur];
  890. }
  891. result = PyBytes_FromStringAndSize(result_buf,
  892. slicelen);
  893. PyMem_Free(result_buf);
  894. return result;
  895. }
  896. }
  897. else {
  898. PyErr_SetString(PyExc_TypeError,
  899. "mmap indices must be integers");
  900. return NULL;
  901. }
  902. }
  903. static int
  904. mmap_ass_item(mmap_object *self, Py_ssize_t i, PyObject *v)
  905. {
  906. const char *buf;
  907. CHECK_VALID(-1);
  908. if (i < 0 || i >= self->size) {
  909. PyErr_SetString(PyExc_IndexError, "mmap index out of range");
  910. return -1;
  911. }
  912. if (v == NULL) {
  913. PyErr_SetString(PyExc_TypeError,
  914. "mmap object doesn't support item deletion");
  915. return -1;
  916. }
  917. if (! (PyBytes_Check(v) && PyBytes_Size(v)==1) ) {
  918. PyErr_SetString(PyExc_IndexError,
  919. "mmap assignment must be length-1 bytes()");
  920. return -1;
  921. }
  922. if (!is_writable(self))
  923. return -1;
  924. buf = PyBytes_AsString(v);
  925. self->data[i] = buf[0];
  926. return 0;
  927. }
  928. static int
  929. mmap_ass_subscript(mmap_object *self, PyObject *item, PyObject *value)
  930. {
  931. CHECK_VALID(-1);
  932. if (!is_writable(self))
  933. return -1;
  934. if (PyIndex_Check(item)) {
  935. Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  936. Py_ssize_t v;
  937. if (i == -1 && PyErr_Occurred())
  938. return -1;
  939. if (i < 0)
  940. i += self->size;
  941. if (i < 0 || i >= self->size) {
  942. PyErr_SetString(PyExc_IndexError,
  943. "mmap index out of range");
  944. return -1;
  945. }
  946. if (value == NULL) {
  947. PyErr_SetString(PyExc_TypeError,
  948. "mmap doesn't support item deletion");
  949. return -1;
  950. }
  951. if (!PyIndex_Check(value)) {
  952. PyErr_SetString(PyExc_TypeError,
  953. "mmap item value must be an int");
  954. return -1;
  955. }
  956. v = PyNumber_AsSsize_t(value, PyExc_TypeError);
  957. if (v == -1 && PyErr_Occurred())
  958. return -1;
  959. if (v < 0 || v > 255) {
  960. PyErr_SetString(PyExc_ValueError,
  961. "mmap item value must be "
  962. "in range(0, 256)");
  963. return -1;
  964. }
  965. CHECK_VALID(-1);
  966. self->data[i] = (char) v;
  967. return 0;
  968. }
  969. else if (PySlice_Check(item)) {
  970. Py_ssize_t start, stop, step, slicelen;
  971. Py_buffer vbuf;
  972. if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
  973. return -1;
  974. }
  975. slicelen = PySlice_AdjustIndices(self->size, &start, &stop, step);
  976. if (value == NULL) {
  977. PyErr_SetString(PyExc_TypeError,
  978. "mmap object doesn't support slice deletion");
  979. return -1;
  980. }
  981. if (PyObject_GetBuffer(value, &vbuf, PyBUF_SIMPLE) < 0)
  982. return -1;
  983. if (vbuf.len != slicelen) {
  984. PyErr_SetString(PyExc_IndexError,
  985. "mmap slice assignment is wrong size");
  986. PyBuffer_Release(&vbuf);
  987. return -1;
  988. }
  989. CHECK_VALID_OR_RELEASE(-1, vbuf);
  990. if (slicelen == 0) {
  991. }
  992. else if (step == 1) {
  993. memcpy(self->data + start, vbuf.buf, slicelen);
  994. }
  995. else {
  996. size_t cur;
  997. Py_ssize_t i;
  998. for (cur = start, i = 0;
  999. i < slicelen;
  1000. cur += step, i++)
  1001. {
  1002. self->data[cur] = ((char *)vbuf.buf)[i];
  1003. }
  1004. }
  1005. PyBuffer_Release(&vbuf);
  1006. return 0;
  1007. }
  1008. else {
  1009. PyErr_SetString(PyExc_TypeError,
  1010. "mmap indices must be integer");
  1011. return -1;
  1012. }
  1013. }
  1014. static PyObject *
  1015. new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict);
  1016. PyDoc_STRVAR(mmap_doc,
  1017. "Windows: mmap(fileno, length[, tagname[, access[, offset]]])\n\
  1018. \n\
  1019. Maps length bytes from the file specified by the file handle fileno,\n\
  1020. and returns a mmap object. If length is larger than the current size\n\
  1021. of the file, the file is extended to contain length bytes. If length\n\
  1022. is 0, the maximum length of the map is the current size of the file,\n\
  1023. except that if the file is empty Windows raises an exception (you cannot\n\
  1024. create an empty mapping on Windows).\n\
  1025. \n\
  1026. Unix: mmap(fileno, length[, flags[, prot[, access[, offset]]]])\n\
  1027. \n\
  1028. Maps length bytes from the file specified by the file descriptor fileno,\n\
  1029. and returns a mmap object. If length is 0, the maximum length of the map\n\
  1030. will be the current size of the file when mmap is called.\n\
  1031. flags specifies the nature of the mapping. MAP_PRIVATE creates a\n\
  1032. private copy-on-write mapping, so changes to the contents of the mmap\n\
  1033. object will be private to this process, and MAP_SHARED creates a mapping\n\
  1034. that's shared with all other processes mapping the same areas of the file.\n\
  1035. The default value is MAP_SHARED.\n\
  1036. \n\
  1037. To map anonymous memory, pass -1 as the fileno (both versions).");
  1038. static PyType_Slot mmap_object_slots[] = {
  1039. {Py_tp_new, new_mmap_object},
  1040. {Py_tp_dealloc, mmap_object_dealloc},
  1041. {Py_tp_repr, mmap__repr__method},
  1042. {Py_tp_doc, (void *)mmap_doc},
  1043. {Py_tp_methods, mmap_object_methods},
  1044. {Py_tp_members, mmap_object_members},
  1045. {Py_tp_getset, mmap_object_getset},
  1046. {Py_tp_getattro, PyObject_GenericGetAttr},
  1047. {Py_tp_traverse, mmap_object_traverse},
  1048. /* as sequence */
  1049. {Py_sq_length, mmap_length},
  1050. {Py_sq_item, mmap_item},
  1051. {Py_sq_ass_item, mmap_ass_item},
  1052. /* as mapping */
  1053. {Py_mp_length, mmap_length},
  1054. {Py_mp_subscript, mmap_subscript},
  1055. {Py_mp_ass_subscript, mmap_ass_subscript},
  1056. /* as buffer */
  1057. {Py_bf_getbuffer, mmap_buffer_getbuf},
  1058. {Py_bf_releasebuffer, mmap_buffer_releasebuf},
  1059. {0, NULL},
  1060. };
  1061. static PyType_Spec mmap_object_spec = {
  1062. .name = "mmap.mmap",
  1063. .basicsize = sizeof(mmap_object),
  1064. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
  1065. Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
  1066. .slots = mmap_object_slots,
  1067. };
  1068. #ifdef UNIX
  1069. #ifdef HAVE_LARGEFILE_SUPPORT
  1070. #define _Py_PARSE_OFF_T "L"
  1071. #else
  1072. #define _Py_PARSE_OFF_T "l"
  1073. #endif
  1074. static PyObject *
  1075. new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
  1076. {
  1077. struct _Py_stat_struct status;
  1078. int fstat_result = -1;
  1079. mmap_object *m_obj;
  1080. Py_ssize_t map_size;
  1081. off_t offset = 0;
  1082. int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ;
  1083. int devzero = -1;
  1084. int access = (int)ACCESS_DEFAULT;
  1085. static char *keywords[] = {"fileno", "length",
  1086. "flags", "prot",
  1087. "access", "offset", NULL};
  1088. if (!PyArg_ParseTupleAndKeywords(args, kwdict, "in|iii" _Py_PARSE_OFF_T, keywords,
  1089. &fd, &map_size, &flags, &prot,
  1090. &access, &offset))
  1091. return NULL;
  1092. if (map_size < 0) {
  1093. PyErr_SetString(PyExc_OverflowError,
  1094. "memory mapped length must be positive");
  1095. return NULL;
  1096. }
  1097. if (offset < 0) {
  1098. PyErr_SetString(PyExc_OverflowError,
  1099. "memory mapped offset must be positive");
  1100. return NULL;
  1101. }
  1102. if ((access != (int)ACCESS_DEFAULT) &&
  1103. ((flags != MAP_SHARED) || (prot != (PROT_WRITE | PROT_READ))))
  1104. return PyErr_Format(PyExc_ValueError,
  1105. "mmap can't specify both access and flags, prot.");
  1106. switch ((access_mode)access) {
  1107. case ACCESS_READ:
  1108. flags = MAP_SHARED;
  1109. prot = PROT_READ;
  1110. break;
  1111. case ACCESS_WRITE:
  1112. flags = MAP_SHARED;
  1113. prot = PROT_READ | PROT_WRITE;
  1114. break;
  1115. case ACCESS_COPY:
  1116. flags = MAP_PRIVATE;
  1117. prot = PROT_READ | PROT_WRITE;
  1118. break;
  1119. case ACCESS_DEFAULT:
  1120. /* map prot to access type */
  1121. if ((prot & PROT_READ) && (prot & PROT_WRITE)) {
  1122. /* ACCESS_DEFAULT */
  1123. }
  1124. else if (prot & PROT_WRITE) {
  1125. access = ACCESS_WRITE;
  1126. }
  1127. else {
  1128. access = ACCESS_READ;
  1129. }
  1130. break;
  1131. default:
  1132. return PyErr_Format(PyExc_ValueError,
  1133. "mmap invalid access parameter.");
  1134. }
  1135. if (PySys_Audit("mmap.__new__", "ini" _Py_PARSE_OFF_T,
  1136. fd, map_size, access, offset) < 0) {
  1137. return NULL;
  1138. }
  1139. #ifdef __APPLE__
  1140. /* Issue #11277: fsync(2) is not enough on OS X - a special, OS X specific
  1141. fcntl(2) is necessary to force DISKSYNC and get around mmap(2) bug */
  1142. if (fd != -1)
  1143. (void)fcntl(fd, F_FULLFSYNC);
  1144. #endif
  1145. if (fd != -1) {
  1146. Py_BEGIN_ALLOW_THREADS
  1147. fstat_result = _Py_fstat_noraise(fd, &status);
  1148. Py_END_ALLOW_THREADS
  1149. }
  1150. if (fd != -1 && fstat_result == 0 && S_ISREG(status.st_mode)) {
  1151. if (map_size == 0) {
  1152. if (status.st_size == 0) {
  1153. PyErr_SetString(PyExc_ValueError,
  1154. "cannot mmap an empty file");
  1155. return NULL;
  1156. }
  1157. if (offset >= status.st_size) {
  1158. PyErr_SetString(PyExc_ValueError,
  1159. "mmap offset is greater than file size");
  1160. return NULL;
  1161. }
  1162. if (status.st_size - offset > PY_SSIZE_T_MAX) {
  1163. PyErr_SetString(PyExc_ValueError,
  1164. "mmap length is too large");
  1165. return NULL;
  1166. }
  1167. map_size = (Py_ssize_t) (status.st_size - offset);
  1168. } else if (offset > status.st_size || status.st_size - offset < map_size) {
  1169. PyErr_SetString(PyExc_ValueError,
  1170. "mmap length is greater than file size");
  1171. return NULL;
  1172. }
  1173. }
  1174. m_obj = (mmap_object *)type->tp_alloc(type, 0);
  1175. if (m_obj == NULL) {return NULL;}
  1176. m_obj->data = NULL;
  1177. m_obj->size = map_size;
  1178. m_obj->pos = 0;
  1179. m_obj->weakreflist = NULL;
  1180. m_obj->exports = 0;
  1181. m_obj->offset = offset;
  1182. if (fd == -1) {
  1183. m_obj->fd = -1;
  1184. /* Assume the caller wants to map anonymous memory.
  1185. This is the same behaviour as Windows. mmap.mmap(-1, size)
  1186. on both Windows and Unix map anonymous memory.
  1187. */
  1188. #ifdef MAP_ANONYMOUS
  1189. /* BSD way to map anonymous memory */
  1190. flags |= MAP_ANONYMOUS;
  1191. /* VxWorks only supports MAP_ANONYMOUS with MAP_PRIVATE flag */
  1192. #ifdef __VXWORKS__
  1193. flags &= ~MAP_SHARED;
  1194. flags |= MAP_PRIVATE;
  1195. #endif
  1196. #else
  1197. /* SVR4 method to map anonymous memory is to open /dev/zero */
  1198. fd = devzero = _Py_open("/dev/zero", O_RDWR);
  1199. if (devzero == -1) {
  1200. Py_DECREF(m_obj);
  1201. return NULL;
  1202. }
  1203. #endif
  1204. }
  1205. else {
  1206. m_obj->fd = _Py_dup(fd);
  1207. if (m_obj->fd == -1) {
  1208. Py_DECREF(m_obj);
  1209. return NULL;
  1210. }
  1211. }
  1212. Py_BEGIN_ALLOW_THREADS
  1213. m_obj->data = mmap(NULL, map_size, prot, flags, fd, offset);
  1214. Py_END_ALLOW_THREADS
  1215. int saved_errno = errno;
  1216. if (devzero != -1) {
  1217. close(devzero);
  1218. }
  1219. if (m_obj->data == (char *)-1) {
  1220. m_obj->data = NULL;
  1221. Py_DECREF(m_obj);
  1222. errno = saved_errno;
  1223. PyErr_SetFromErrno(PyExc_OSError);
  1224. return NULL;
  1225. }
  1226. m_obj->access = (access_mode)access;
  1227. return (PyObject *)m_obj;
  1228. }
  1229. #endif /* UNIX */
  1230. #ifdef MS_WINDOWS
  1231. /* A note on sizes and offsets: while the actual map size must hold in a
  1232. Py_ssize_t, both the total file size and the start offset can be longer
  1233. than a Py_ssize_t, so we use long long which is always 64-bit.
  1234. */
  1235. static PyObject *
  1236. new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
  1237. {
  1238. mmap_object *m_obj;
  1239. Py_ssize_t map_size;
  1240. long long offset = 0, size;
  1241. DWORD off_hi; /* upper 32 bits of offset */
  1242. DWORD off_lo; /* lower 32 bits of offset */
  1243. DWORD size_hi; /* upper 32 bits of size */
  1244. DWORD size_lo; /* lower 32 bits of size */
  1245. PyObject *tagname = Py_None;
  1246. DWORD dwErr = 0;
  1247. int fileno;
  1248. HANDLE fh = 0;
  1249. int access = (access_mode)ACCESS_DEFAULT;
  1250. DWORD flProtect, dwDesiredAccess;
  1251. static char *keywords[] = { "fileno", "length",
  1252. "tagname",
  1253. "access", "offset", NULL };
  1254. if (!PyArg_ParseTupleAndKeywords(args, kwdict, "in|OiL", keywords,
  1255. &fileno, &map_size,
  1256. &tagname, &access, &offset)) {
  1257. return NULL;
  1258. }
  1259. if (PySys_Audit("mmap.__new__", "iniL",
  1260. fileno, map_size, access, offset) < 0) {
  1261. return NULL;
  1262. }
  1263. switch((access_mode)access) {
  1264. case ACCESS_READ:
  1265. flProtect = PAGE_READONLY;
  1266. dwDesiredAccess = FILE_MAP_READ;
  1267. break;
  1268. case ACCESS_DEFAULT: case ACCESS_WRITE:
  1269. flProtect = PAGE_READWRITE;
  1270. dwDesiredAccess = FILE_MAP_WRITE;
  1271. break;
  1272. case ACCESS_COPY:
  1273. flProtect = PAGE_WRITECOPY;
  1274. dwDesiredAccess = FILE_MAP_COPY;
  1275. break;
  1276. default:
  1277. return PyErr_Format(PyExc_ValueError,
  1278. "mmap invalid access parameter.");
  1279. }
  1280. if (map_size < 0) {
  1281. PyErr_SetString(PyExc_OverflowError,
  1282. "memory mapped length must be positive");
  1283. return NULL;
  1284. }
  1285. if (offset < 0) {
  1286. PyErr_SetString(PyExc_OverflowError,
  1287. "memory mapped offset must be positive");
  1288. return NULL;
  1289. }
  1290. /* assume -1 and 0 both mean invalid filedescriptor
  1291. to 'anonymously' map memory.
  1292. XXX: fileno == 0 is a valid fd, but was accepted prior to 2.5.
  1293. XXX: Should this code be added?
  1294. if (fileno == 0)
  1295. PyErr_WarnEx(PyExc_DeprecationWarning,
  1296. "don't use 0 for anonymous memory",
  1297. 1);
  1298. */
  1299. if (fileno != -1 && fileno != 0) {
  1300. /* Ensure that fileno is within the CRT's valid range */
  1301. fh = _Py_get_osfhandle(fileno);
  1302. if (fh == INVALID_HANDLE_VALUE)
  1303. return NULL;
  1304. /* Win9x appears to need us seeked to zero */
  1305. lseek(fileno, 0, SEEK_SET);
  1306. }
  1307. m_obj = (mmap_object *)type->tp_alloc(type, 0);
  1308. if (m_obj == NULL)
  1309. return NULL;
  1310. /* Set every field to an invalid marker, so we can safely
  1311. destruct the object in the face of failure */
  1312. m_obj->data = NULL;
  1313. m_obj->file_handle = INVALID_HANDLE_VALUE;
  1314. m_obj->map_handle = NULL;
  1315. m_obj->tagname = NULL;
  1316. m_obj->offset = offset;
  1317. if (fh) {
  1318. /* It is necessary to duplicate the handle, so the
  1319. Python code can close it on us */
  1320. if (!DuplicateHandle(
  1321. GetCurrentProcess(), /* source process handle */
  1322. fh, /* handle to be duplicated */
  1323. GetCurrentProcess(), /* target proc handle */
  1324. (LPHANDLE)&m_obj->file_handle, /* result */
  1325. 0, /* access - ignored due to options value */
  1326. FALSE, /* inherited by child processes? */
  1327. DUPLICATE_SAME_ACCESS)) { /* options */
  1328. dwErr = GetLastError();
  1329. Py_DECREF(m_obj);
  1330. PyErr_SetFromWindowsErr(dwErr);
  1331. return NULL;
  1332. }
  1333. if (!map_size) {
  1334. DWORD low,high;
  1335. low = GetFileSize(fh, &high);
  1336. /* low might just happen to have the value INVALID_FILE_SIZE;
  1337. so we need to check the last error also. */
  1338. if (low == INVALID_FILE_SIZE &&
  1339. (dwErr = GetLastError()) != NO_ERROR) {
  1340. Py_DECREF(m_obj);
  1341. return PyErr_SetFromWindowsErr(dwErr);
  1342. }
  1343. size = (((long long) high) << 32) + low;
  1344. if (size == 0) {
  1345. PyErr_SetString(PyExc_ValueError,
  1346. "cannot mmap an empty file");
  1347. Py_DECREF(m_obj);
  1348. return NULL;
  1349. }
  1350. if (offset >= size) {
  1351. PyErr_SetString(PyExc_ValueError,
  1352. "mmap offset is greater than file size");
  1353. Py_DECREF(m_obj);
  1354. return NULL;
  1355. }
  1356. if (size - offset > PY_SSIZE_T_MAX) {
  1357. PyErr_SetString(PyExc_ValueError,
  1358. "mmap length is too large");
  1359. Py_DECREF(m_obj);
  1360. return NULL;
  1361. }
  1362. m_obj->size = (Py_ssize_t) (size - offset);
  1363. } else {
  1364. m_obj->size = map_size;
  1365. size = offset + map_size;
  1366. }
  1367. }
  1368. else {
  1369. m_obj->size = map_size;
  1370. size = offset + map_size;
  1371. }
  1372. /* set the initial position */
  1373. m_obj->pos = (size_t) 0;
  1374. m_obj->weakreflist = NULL;
  1375. m_obj->exports = 0;
  1376. /* set the tag name */
  1377. if (!Py_IsNone(tagname)) {
  1378. if (!PyUnicode_Check(tagname)) {
  1379. Py_DECREF(m_obj);
  1380. return PyErr_Format(PyExc_TypeError, "expected str or None for "
  1381. "'tagname', not %.200s",
  1382. Py_TYPE(tagname)->tp_name);
  1383. }
  1384. m_obj->tagname = PyUnicode_AsWideCharString(tagname, NULL);
  1385. if (m_obj->tagname == NULL) {
  1386. Py_DECREF(m_obj);
  1387. return NULL;
  1388. }
  1389. }
  1390. m_obj->access = (access_mode)access;
  1391. size_hi = (DWORD)(size >> 32);
  1392. size_lo = (DWORD)(size & 0xFFFFFFFF);
  1393. off_hi = (DWORD)(offset >> 32);
  1394. off_lo = (DWORD)(offset & 0xFFFFFFFF);
  1395. /* For files, it would be sufficient to pass 0 as size.
  1396. For anonymous maps, we have to pass the size explicitly. */
  1397. m_obj->map_handle = CreateFileMappingW(m_obj->file_handle,
  1398. NULL,
  1399. flProtect,
  1400. size_hi,
  1401. size_lo,
  1402. m_obj->tagname);
  1403. if (m_obj->map_handle != NULL) {
  1404. m_obj->data = (char *) MapViewOfFile(m_obj->map_handle,
  1405. dwDesiredAccess,
  1406. off_hi,
  1407. off_lo,
  1408. m_obj->size);
  1409. if (m_obj->data != NULL)
  1410. return (PyObject *)m_obj;
  1411. else {
  1412. dwErr = GetLastError();
  1413. CloseHandle(m_obj->map_handle);
  1414. m_obj->map_handle = NULL;
  1415. }
  1416. } else
  1417. dwErr = GetLastError();
  1418. Py_DECREF(m_obj);
  1419. PyErr_SetFromWindowsErr(dwErr);
  1420. return NULL;
  1421. }
  1422. #endif /* MS_WINDOWS */
  1423. static int
  1424. mmap_exec(PyObject *module)
  1425. {
  1426. Py_INCREF(PyExc_OSError);
  1427. if (PyModule_AddObject(module, "error", PyExc_OSError) < 0) {
  1428. Py_DECREF(PyExc_OSError);
  1429. return -1;
  1430. }
  1431. PyObject *mmap_object_type = PyType_FromModuleAndSpec(module,
  1432. &mmap_object_spec, NULL);
  1433. if (mmap_object_type == NULL) {
  1434. return -1;
  1435. }
  1436. int rc = PyModule_AddType(module, (PyTypeObject *)mmap_object_type);
  1437. Py_DECREF(mmap_object_type);
  1438. if (rc < 0) {
  1439. return -1;
  1440. }
  1441. #define ADD_INT_MACRO(module, constant) \
  1442. do { \
  1443. if (PyModule_AddIntConstant(module, #constant, constant) < 0) { \
  1444. return -1; \
  1445. } \
  1446. } while (0)
  1447. #ifdef PROT_EXEC
  1448. ADD_INT_MACRO(module, PROT_EXEC);
  1449. #endif
  1450. #ifdef PROT_READ
  1451. ADD_INT_MACRO(module, PROT_READ);
  1452. #endif
  1453. #ifdef PROT_WRITE
  1454. ADD_INT_MACRO(module, PROT_WRITE);
  1455. #endif
  1456. #ifdef MAP_SHARED
  1457. ADD_INT_MACRO(module, MAP_SHARED);
  1458. #endif
  1459. #ifdef MAP_PRIVATE
  1460. ADD_INT_MACRO(module, MAP_PRIVATE);
  1461. #endif
  1462. #ifdef MAP_DENYWRITE
  1463. ADD_INT_MACRO(module, MAP_DENYWRITE);
  1464. #endif
  1465. #ifdef MAP_EXECUTABLE
  1466. ADD_INT_MACRO(module, MAP_EXECUTABLE);
  1467. #endif
  1468. #ifdef MAP_ANONYMOUS
  1469. if (PyModule_AddIntConstant(module, "MAP_ANON", MAP_ANONYMOUS) < 0 ) {
  1470. return -1;
  1471. }
  1472. ADD_INT_MACRO(module, MAP_ANONYMOUS);
  1473. #endif
  1474. #ifdef MAP_POPULATE
  1475. ADD_INT_MACRO(module, MAP_POPULATE);
  1476. #endif
  1477. #ifdef MAP_STACK
  1478. // Mostly a no-op on Linux and NetBSD, but useful on OpenBSD
  1479. // for stack usage (even on x86 arch)
  1480. ADD_INT_MACRO(module, MAP_STACK);
  1481. #endif
  1482. #ifdef MAP_ALIGNED_SUPER
  1483. ADD_INT_MACRO(module, MAP_ALIGNED_SUPER);
  1484. #endif
  1485. #ifdef MAP_CONCEAL
  1486. ADD_INT_MACRO(module, MAP_CONCEAL);
  1487. #endif
  1488. if (PyModule_AddIntConstant(module, "PAGESIZE", (long)my_getpagesize()) < 0 ) {
  1489. return -1;
  1490. }
  1491. if (PyModule_AddIntConstant(module, "ALLOCATIONGRANULARITY", (long)my_getallocationgranularity()) < 0 ) {
  1492. return -1;
  1493. }
  1494. ADD_INT_MACRO(module, ACCESS_DEFAULT);
  1495. ADD_INT_MACRO(module, ACCESS_READ);
  1496. ADD_INT_MACRO(module, ACCESS_WRITE);
  1497. ADD_INT_MACRO(module, ACCESS_COPY);
  1498. #ifdef HAVE_MADVISE
  1499. // Conventional advice values
  1500. #ifdef MADV_NORMAL
  1501. ADD_INT_MACRO(module, MADV_NORMAL);
  1502. #endif
  1503. #ifdef MADV_RANDOM
  1504. ADD_INT_MACRO(module, MADV_RANDOM);
  1505. #endif
  1506. #ifdef MADV_SEQUENTIAL
  1507. ADD_INT_MACRO(module, MADV_SEQUENTIAL);
  1508. #endif
  1509. #ifdef MADV_WILLNEED
  1510. ADD_INT_MACRO(module, MADV_WILLNEED);
  1511. #endif
  1512. #ifdef MADV_DONTNEED
  1513. ADD_INT_MACRO(module, MADV_DONTNEED);
  1514. #endif
  1515. // Linux-specific advice values
  1516. #ifdef MADV_REMOVE
  1517. ADD_INT_MACRO(module, MADV_REMOVE);
  1518. #endif
  1519. #ifdef MADV_DONTFORK
  1520. ADD_INT_MACRO(module, MADV_DONTFORK);
  1521. #endif
  1522. #ifdef MADV_DOFORK
  1523. ADD_INT_MACRO(module, MADV_DOFORK);
  1524. #endif
  1525. #ifdef MADV_HWPOISON
  1526. ADD_INT_MACRO(module, MADV_HWPOISON);
  1527. #endif
  1528. #ifdef MADV_MERGEABLE
  1529. ADD_INT_MACRO(module, MADV_MERGEABLE);
  1530. #endif
  1531. #ifdef MADV_UNMERGEABLE
  1532. ADD_INT_MACRO(module, MADV_UNMERGEABLE);
  1533. #endif
  1534. #ifdef MADV_SOFT_OFFLINE
  1535. ADD_INT_MACRO(module, MADV_SOFT_OFFLINE);
  1536. #endif
  1537. #ifdef MADV_HUGEPAGE
  1538. ADD_INT_MACRO(module, MADV_HUGEPAGE);
  1539. #endif
  1540. #ifdef MADV_NOHUGEPAGE
  1541. ADD_INT_MACRO(module, MADV_NOHUGEPAGE);
  1542. #endif
  1543. #ifdef MADV_DONTDUMP
  1544. ADD_INT_MACRO(module, MADV_DONTDUMP);
  1545. #endif
  1546. #ifdef MADV_DODUMP
  1547. ADD_INT_MACRO(module, MADV_DODUMP);
  1548. #endif
  1549. #ifdef MADV_FREE // (Also present on FreeBSD and macOS.)
  1550. ADD_INT_MACRO(module, MADV_FREE);
  1551. #endif
  1552. // FreeBSD-specific
  1553. #ifdef MADV_NOSYNC
  1554. ADD_INT_MACRO(module, MADV_NOSYNC);
  1555. #endif
  1556. #ifdef MADV_AUTOSYNC
  1557. ADD_INT_MACRO(module, MADV_AUTOSYNC);
  1558. #endif
  1559. #ifdef MADV_NOCORE
  1560. ADD_INT_MACRO(module, MADV_NOCORE);
  1561. #endif
  1562. #ifdef MADV_CORE
  1563. ADD_INT_MACRO(module, MADV_CORE);
  1564. #endif
  1565. #ifdef MADV_PROTECT
  1566. ADD_INT_MACRO(module, MADV_PROTECT);
  1567. #endif
  1568. // Darwin-specific
  1569. #ifdef MADV_FREE_REUSABLE // (As MADV_FREE but reclaims more faithful for task_info/Activity Monitor...)
  1570. ADD_INT_MACRO(module, MADV_FREE_REUSABLE);
  1571. #endif
  1572. #ifdef MADV_FREE_REUSE // (Reuse pages previously tagged as reusable)
  1573. ADD_INT_MACRO(module, MADV_FREE_REUSE);
  1574. #endif
  1575. #endif // HAVE_MADVISE
  1576. return 0;
  1577. }
  1578. static PyModuleDef_Slot mmap_slots[] = {
  1579. {Py_mod_exec, mmap_exec},
  1580. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  1581. {0, NULL}
  1582. };
  1583. static struct PyModuleDef mmapmodule = {
  1584. .m_base = PyModuleDef_HEAD_INIT,
  1585. .m_name = "mmap",
  1586. .m_size = 0,
  1587. .m_slots = mmap_slots,
  1588. };
  1589. PyMODINIT_FUNC
  1590. PyInit_mmap(void)
  1591. {
  1592. return PyModuleDef_Init(&mmapmodule);
  1593. }