blob: 917c6362c11d9af0861949eb522186c9cffa4927 [file] [log] [blame]
Guido van Rossum09fdf072000-03-31 01:17:07 +00001/*
2 / Author: Sam Rushing <rushing@nightmare.com>
Andrew M. Kuchling10f9c072001-11-05 21:25:42 +00003 / Hacked for Unix by AMK
Guido van Rossum09fdf072000-03-31 01:17:07 +00004 / $Id$
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00005
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006 / Modified to support mmap with offset - to map a 'window' of a file
7 / Author: Yotam Medini yotamm@mellanox.co.il
8 /
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00009 / mmapmodule.cpp -- map a view of a file into memory
10 /
11 / todo: need permission flags, perhaps a 'chsize' analog
12 / not all functions check range yet!!!
13 /
14 /
Mark Hammond071864a2000-07-30 02:46:26 +000015 / This version of mmapmodule.c has been changed significantly
16 / from the original mmapfile.c on which it was based.
17 / The original version of mmapfile is maintained by Sam at
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +000018 / ftp://squirl.nightmare.com/pub/python/python-ext.
19*/
20
Martin v. Löwiscfe7e092006-02-17 06:59:14 +000021#define PY_SSIZE_T_CLEAN
Guido van Rossum09fdf072000-03-31 01:17:07 +000022#include <Python.h>
Antoine Pitrouc53204b2013-08-05 23:17:30 +020023#include "structmember.h"
Guido van Rossum09fdf072000-03-31 01:17:07 +000024
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000025#ifndef MS_WINDOWS
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +000026#define UNIX
Benjamin Petersonf6b5cad2015-08-02 12:15:30 -070027# ifdef HAVE_FCNTL_H
Victor Stinnera6cd0cf2011-05-02 01:05:37 +020028# include <fcntl.h>
Benjamin Petersonf6b5cad2015-08-02 12:15:30 -070029# endif /* HAVE_FCNTL_H */
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +000030#endif
31
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000032#ifdef MS_WINDOWS
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +000033#include <windows.h>
Fred Drake145f96e2000-10-01 17:50:46 +000034static int
35my_getpagesize(void)
36{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000037 SYSTEM_INFO si;
38 GetSystemInfo(&si);
39 return si.dwPageSize;
Fred Drake145f96e2000-10-01 17:50:46 +000040}
Guido van Rossum8ce8a782007-11-01 19:42:39 +000041
42static int
43my_getallocationgranularity (void)
44{
45
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 SYSTEM_INFO si;
47 GetSystemInfo(&si);
48 return si.dwAllocationGranularity;
Guido van Rossum8ce8a782007-11-01 19:42:39 +000049}
50
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +000051#endif
52
53#ifdef UNIX
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +000054#include <sys/mman.h>
Andrew M. Kuchling7b9fb922000-06-17 22:41:22 +000055#include <sys/stat.h>
Guido van Rossum4b36e6b2000-09-25 13:16:15 +000056
Fred Drake145f96e2000-10-01 17:50:46 +000057#if defined(HAVE_SYSCONF) && defined(_SC_PAGESIZE)
58static int
59my_getpagesize(void)
60{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 return sysconf(_SC_PAGESIZE);
Fred Drake145f96e2000-10-01 17:50:46 +000062}
Guido van Rossum8ce8a782007-11-01 19:42:39 +000063
64#define my_getallocationgranularity my_getpagesize
Fred Drake145f96e2000-10-01 17:50:46 +000065#else
66#define my_getpagesize getpagesize
67#endif
68
Guido van Rossum4b36e6b2000-09-25 13:16:15 +000069#endif /* UNIX */
70
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +000071#include <string.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000072
73#ifdef HAVE_SYS_TYPES_H
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +000074#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000075#endif /* HAVE_SYS_TYPES_H */
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +000076
Neal Norwitz3eaf2b52006-02-16 08:08:54 +000077/* Prefer MAP_ANONYMOUS since MAP_ANON is deprecated according to man page. */
Neal Norwitz0e6bc8c2006-02-05 05:45:43 +000078#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
79# define MAP_ANONYMOUS MAP_ANON
80#endif
81
Tim Peters5ebfd362001-11-13 23:11:19 +000082typedef enum
83{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 ACCESS_DEFAULT,
85 ACCESS_READ,
86 ACCESS_WRITE,
87 ACCESS_COPY
Tim Peters5ebfd362001-11-13 23:11:19 +000088} access_mode;
89
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +000090typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 PyObject_HEAD
92 char * data;
Benjamin Petersoncd04db02016-10-05 21:45:48 -070093 Py_ssize_t size;
94 Py_ssize_t pos; /* relative to offset */
Antoine Pitrou97696cb2011-02-21 23:46:27 +000095#ifdef MS_WINDOWS
Benjamin Petersonaf580df2016-09-06 10:46:49 -070096 long long offset;
Antoine Pitrou97696cb2011-02-21 23:46:27 +000097#else
98 off_t offset;
99#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 int exports;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000101
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000102#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 HANDLE map_handle;
104 HANDLE file_handle;
105 char * tagname;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000106#endif
107
108#ifdef UNIX
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 int fd;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000110#endif
Tim Peters5ebfd362001-11-13 23:11:19 +0000111
Antoine Pitrouc53204b2013-08-05 23:17:30 +0200112 PyObject *weakreflist;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 access_mode access;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000114} mmap_object;
115
Tim Peters5ebfd362001-11-13 23:11:19 +0000116
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000117static void
Fredrik Lundh54cf3dc2000-07-08 22:05:01 +0000118mmap_object_dealloc(mmap_object *m_obj)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000119{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000120#ifdef MS_WINDOWS
Davide Rizzodc078942019-03-06 18:08:31 +0100121 Py_BEGIN_ALLOW_THREADS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 if (m_obj->data != NULL)
123 UnmapViewOfFile (m_obj->data);
124 if (m_obj->map_handle != NULL)
125 CloseHandle (m_obj->map_handle);
126 if (m_obj->file_handle != INVALID_HANDLE_VALUE)
127 CloseHandle (m_obj->file_handle);
Davide Rizzodc078942019-03-06 18:08:31 +0100128 Py_END_ALLOW_THREADS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 if (m_obj->tagname)
130 PyMem_Free(m_obj->tagname);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000131#endif /* MS_WINDOWS */
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000132
133#ifdef UNIX
Davide Rizzodc078942019-03-06 18:08:31 +0100134 Py_BEGIN_ALLOW_THREADS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 if (m_obj->fd >= 0)
136 (void) close(m_obj->fd);
137 if (m_obj->data!=NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 munmap(m_obj->data, m_obj->size);
139 }
Davide Rizzobb9593a2019-03-06 16:52:34 +0100140 Py_END_ALLOW_THREADS
Davide Rizzodc078942019-03-06 18:08:31 +0100141#endif /* UNIX */
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000142
Antoine Pitrouc53204b2013-08-05 23:17:30 +0200143 if (m_obj->weakreflist != NULL)
144 PyObject_ClearWeakRefs((PyObject *) m_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 Py_TYPE(m_obj)->tp_free((PyObject*)m_obj);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000146}
147
148static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000149mmap_close_method(mmap_object *self, PyObject *unused)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 if (self->exports > 0) {
152 PyErr_SetString(PyExc_BufferError, "cannot close "\
153 "exported pointers exist");
154 return NULL;
155 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000156#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 /* For each resource we maintain, we need to check
158 the value is valid, and if so, free the resource
159 and set the member value to an invalid value so
160 the dealloc does not attempt to resource clearing
161 again.
162 TODO - should we check for errors in the close operations???
163 */
Davide Rizzobb9593a2019-03-06 16:52:34 +0100164 HANDLE map_handle = self->map_handle;
165 HANDLE file_handle = self->file_handle;
166 char *data = self->data;
167 self->map_handle = NULL;
168 self->file_handle = INVALID_HANDLE_VALUE;
169 self->data = NULL;
170 Py_BEGIN_ALLOW_THREADS
171 if (data != NULL) {
172 UnmapViewOfFile(data);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 }
Davide Rizzobb9593a2019-03-06 16:52:34 +0100174 if (map_handle != NULL) {
175 CloseHandle(map_handle);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 }
Davide Rizzobb9593a2019-03-06 16:52:34 +0100177 if (file_handle != INVALID_HANDLE_VALUE) {
178 CloseHandle(file_handle);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 }
Davide Rizzobb9593a2019-03-06 16:52:34 +0100180 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000181#endif /* MS_WINDOWS */
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000182
183#ifdef UNIX
Davide Rizzobb9593a2019-03-06 16:52:34 +0100184 int fd = self->fd;
185 char *data = self->data;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 self->fd = -1;
Davide Rizzobb9593a2019-03-06 16:52:34 +0100187 self->data = NULL;
188 Py_BEGIN_ALLOW_THREADS
189 if (0 <= fd)
190 (void) close(fd);
191 if (data != NULL) {
192 munmap(data, self->size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 }
Davide Rizzobb9593a2019-03-06 16:52:34 +0100194 Py_END_ALLOW_THREADS
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000195#endif
196
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200197 Py_RETURN_NONE;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000198}
199
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000200#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201#define CHECK_VALID(err) \
202do { \
203 if (self->map_handle == NULL) { \
204 PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \
205 return err; \
206 } \
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000207} while (0)
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000208#endif /* MS_WINDOWS */
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000209
210#ifdef UNIX
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211#define CHECK_VALID(err) \
212do { \
213 if (self->data == NULL) { \
214 PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \
215 return err; \
216 } \
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000217} while (0)
218#endif /* UNIX */
219
220static PyObject *
Fredrik Lundh54cf3dc2000-07-08 22:05:01 +0000221mmap_read_byte_method(mmap_object *self,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 PyObject *unused)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 CHECK_VALID(NULL);
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700225 if (self->pos >= self->size) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 PyErr_SetString(PyExc_ValueError, "read byte out of range");
227 return NULL;
228 }
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700229 return PyLong_FromLong((unsigned char)self->data[self->pos++]);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000230}
231
232static PyObject *
Fredrik Lundh54cf3dc2000-07-08 22:05:01 +0000233mmap_read_line_method(mmap_object *self,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 PyObject *unused)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000235{
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700236 Py_ssize_t remaining;
237 char *start, *eol;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 PyObject *result;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 CHECK_VALID(NULL);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000241
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700242 remaining = (self->pos < self->size) ? self->size - self->pos : 0;
243 if (!remaining)
244 return PyBytes_FromString("");
245 start = self->data + self->pos;
246 eol = memchr(start, '\n', remaining);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 if (!eol)
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700248 eol = self->data + self->size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 else
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700250 ++eol; /* advance past newline */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 result = PyBytes_FromStringAndSize(start, (eol - start));
252 self->pos += (eol - start);
253 return result;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000254}
255
256static PyObject *
Fredrik Lundh54cf3dc2000-07-08 22:05:01 +0000257mmap_read_method(mmap_object *self,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 PyObject *args)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000259{
Benjamin Peterson8f1cdc62016-10-05 23:32:09 -0700260 Py_ssize_t num_bytes = PY_SSIZE_T_MAX, remaining;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 PyObject *result;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 CHECK_VALID(NULL);
Serhiy Storchaka762bf402017-03-30 09:15:31 +0300264 if (!PyArg_ParseTuple(args, "|O&:read", _Py_convert_optional_to_ssize_t, &num_bytes))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 return(NULL);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 /* silently 'adjust' out-of-range requests */
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700268 remaining = (self->pos < self->size) ? self->size - self->pos : 0;
269 if (num_bytes < 0 || num_bytes > remaining)
270 num_bytes = remaining;
271 result = PyBytes_FromStringAndSize(&self->data[self->pos], num_bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 self->pos += num_bytes;
273 return result;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000274}
275
276static PyObject *
Georg Brandlfceab5a2008-01-19 20:08:23 +0000277mmap_gfind(mmap_object *self,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 PyObject *args,
279 int reverse)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 Py_ssize_t start = self->pos;
282 Py_ssize_t end = self->size;
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +0200283 Py_buffer view;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 CHECK_VALID(NULL);
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +0200286 if (!PyArg_ParseTuple(args, reverse ? "y*|nn:rfind" : "y*|nn:find",
287 &view, &start, &end)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 return NULL;
289 } else {
290 const char *p, *start_p, *end_p;
291 int sign = reverse ? -1 : 1;
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +0200292 const char *needle = view.buf;
293 Py_ssize_t len = view.len;
Greg Stein834f4dd2001-05-14 09:32:26 +0000294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 if (start < 0)
296 start += self->size;
297 if (start < 0)
298 start = 0;
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700299 else if (start > self->size)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 start = self->size;
Greg Stein834f4dd2001-05-14 09:32:26 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 if (end < 0)
303 end += self->size;
304 if (end < 0)
305 end = 0;
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700306 else if (end > self->size)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 end = self->size;
Georg Brandlfceab5a2008-01-19 20:08:23 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 start_p = self->data + start;
310 end_p = self->data + end;
Georg Brandlfceab5a2008-01-19 20:08:23 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 for (p = (reverse ? end_p - len : start_p);
313 (p >= start_p) && (p + len <= end_p); p += sign) {
314 Py_ssize_t i;
315 for (i = 0; i < len && needle[i] == p[i]; ++i)
316 /* nothing */;
317 if (i == len) {
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +0200318 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 return PyLong_FromSsize_t(p - self->data);
320 }
321 }
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +0200322 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 return PyLong_FromLong(-1);
324 }
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000325}
326
Georg Brandlfceab5a2008-01-19 20:08:23 +0000327static PyObject *
328mmap_find_method(mmap_object *self,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 PyObject *args)
Georg Brandlfceab5a2008-01-19 20:08:23 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 return mmap_gfind(self, args, 0);
Georg Brandlfceab5a2008-01-19 20:08:23 +0000332}
333
334static PyObject *
335mmap_rfind_method(mmap_object *self,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 PyObject *args)
Georg Brandlfceab5a2008-01-19 20:08:23 +0000337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 return mmap_gfind(self, args, 1);
Georg Brandlfceab5a2008-01-19 20:08:23 +0000339}
340
Tim Petersec0a5f02006-02-16 23:47:20 +0000341static int
Sean Reifscheider54cf12b2007-09-17 17:55:36 +0000342is_writable(mmap_object *self)
Tim Peters5ebfd362001-11-13 23:11:19 +0000343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 if (self->access != ACCESS_READ)
345 return 1;
346 PyErr_Format(PyExc_TypeError, "mmap can't modify a readonly memory map.");
347 return 0;
Tim Peters5ebfd362001-11-13 23:11:19 +0000348}
349
Tim Petersec0a5f02006-02-16 23:47:20 +0000350static int
Tim Peters5ebfd362001-11-13 23:11:19 +0000351is_resizeable(mmap_object *self)
352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 if (self->exports > 0) {
354 PyErr_SetString(PyExc_BufferError,
355 "mmap can't resize with extant buffers exported.");
356 return 0;
357 }
358 if ((self->access == ACCESS_WRITE) || (self->access == ACCESS_DEFAULT))
359 return 1;
360 PyErr_Format(PyExc_TypeError,
361 "mmap can't resize a readonly or copy-on-write memory map.");
362 return 0;
Tim Peters5ebfd362001-11-13 23:11:19 +0000363}
364
365
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000366static PyObject *
Fredrik Lundh54cf3dc2000-07-08 22:05:01 +0000367mmap_write_method(mmap_object *self,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 PyObject *args)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000369{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +0200370 Py_buffer data;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 CHECK_VALID(NULL);
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +0200373 if (!PyArg_ParseTuple(args, "y*:write", &data))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 return(NULL);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000375
Benjamin Peterson37768362016-10-05 23:29:07 -0700376 if (!is_writable(self)) {
377 PyBuffer_Release(&data);
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700378 return NULL;
Benjamin Peterson37768362016-10-05 23:29:07 -0700379 }
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700380
381 if (self->pos > self->size || self->size - self->pos < data.len) {
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +0200382 PyBuffer_Release(&data);
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700383 PyErr_SetString(PyExc_ValueError, "data out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 return NULL;
385 }
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +0200386
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700387 memcpy(&self->data[self->pos], data.buf, data.len);
388 self->pos += data.len;
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +0200389 PyBuffer_Release(&data);
Benjamin Peterson87845bc2016-10-05 22:54:19 -0700390 return PyLong_FromSsize_t(data.len);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000391}
392
393static PyObject *
Fredrik Lundh54cf3dc2000-07-08 22:05:01 +0000394mmap_write_byte_method(mmap_object *self,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 PyObject *args)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 char value;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 CHECK_VALID(NULL);
400 if (!PyArg_ParseTuple(args, "b:write_byte", &value))
401 return(NULL);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 if (!is_writable(self))
404 return NULL;
Hirokazu Yamamoto39c6dea2009-02-28 10:56:50 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 if (self->pos < self->size) {
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700407 self->data[self->pos++] = value;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200408 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 }
410 else {
411 PyErr_SetString(PyExc_ValueError, "write byte out of range");
412 return NULL;
413 }
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000414}
Tim Petersec0a5f02006-02-16 23:47:20 +0000415
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000416static PyObject *
Fredrik Lundh54cf3dc2000-07-08 22:05:01 +0000417mmap_size_method(mmap_object *self,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 PyObject *unused)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 CHECK_VALID(NULL);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000421
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000422#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 if (self->file_handle != INVALID_HANDLE_VALUE) {
424 DWORD low,high;
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700425 long long size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 low = GetFileSize(self->file_handle, &high);
427 if (low == INVALID_FILE_SIZE) {
428 /* It might be that the function appears to have failed,
429 when indeed its size equals INVALID_FILE_SIZE */
430 DWORD error = GetLastError();
431 if (error != NO_ERROR)
432 return PyErr_SetFromWindowsErr(error);
433 }
434 if (!high && low < LONG_MAX)
435 return PyLong_FromLong((long)low);
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700436 size = (((long long)high)<<32) + low;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 return PyLong_FromLongLong(size);
438 } else {
439 return PyLong_FromSsize_t(self->size);
440 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000441#endif /* MS_WINDOWS */
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000442
443#ifdef UNIX
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 {
Victor Stinnere134a7f2015-03-30 10:09:31 +0200445 struct _Py_stat_struct status;
446 if (_Py_fstat(self->fd, &status) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 return NULL;
Antoine Pitrou97696cb2011-02-21 23:46:27 +0000448#ifdef HAVE_LARGEFILE_SUPPORT
Victor Stinnere134a7f2015-03-30 10:09:31 +0200449 return PyLong_FromLongLong(status.st_size);
Antoine Pitrou97696cb2011-02-21 23:46:27 +0000450#else
Victor Stinnere134a7f2015-03-30 10:09:31 +0200451 return PyLong_FromLong(status.st_size);
Antoine Pitrou97696cb2011-02-21 23:46:27 +0000452#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 }
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000454#endif /* UNIX */
455}
456
457/* This assumes that you want the entire file mapped,
458 / and when recreating the map will make the new file
459 / have the new size
460 /
461 / Is this really necessary? This could easily be done
462 / from python by just closing and re-opening with the
463 / new size?
464 */
465
466static PyObject *
Fredrik Lundh54cf3dc2000-07-08 22:05:01 +0000467mmap_resize_method(mmap_object *self,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 PyObject *args)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 Py_ssize_t new_size;
471 CHECK_VALID(NULL);
472 if (!PyArg_ParseTuple(args, "n:resize", &new_size) ||
473 !is_resizeable(self)) {
474 return NULL;
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700475 }
476 if (new_size < 0 || PY_SSIZE_T_MAX - new_size < self->offset) {
477 PyErr_SetString(PyExc_ValueError, "new size out of range");
478 return NULL;
479 }
480
481 {
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000482#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 DWORD dwErrCode = 0;
484 DWORD off_hi, off_lo, newSizeLow, newSizeHigh;
485 /* First, unmap the file view */
486 UnmapViewOfFile(self->data);
487 self->data = NULL;
488 /* Close the mapping object */
489 CloseHandle(self->map_handle);
490 self->map_handle = NULL;
491 /* Move to the desired EOF position */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 newSizeHigh = (DWORD)((self->offset + new_size) >> 32);
493 newSizeLow = (DWORD)((self->offset + new_size) & 0xFFFFFFFF);
494 off_hi = (DWORD)(self->offset >> 32);
495 off_lo = (DWORD)(self->offset & 0xFFFFFFFF);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 SetFilePointer(self->file_handle,
497 newSizeLow, &newSizeHigh, FILE_BEGIN);
498 /* Change the size of the file */
499 SetEndOfFile(self->file_handle);
500 /* Create another mapping object and remap the file view */
501 self->map_handle = CreateFileMapping(
502 self->file_handle,
503 NULL,
504 PAGE_READWRITE,
505 0,
506 0,
507 self->tagname);
508 if (self->map_handle != NULL) {
509 self->data = (char *) MapViewOfFile(self->map_handle,
510 FILE_MAP_WRITE,
511 off_hi,
512 off_lo,
513 new_size);
514 if (self->data != NULL) {
515 self->size = new_size;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200516 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 } else {
518 dwErrCode = GetLastError();
519 CloseHandle(self->map_handle);
520 self->map_handle = NULL;
521 }
522 } else {
523 dwErrCode = GetLastError();
524 }
525 PyErr_SetFromWindowsErr(dwErrCode);
526 return NULL;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000527#endif /* MS_WINDOWS */
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000528
529#ifdef UNIX
Tim Petersec0a5f02006-02-16 23:47:20 +0000530#ifndef HAVE_MREMAP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 PyErr_SetString(PyExc_SystemError,
532 "mmap: resizing not available--no mremap()");
533 return NULL;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000534#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 void *newmap;
Armin Rigo335ffe82005-09-20 19:04:02 +0000536
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700537 if (self->fd != -1 && ftruncate(self->fd, self->offset + new_size) == -1) {
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200538 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 return NULL;
540 }
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000541
Andrew M. Kuchling6fef30e2000-06-18 14:51:21 +0000542#ifdef MREMAP_MAYMOVE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 newmap = mremap(self->data, self->size, new_size, MREMAP_MAYMOVE);
Andrew M. Kuchling6fef30e2000-06-18 14:51:21 +0000544#else
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700545#if defined(__NetBSD__)
546 newmap = mremap(self->data, self->size, self->data, new_size, 0);
547#else
548 newmap = mremap(self->data, self->size, new_size, 0);
549#endif /* __NetBSD__ */
Andrew M. Kuchling6fef30e2000-06-18 14:51:21 +0000550#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 if (newmap == (void *)-1)
552 {
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200553 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 return NULL;
555 }
556 self->data = newmap;
557 self->size = new_size;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200558 Py_RETURN_NONE;
Andrew M. Kuchling6fef30e2000-06-18 14:51:21 +0000559#endif /* HAVE_MREMAP */
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000560#endif /* UNIX */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 }
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000562}
563
564static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000565mmap_tell_method(mmap_object *self, PyObject *unused)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 CHECK_VALID(NULL);
568 return PyLong_FromSize_t(self->pos);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000569}
570
571static PyObject *
Fredrik Lundh54cf3dc2000-07-08 22:05:01 +0000572mmap_flush_method(mmap_object *self, PyObject *args)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 Py_ssize_t offset = 0;
575 Py_ssize_t size = self->size;
576 CHECK_VALID(NULL);
577 if (!PyArg_ParseTuple(args, "|nn:flush", &offset, &size))
578 return NULL;
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700579 if (size < 0 || offset < 0 || self->size - offset < size) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 PyErr_SetString(PyExc_ValueError, "flush values out of range");
581 return NULL;
582 }
R. David Murraye194dd62010-10-18 01:14:06 +0000583
584 if (self->access == ACCESS_READ || self->access == ACCESS_COPY)
Berker Peksage7d4b2f2018-08-22 21:21:05 +0300585 Py_RETURN_NONE;
R. David Murraye194dd62010-10-18 01:14:06 +0000586
Christian Heimesaf98da12008-01-27 15:18:18 +0000587#ifdef MS_WINDOWS
Berker Peksage7d4b2f2018-08-22 21:21:05 +0300588 if (!FlushViewOfFile(self->data+offset, size)) {
589 PyErr_SetFromWindowsErr(GetLastError());
590 return NULL;
591 }
592 Py_RETURN_NONE;
Christian Heimesaf98da12008-01-27 15:18:18 +0000593#elif defined(UNIX)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 /* XXX flags for msync? */
595 if (-1 == msync(self->data + offset, size, MS_SYNC)) {
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200596 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 return NULL;
598 }
Berker Peksage7d4b2f2018-08-22 21:21:05 +0300599 Py_RETURN_NONE;
Christian Heimesaf98da12008-01-27 15:18:18 +0000600#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 PyErr_SetString(PyExc_ValueError, "flush not supported on this system");
602 return NULL;
Christian Heimesaf98da12008-01-27 15:18:18 +0000603#endif
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000604}
605
606static PyObject *
Fredrik Lundh54cf3dc2000-07-08 22:05:01 +0000607mmap_seek_method(mmap_object *self, PyObject *args)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 Py_ssize_t dist;
610 int how=0;
611 CHECK_VALID(NULL);
612 if (!PyArg_ParseTuple(args, "n|i:seek", &dist, &how))
613 return NULL;
614 else {
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700615 Py_ssize_t where;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 switch (how) {
617 case 0: /* relative to start */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 where = dist;
619 break;
620 case 1: /* relative to current position */
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700621 if (PY_SSIZE_T_MAX - self->pos < dist)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 goto onoutofrange;
623 where = self->pos + dist;
624 break;
625 case 2: /* relative to end */
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700626 if (PY_SSIZE_T_MAX - self->size < dist)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 goto onoutofrange;
628 where = self->size + dist;
629 break;
630 default:
631 PyErr_SetString(PyExc_ValueError, "unknown seek type");
632 return NULL;
633 }
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700634 if (where > self->size || where < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 goto onoutofrange;
636 self->pos = where;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200637 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 }
Andrew M. Kuchling70d27422000-06-18 04:45:14 +0000639
Tim Peters5ebfd362001-11-13 23:11:19 +0000640 onoutofrange:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 PyErr_SetString(PyExc_ValueError, "seek out of range");
642 return NULL;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000643}
644
645static PyObject *
Fredrik Lundh54cf3dc2000-07-08 22:05:01 +0000646mmap_move_method(mmap_object *self, PyObject *args)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000647{
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700648 Py_ssize_t dest, src, cnt;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 CHECK_VALID(NULL);
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700650 if (!PyArg_ParseTuple(args, "nnn:move", &dest, &src, &cnt) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 !is_writable(self)) {
652 return NULL;
653 } else {
654 /* bounds check the values */
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700655 if (dest < 0 || src < 0 || cnt < 0)
656 goto bounds;
657 if (self->size - dest < cnt || self->size - src < cnt)
658 goto bounds;
659
660 memmove(&self->data[dest], &self->data[src], cnt);
661
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200662 Py_RETURN_NONE;
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700663
664 bounds:
665 PyErr_SetString(PyExc_ValueError,
666 "source, destination, or count out of range");
667 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 }
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000669}
670
Georg Brandl0bccc182010-08-01 14:50:00 +0000671static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200672mmap_closed_get(mmap_object *self, void *Py_UNUSED(ignored))
Georg Brandl0bccc182010-08-01 14:50:00 +0000673{
674#ifdef MS_WINDOWS
675 return PyBool_FromLong(self->map_handle == NULL ? 1 : 0);
676#elif defined(UNIX)
677 return PyBool_FromLong(self->data == NULL ? 1 : 0);
678#endif
679}
680
681static PyObject *
682mmap__enter__method(mmap_object *self, PyObject *args)
683{
684 CHECK_VALID(NULL);
685
686 Py_INCREF(self);
687 return (PyObject *)self;
688}
689
690static PyObject *
691mmap__exit__method(PyObject *self, PyObject *args)
692{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200693 _Py_IDENTIFIER(close);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200694
695 return _PyObject_CallMethodId(self, &PyId_close, NULL);
Georg Brandl0bccc182010-08-01 14:50:00 +0000696}
697
Serhiy Storchaka76b47652014-08-19 17:11:20 +0300698#ifdef MS_WINDOWS
699static PyObject *
700mmap__sizeof__method(mmap_object *self, void *unused)
701{
702 Py_ssize_t res;
703
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +0200704 res = _PyObject_SIZE(Py_TYPE(self));
Serhiy Storchaka76b47652014-08-19 17:11:20 +0300705 if (self->tagname)
706 res += strlen(self->tagname) + 1;
707 return PyLong_FromSsize_t(res);
708}
709#endif
710
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000711static struct PyMethodDef mmap_object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 {"close", (PyCFunction) mmap_close_method, METH_NOARGS},
713 {"find", (PyCFunction) mmap_find_method, METH_VARARGS},
714 {"rfind", (PyCFunction) mmap_rfind_method, METH_VARARGS},
715 {"flush", (PyCFunction) mmap_flush_method, METH_VARARGS},
716 {"move", (PyCFunction) mmap_move_method, METH_VARARGS},
717 {"read", (PyCFunction) mmap_read_method, METH_VARARGS},
718 {"read_byte", (PyCFunction) mmap_read_byte_method, METH_NOARGS},
719 {"readline", (PyCFunction) mmap_read_line_method, METH_NOARGS},
720 {"resize", (PyCFunction) mmap_resize_method, METH_VARARGS},
721 {"seek", (PyCFunction) mmap_seek_method, METH_VARARGS},
722 {"size", (PyCFunction) mmap_size_method, METH_NOARGS},
723 {"tell", (PyCFunction) mmap_tell_method, METH_NOARGS},
724 {"write", (PyCFunction) mmap_write_method, METH_VARARGS},
725 {"write_byte", (PyCFunction) mmap_write_byte_method, METH_VARARGS},
Georg Brandl0bccc182010-08-01 14:50:00 +0000726 {"__enter__", (PyCFunction) mmap__enter__method, METH_NOARGS},
727 {"__exit__", (PyCFunction) mmap__exit__method, METH_VARARGS},
Serhiy Storchaka76b47652014-08-19 17:11:20 +0300728#ifdef MS_WINDOWS
729 {"__sizeof__", (PyCFunction) mmap__sizeof__method, METH_NOARGS},
730#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 {NULL, NULL} /* sentinel */
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000732};
733
Georg Brandl0bccc182010-08-01 14:50:00 +0000734static PyGetSetDef mmap_object_getset[] = {
735 {"closed", (getter) mmap_closed_get, NULL, NULL},
736 {NULL}
737};
738
739
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000740/* Functions for treating an mmap'ed file as a buffer */
741
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000742static int
Guido van Rossum98297ee2007-11-06 21:34:58 +0000743mmap_buffer_getbuf(mmap_object *self, Py_buffer *view, int flags)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 CHECK_VALID(-1);
746 if (PyBuffer_FillInfo(view, (PyObject*)self, self->data, self->size,
747 (self->access == ACCESS_READ), flags) < 0)
748 return -1;
749 self->exports++;
750 return 0;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000751}
752
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000753static void
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000754mmap_buffer_releasebuf(mmap_object *self, Py_buffer *view)
Tim Petersec0a5f02006-02-16 23:47:20 +0000755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 self->exports--;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000757}
758
Martin v. Löwis18e16552006-02-15 17:27:45 +0000759static Py_ssize_t
Fredrik Lundh54cf3dc2000-07-08 22:05:01 +0000760mmap_length(mmap_object *self)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 CHECK_VALID(-1);
763 return self->size;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000764}
765
766static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000767mmap_item(mmap_object *self, Py_ssize_t i)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 CHECK_VALID(NULL);
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700770 if (i < 0 || i >= self->size) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 PyErr_SetString(PyExc_IndexError, "mmap index out of range");
772 return NULL;
773 }
774 return PyBytes_FromStringAndSize(self->data + i, 1);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000775}
776
777static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000778mmap_subscript(mmap_object *self, PyObject *item)
779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 CHECK_VALID(NULL);
781 if (PyIndex_Check(item)) {
782 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
783 if (i == -1 && PyErr_Occurred())
784 return NULL;
785 if (i < 0)
786 i += self->size;
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700787 if (i < 0 || i >= self->size) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 PyErr_SetString(PyExc_IndexError,
789 "mmap index out of range");
790 return NULL;
791 }
792 return PyLong_FromLong(Py_CHARMASK(self->data[i]));
793 }
794 else if (PySlice_Check(item)) {
795 Py_ssize_t start, stop, step, slicelen;
Thomas Woutersed03b412007-08-28 21:37:11 +0000796
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300797 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 return NULL;
799 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300800 slicelen = PySlice_AdjustIndices(self->size, &start, &stop, step);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 if (slicelen <= 0)
803 return PyBytes_FromStringAndSize("", 0);
804 else if (step == 1)
805 return PyBytes_FromStringAndSize(self->data + start,
806 slicelen);
807 else {
808 char *result_buf = (char *)PyMem_Malloc(slicelen);
Zackery Spytz14514d92019-05-17 01:13:03 -0600809 size_t cur;
810 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 PyObject *result;
Thomas Woutersed03b412007-08-28 21:37:11 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 if (result_buf == NULL)
814 return PyErr_NoMemory();
815 for (cur = start, i = 0; i < slicelen;
816 cur += step, i++) {
817 result_buf[i] = self->data[cur];
818 }
819 result = PyBytes_FromStringAndSize(result_buf,
820 slicelen);
821 PyMem_Free(result_buf);
822 return result;
823 }
824 }
825 else {
826 PyErr_SetString(PyExc_TypeError,
827 "mmap indices must be integers");
828 return NULL;
829 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000830}
831
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000832static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000833mmap_ass_item(mmap_object *self, Py_ssize_t i, PyObject *v)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 const char *buf;
Tim Petersec0a5f02006-02-16 23:47:20 +0000836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 CHECK_VALID(-1);
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700838 if (i < 0 || i >= self->size) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 PyErr_SetString(PyExc_IndexError, "mmap index out of range");
840 return -1;
841 }
842 if (v == NULL) {
843 PyErr_SetString(PyExc_TypeError,
844 "mmap object doesn't support item deletion");
845 return -1;
846 }
847 if (! (PyBytes_Check(v) && PyBytes_Size(v)==1) ) {
848 PyErr_SetString(PyExc_IndexError,
849 "mmap assignment must be length-1 bytes()");
850 return -1;
851 }
852 if (!is_writable(self))
853 return -1;
854 buf = PyBytes_AsString(v);
855 self->data[i] = buf[0];
856 return 0;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000857}
858
Thomas Woutersed03b412007-08-28 21:37:11 +0000859static int
860mmap_ass_subscript(mmap_object *self, PyObject *item, PyObject *value)
861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 CHECK_VALID(-1);
Thomas Woutersed03b412007-08-28 21:37:11 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (!is_writable(self))
865 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 if (PyIndex_Check(item)) {
868 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
869 Py_ssize_t v;
Thomas Woutersed03b412007-08-28 21:37:11 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 if (i == -1 && PyErr_Occurred())
872 return -1;
873 if (i < 0)
874 i += self->size;
Benjamin Petersoncd04db02016-10-05 21:45:48 -0700875 if (i < 0 || i >= self->size) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 PyErr_SetString(PyExc_IndexError,
877 "mmap index out of range");
878 return -1;
879 }
880 if (value == NULL) {
881 PyErr_SetString(PyExc_TypeError,
882 "mmap doesn't support item deletion");
883 return -1;
884 }
885 if (!PyIndex_Check(value)) {
886 PyErr_SetString(PyExc_TypeError,
887 "mmap item value must be an int");
888 return -1;
889 }
890 v = PyNumber_AsSsize_t(value, PyExc_TypeError);
891 if (v == -1 && PyErr_Occurred())
892 return -1;
893 if (v < 0 || v > 255) {
894 PyErr_SetString(PyExc_ValueError,
895 "mmap item value must be "
896 "in range(0, 256)");
897 return -1;
898 }
Antoine Pitrou22e41552010-08-15 18:07:50 +0000899 self->data[i] = (char) v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 return 0;
901 }
902 else if (PySlice_Check(item)) {
903 Py_ssize_t start, stop, step, slicelen;
904 Py_buffer vbuf;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000905
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300906 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 return -1;
908 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300909 slicelen = PySlice_AdjustIndices(self->size, &start, &stop, step);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 if (value == NULL) {
911 PyErr_SetString(PyExc_TypeError,
912 "mmap object doesn't support slice deletion");
913 return -1;
914 }
915 if (PyObject_GetBuffer(value, &vbuf, PyBUF_SIMPLE) < 0)
916 return -1;
917 if (vbuf.len != slicelen) {
918 PyErr_SetString(PyExc_IndexError,
919 "mmap slice assignment is wrong size");
920 PyBuffer_Release(&vbuf);
921 return -1;
922 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (slicelen == 0) {
925 }
926 else if (step == 1) {
927 memcpy(self->data + start, vbuf.buf, slicelen);
928 }
929 else {
Zackery Spytz14514d92019-05-17 01:13:03 -0600930 size_t cur;
931 Py_ssize_t i;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 for (cur = start, i = 0;
934 i < slicelen;
935 cur += step, i++)
936 {
937 self->data[cur] = ((char *)vbuf.buf)[i];
938 }
939 }
940 PyBuffer_Release(&vbuf);
941 return 0;
942 }
943 else {
944 PyErr_SetString(PyExc_TypeError,
945 "mmap indices must be integer");
946 return -1;
947 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000948}
949
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000950static PySequenceMethods mmap_as_sequence = {
Stefan Krah23186992012-03-06 15:37:36 +0100951 (lenfunc)mmap_length, /*sq_length*/
Zackery Spytze9e39762018-06-05 06:59:41 -0600952 0, /*sq_concat*/
953 0, /*sq_repeat*/
Stefan Krah23186992012-03-06 15:37:36 +0100954 (ssizeargfunc)mmap_item, /*sq_item*/
955 0, /*sq_slice*/
956 (ssizeobjargproc)mmap_ass_item, /*sq_ass_item*/
957 0, /*sq_ass_slice*/
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000958};
959
Thomas Woutersed03b412007-08-28 21:37:11 +0000960static PyMappingMethods mmap_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 (lenfunc)mmap_length,
962 (binaryfunc)mmap_subscript,
963 (objobjargproc)mmap_ass_subscript,
Thomas Woutersed03b412007-08-28 21:37:11 +0000964};
965
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000966static PyBufferProcs mmap_as_buffer = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 (getbufferproc)mmap_buffer_getbuf,
968 (releasebufferproc)mmap_buffer_releasebuf,
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000969};
970
Georg Brandl86def6c2008-01-21 20:36:10 +0000971static PyObject *
972new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict);
973
Christian Heimese1c98112008-01-21 11:20:28 +0000974PyDoc_STRVAR(mmap_doc,
975"Windows: mmap(fileno, length[, tagname[, access[, offset]]])\n\
976\n\
977Maps length bytes from the file specified by the file handle fileno,\n\
978and returns a mmap object. If length is larger than the current size\n\
979of the file, the file is extended to contain length bytes. If length\n\
980is 0, the maximum length of the map is the current size of the file,\n\
981except that if the file is empty Windows raises an exception (you cannot\n\
982create an empty mapping on Windows).\n\
983\n\
984Unix: mmap(fileno, length[, flags[, prot[, access[, offset]]]])\n\
985\n\
986Maps length bytes from the file specified by the file descriptor fileno,\n\
987and returns a mmap object. If length is 0, the maximum length of the map\n\
988will be the current size of the file when mmap is called.\n\
989flags specifies the nature of the mapping. MAP_PRIVATE creates a\n\
990private copy-on-write mapping, so changes to the contents of the mmap\n\
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000991object will be private to this process, and MAP_SHARED creates a mapping\n\
Christian Heimese1c98112008-01-21 11:20:28 +0000992that's shared with all other processes mapping the same areas of the file.\n\
993The default value is MAP_SHARED.\n\
994\n\
995To map anonymous memory, pass -1 as the fileno (both versions).");
996
997
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +0000998static PyTypeObject mmap_object_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 PyVarObject_HEAD_INIT(NULL, 0)
1000 "mmap.mmap", /* tp_name */
Peter Eisentraut0e0bc4e2018-09-10 18:46:08 +02001001 sizeof(mmap_object), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 0, /* tp_itemsize */
1003 /* methods */
1004 (destructor) mmap_object_dealloc, /* tp_dealloc */
1005 0, /* tp_print */
1006 0, /* tp_getattr */
1007 0, /* tp_setattr */
1008 0, /* tp_reserved */
1009 0, /* tp_repr */
1010 0, /* tp_as_number */
1011 &mmap_as_sequence, /*tp_as_sequence*/
1012 &mmap_as_mapping, /*tp_as_mapping*/
1013 0, /*tp_hash*/
1014 0, /*tp_call*/
1015 0, /*tp_str*/
1016 PyObject_GenericGetAttr, /*tp_getattro*/
1017 0, /*tp_setattro*/
1018 &mmap_as_buffer, /*tp_as_buffer*/
Stefan Krah23186992012-03-06 15:37:36 +01001019 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 mmap_doc, /*tp_doc*/
1021 0, /* tp_traverse */
1022 0, /* tp_clear */
1023 0, /* tp_richcompare */
Antoine Pitrouc53204b2013-08-05 23:17:30 +02001024 offsetof(mmap_object, weakreflist), /* tp_weaklistoffset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 0, /* tp_iter */
1026 0, /* tp_iternext */
1027 mmap_object_methods, /* tp_methods */
1028 0, /* tp_members */
Georg Brandl0bccc182010-08-01 14:50:00 +00001029 mmap_object_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 0, /* tp_base */
1031 0, /* tp_dict */
1032 0, /* tp_descr_get */
1033 0, /* tp_descr_set */
1034 0, /* tp_dictoffset */
Stefan Krah23186992012-03-06 15:37:36 +01001035 0, /* tp_init */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 PyType_GenericAlloc, /* tp_alloc */
1037 new_mmap_object, /* tp_new */
Stefan Krah23186992012-03-06 15:37:36 +01001038 PyObject_Del, /* tp_free */
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001039};
1040
Andrew M. Kuchling70d27422000-06-18 04:45:14 +00001041
Tim Petersec0a5f02006-02-16 23:47:20 +00001042#ifdef UNIX
Antoine Pitrou97696cb2011-02-21 23:46:27 +00001043#ifdef HAVE_LARGEFILE_SUPPORT
1044#define _Py_PARSE_OFF_T "L"
1045#else
1046#define _Py_PARSE_OFF_T "l"
1047#endif
1048
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001049static PyObject *
Georg Brandl86def6c2008-01-21 20:36:10 +00001050new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001051{
Victor Stinnere134a7f2015-03-30 10:09:31 +02001052 struct _Py_stat_struct status;
Zackery Spytzd6e14042018-03-14 14:08:01 -06001053 int fstat_result = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 mmap_object *m_obj;
Antoine Pitrou97696cb2011-02-21 23:46:27 +00001055 Py_ssize_t map_size;
1056 off_t offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ;
1058 int devzero = -1;
1059 int access = (int)ACCESS_DEFAULT;
1060 static char *keywords[] = {"fileno", "length",
Stefan Krah23186992012-03-06 15:37:36 +01001061 "flags", "prot",
1062 "access", "offset", NULL};
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001063
Benjamin Petersoncd04db02016-10-05 21:45:48 -07001064 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "in|iii" _Py_PARSE_OFF_T, keywords,
1065 &fd, &map_size, &flags, &prot,
Antoine Pitrou97696cb2011-02-21 23:46:27 +00001066 &access, &offset))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 return NULL;
Benjamin Petersoncd04db02016-10-05 21:45:48 -07001068 if (map_size < 0) {
1069 PyErr_SetString(PyExc_OverflowError,
Zackery Spytz9308dea2018-03-21 00:02:37 -06001070 "memory mapped length must be positive");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 return NULL;
Benjamin Petersoncd04db02016-10-05 21:45:48 -07001072 }
Antoine Pitrou97696cb2011-02-21 23:46:27 +00001073 if (offset < 0) {
1074 PyErr_SetString(PyExc_OverflowError,
1075 "memory mapped offset must be positive");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 return NULL;
Antoine Pitrou97696cb2011-02-21 23:46:27 +00001077 }
Tim Peters5ebfd362001-11-13 23:11:19 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 if ((access != (int)ACCESS_DEFAULT) &&
1080 ((flags != MAP_SHARED) || (prot != (PROT_WRITE | PROT_READ))))
1081 return PyErr_Format(PyExc_ValueError,
1082 "mmap can't specify both access and flags, prot.");
1083 switch ((access_mode)access) {
1084 case ACCESS_READ:
1085 flags = MAP_SHARED;
1086 prot = PROT_READ;
1087 break;
1088 case ACCESS_WRITE:
1089 flags = MAP_SHARED;
1090 prot = PROT_READ | PROT_WRITE;
1091 break;
1092 case ACCESS_COPY:
1093 flags = MAP_PRIVATE;
1094 prot = PROT_READ | PROT_WRITE;
1095 break;
1096 case ACCESS_DEFAULT:
Antoine Pitrou16a0a0b2011-03-06 01:11:03 +01001097 /* map prot to access type */
1098 if ((prot & PROT_READ) && (prot & PROT_WRITE)) {
1099 /* ACCESS_DEFAULT */
1100 }
1101 else if (prot & PROT_WRITE) {
1102 access = ACCESS_WRITE;
1103 }
1104 else {
1105 access = ACCESS_READ;
1106 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 break;
1108 default:
1109 return PyErr_Format(PyExc_ValueError,
1110 "mmap invalid access parameter.");
1111 }
Neal Norwitzb5673922002-09-05 21:48:07 +00001112
Victor Stinnera6cd0cf2011-05-02 01:05:37 +02001113#ifdef __APPLE__
1114 /* Issue #11277: fsync(2) is not enough on OS X - a special, OS X specific
1115 fcntl(2) is necessary to force DISKSYNC and get around mmap(2) bug */
1116 if (fd != -1)
1117 (void)fcntl(fd, F_FULLFSYNC);
1118#endif
Nir Soffer4484f9d2018-03-12 01:39:22 +02001119
1120 if (fd != -1) {
1121 Py_BEGIN_ALLOW_THREADS
1122 fstat_result = _Py_fstat_noraise(fd, &status);
1123 Py_END_ALLOW_THREADS
1124 }
1125
1126 if (fd != -1 && fstat_result == 0 && S_ISREG(status.st_mode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 if (map_size == 0) {
Victor Stinnere134a7f2015-03-30 10:09:31 +02001128 if (status.st_size == 0) {
Jesus Cea941bfcc2012-09-10 00:27:55 +02001129 PyErr_SetString(PyExc_ValueError,
1130 "cannot mmap an empty file");
1131 return NULL;
1132 }
Victor Stinnere134a7f2015-03-30 10:09:31 +02001133 if (offset >= status.st_size) {
Antoine Pitrou305bc9e2011-01-20 21:07:24 +00001134 PyErr_SetString(PyExc_ValueError,
1135 "mmap offset is greater than file size");
1136 return NULL;
1137 }
Victor Stinnere134a7f2015-03-30 10:09:31 +02001138 if (status.st_size - offset > PY_SSIZE_T_MAX) {
Antoine Pitrou97696cb2011-02-21 23:46:27 +00001139 PyErr_SetString(PyExc_ValueError,
1140 "mmap length is too large");
Richard Oudkerk0d09ba82013-02-13 12:18:03 +00001141 return NULL;
1142 }
Victor Stinnere134a7f2015-03-30 10:09:31 +02001143 map_size = (Py_ssize_t) (status.st_size - offset);
Benjamin Petersoncd04db02016-10-05 21:45:48 -07001144 } else if (offset > status.st_size || status.st_size - offset < map_size) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyErr_SetString(PyExc_ValueError,
1146 "mmap length is greater than file size");
1147 return NULL;
1148 }
1149 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 m_obj = (mmap_object *)type->tp_alloc(type, 0);
1151 if (m_obj == NULL) {return NULL;}
1152 m_obj->data = NULL;
Benjamin Petersoncd04db02016-10-05 21:45:48 -07001153 m_obj->size = map_size;
1154 m_obj->pos = 0;
Antoine Pitrouc53204b2013-08-05 23:17:30 +02001155 m_obj->weakreflist = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 m_obj->exports = 0;
1157 m_obj->offset = offset;
1158 if (fd == -1) {
1159 m_obj->fd = -1;
1160 /* Assume the caller wants to map anonymous memory.
1161 This is the same behaviour as Windows. mmap.mmap(-1, size)
1162 on both Windows and Unix map anonymous memory.
1163 */
Neal Norwitz0e6bc8c2006-02-05 05:45:43 +00001164#ifdef MAP_ANONYMOUS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 /* BSD way to map anonymous memory */
1166 flags |= MAP_ANONYMOUS;
Lihua Zhao4fb15022019-05-21 18:50:14 +08001167
1168 /* VxWorks only supports MAP_ANONYMOUS with MAP_PRIVATE flag */
1169#ifdef __VXWORKS__
1170 flags &= ~MAP_SHARED;
1171 flags |= MAP_PRIVATE;
1172#endif
1173
Neal Norwitz0e6bc8c2006-02-05 05:45:43 +00001174#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 /* SVR4 method to map anonymous memory is to open /dev/zero */
Victor Stinnerdaf45552013-08-28 00:53:59 +02001176 fd = devzero = _Py_open("/dev/zero", O_RDWR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (devzero == -1) {
1178 Py_DECREF(m_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 return NULL;
1180 }
Neal Norwitz0e6bc8c2006-02-05 05:45:43 +00001181#endif
Victor Stinnerdaf45552013-08-28 00:53:59 +02001182 }
1183 else {
1184 m_obj->fd = _Py_dup(fd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 if (m_obj->fd == -1) {
1186 Py_DECREF(m_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 return NULL;
1188 }
1189 }
Neal Norwitz0e6bc8c2006-02-05 05:45:43 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 m_obj->data = mmap(NULL, map_size,
1192 prot, flags,
1193 fd, offset);
Neal Norwitz0e6bc8c2006-02-05 05:45:43 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 if (devzero != -1) {
1196 close(devzero);
1197 }
1198
1199 if (m_obj->data == (char *)-1) {
1200 m_obj->data = NULL;
1201 Py_DECREF(m_obj);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001202 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 return NULL;
1204 }
1205 m_obj->access = (access_mode)access;
1206 return (PyObject *)m_obj;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001207}
1208#endif /* UNIX */
1209
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001210#ifdef MS_WINDOWS
Antoine Pitrou97696cb2011-02-21 23:46:27 +00001211
1212/* A note on sizes and offsets: while the actual map size must hold in a
1213 Py_ssize_t, both the total file size and the start offset can be longer
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001214 than a Py_ssize_t, so we use long long which is always 64-bit.
Antoine Pitrou97696cb2011-02-21 23:46:27 +00001215*/
1216
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001217static PyObject *
Georg Brandl86def6c2008-01-21 20:36:10 +00001218new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 mmap_object *m_obj;
Antoine Pitrou97696cb2011-02-21 23:46:27 +00001221 Py_ssize_t map_size;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001222 long long offset = 0, size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 DWORD off_hi; /* upper 32 bits of offset */
1224 DWORD off_lo; /* lower 32 bits of offset */
1225 DWORD size_hi; /* upper 32 bits of size */
1226 DWORD size_lo; /* lower 32 bits of size */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001227 const char *tagname = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 DWORD dwErr = 0;
1229 int fileno;
1230 HANDLE fh = 0;
1231 int access = (access_mode)ACCESS_DEFAULT;
1232 DWORD flProtect, dwDesiredAccess;
1233 static char *keywords[] = { "fileno", "length",
Stefan Krah23186992012-03-06 15:37:36 +01001234 "tagname",
1235 "access", "offset", NULL };
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001236
Benjamin Petersoncd04db02016-10-05 21:45:48 -07001237 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "in|ziL", keywords,
1238 &fileno, &map_size,
Antoine Pitrou97696cb2011-02-21 23:46:27 +00001239 &tagname, &access, &offset)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 return NULL;
1241 }
Tim Peters5ebfd362001-11-13 23:11:19 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 switch((access_mode)access) {
1244 case ACCESS_READ:
1245 flProtect = PAGE_READONLY;
1246 dwDesiredAccess = FILE_MAP_READ;
1247 break;
1248 case ACCESS_DEFAULT: case ACCESS_WRITE:
1249 flProtect = PAGE_READWRITE;
1250 dwDesiredAccess = FILE_MAP_WRITE;
1251 break;
1252 case ACCESS_COPY:
1253 flProtect = PAGE_WRITECOPY;
1254 dwDesiredAccess = FILE_MAP_COPY;
1255 break;
1256 default:
1257 return PyErr_Format(PyExc_ValueError,
1258 "mmap invalid access parameter.");
1259 }
Tim Peters5ebfd362001-11-13 23:11:19 +00001260
Benjamin Petersoncd04db02016-10-05 21:45:48 -07001261 if (map_size < 0) {
1262 PyErr_SetString(PyExc_OverflowError,
Zackery Spytz9308dea2018-03-21 00:02:37 -06001263 "memory mapped length must be positive");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 return NULL;
Benjamin Petersoncd04db02016-10-05 21:45:48 -07001265 }
Antoine Pitrou97696cb2011-02-21 23:46:27 +00001266 if (offset < 0) {
1267 PyErr_SetString(PyExc_OverflowError,
1268 "memory mapped offset must be positive");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 return NULL;
Antoine Pitrou97696cb2011-02-21 23:46:27 +00001270 }
Tim Petersec0a5f02006-02-16 23:47:20 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 /* assume -1 and 0 both mean invalid filedescriptor
1273 to 'anonymously' map memory.
1274 XXX: fileno == 0 is a valid fd, but was accepted prior to 2.5.
1275 XXX: Should this code be added?
1276 if (fileno == 0)
1277 PyErr_WarnEx(PyExc_DeprecationWarning,
1278 "don't use 0 for anonymous memory",
1279 1);
1280 */
1281 if (fileno != -1 && fileno != 0) {
Brian Curtinea47eaa2010-08-01 15:26:26 +00001282 /* Ensure that fileno is within the CRT's valid range */
Steve Dower8fc89802015-04-12 00:26:27 -04001283 _Py_BEGIN_SUPPRESS_IPH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 fh = (HANDLE)_get_osfhandle(fileno);
Steve Dower8fc89802015-04-12 00:26:27 -04001285 _Py_END_SUPPRESS_IPH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 if (fh==(HANDLE)-1) {
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001287 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 return NULL;
1289 }
1290 /* Win9x appears to need us seeked to zero */
1291 lseek(fileno, 0, SEEK_SET);
1292 }
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 m_obj = (mmap_object *)type->tp_alloc(type, 0);
1295 if (m_obj == NULL)
1296 return NULL;
1297 /* Set every field to an invalid marker, so we can safely
1298 destruct the object in the face of failure */
1299 m_obj->data = NULL;
1300 m_obj->file_handle = INVALID_HANDLE_VALUE;
1301 m_obj->map_handle = NULL;
1302 m_obj->tagname = NULL;
1303 m_obj->offset = offset;
Mark Hammond2cbed002000-07-30 02:22:43 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 if (fh) {
1306 /* It is necessary to duplicate the handle, so the
1307 Python code can close it on us */
1308 if (!DuplicateHandle(
1309 GetCurrentProcess(), /* source process handle */
1310 fh, /* handle to be duplicated */
1311 GetCurrentProcess(), /* target proc handle */
1312 (LPHANDLE)&m_obj->file_handle, /* result */
1313 0, /* access - ignored due to options value */
1314 FALSE, /* inherited by child processes? */
1315 DUPLICATE_SAME_ACCESS)) { /* options */
1316 dwErr = GetLastError();
1317 Py_DECREF(m_obj);
1318 PyErr_SetFromWindowsErr(dwErr);
1319 return NULL;
1320 }
1321 if (!map_size) {
1322 DWORD low,high;
1323 low = GetFileSize(fh, &high);
1324 /* low might just happen to have the value INVALID_FILE_SIZE;
1325 so we need to check the last error also. */
1326 if (low == INVALID_FILE_SIZE &&
1327 (dwErr = GetLastError()) != NO_ERROR) {
1328 Py_DECREF(m_obj);
1329 return PyErr_SetFromWindowsErr(dwErr);
1330 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001331
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001332 size = (((long long) high) << 32) + low;
Jesus Cea1f2799b2012-09-10 22:49:50 +02001333 if (size == 0) {
1334 PyErr_SetString(PyExc_ValueError,
1335 "cannot mmap an empty file");
Jesus Ceae8db3562012-09-10 22:58:07 +02001336 Py_DECREF(m_obj);
Jesus Cea1f2799b2012-09-10 22:49:50 +02001337 return NULL;
1338 }
Antoine Pitrou97696cb2011-02-21 23:46:27 +00001339 if (offset >= size) {
Antoine Pitrou305bc9e2011-01-20 21:07:24 +00001340 PyErr_SetString(PyExc_ValueError,
1341 "mmap offset is greater than file size");
1342 Py_DECREF(m_obj);
1343 return NULL;
1344 }
Richard Oudkerk0d09ba82013-02-13 12:18:03 +00001345 if (size - offset > PY_SSIZE_T_MAX) {
1346 PyErr_SetString(PyExc_ValueError,
1347 "mmap length is too large");
1348 Py_DECREF(m_obj);
1349 return NULL;
1350 }
1351 m_obj->size = (Py_ssize_t) (size - offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 } else {
1353 m_obj->size = map_size;
Antoine Pitrou97696cb2011-02-21 23:46:27 +00001354 size = offset + map_size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 }
1356 }
1357 else {
1358 m_obj->size = map_size;
Antoine Pitrou97696cb2011-02-21 23:46:27 +00001359 size = offset + map_size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 }
Guido van Rossum09fdf072000-03-31 01:17:07 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 /* set the initial position */
1363 m_obj->pos = (size_t) 0;
Guido van Rossum09fdf072000-03-31 01:17:07 +00001364
Antoine Pitrouc53204b2013-08-05 23:17:30 +02001365 m_obj->weakreflist = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 m_obj->exports = 0;
1367 /* set the tag name */
1368 if (tagname != NULL && *tagname != '\0') {
1369 m_obj->tagname = PyMem_Malloc(strlen(tagname)+1);
1370 if (m_obj->tagname == NULL) {
1371 PyErr_NoMemory();
1372 Py_DECREF(m_obj);
1373 return NULL;
1374 }
1375 strcpy(m_obj->tagname, tagname);
1376 }
1377 else
1378 m_obj->tagname = NULL;
Mark Hammond2cbed002000-07-30 02:22:43 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 m_obj->access = (access_mode)access;
Antoine Pitrou97696cb2011-02-21 23:46:27 +00001381 size_hi = (DWORD)(size >> 32);
1382 size_lo = (DWORD)(size & 0xFFFFFFFF);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 off_hi = (DWORD)(offset >> 32);
1384 off_lo = (DWORD)(offset & 0xFFFFFFFF);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 /* For files, it would be sufficient to pass 0 as size.
1386 For anonymous maps, we have to pass the size explicitly. */
1387 m_obj->map_handle = CreateFileMapping(m_obj->file_handle,
1388 NULL,
1389 flProtect,
1390 size_hi,
1391 size_lo,
1392 m_obj->tagname);
1393 if (m_obj->map_handle != NULL) {
1394 m_obj->data = (char *) MapViewOfFile(m_obj->map_handle,
1395 dwDesiredAccess,
1396 off_hi,
1397 off_lo,
1398 m_obj->size);
1399 if (m_obj->data != NULL)
1400 return (PyObject *)m_obj;
1401 else {
1402 dwErr = GetLastError();
1403 CloseHandle(m_obj->map_handle);
1404 m_obj->map_handle = NULL;
1405 }
1406 } else
1407 dwErr = GetLastError();
1408 Py_DECREF(m_obj);
1409 PyErr_SetFromWindowsErr(dwErr);
1410 return NULL;
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001411}
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001412#endif /* MS_WINDOWS */
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001413
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001414static void
1415setint(PyObject *d, const char *name, long value)
1416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 PyObject *o = PyLong_FromLong(value);
1418 if (o && PyDict_SetItemString(d, name, o) == 0) {
1419 Py_DECREF(o);
1420 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001421}
1422
Martin v. Löwis1a214512008-06-11 05:26:20 +00001423
1424static struct PyModuleDef mmapmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 PyModuleDef_HEAD_INIT,
1426 "mmap",
1427 NULL,
1428 -1,
1429 NULL,
1430 NULL,
1431 NULL,
1432 NULL,
1433 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001434};
1435
Mark Hammond62b1ab12002-07-23 06:31:15 +00001436PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001437PyInit_mmap(void)
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 PyObject *dict, *module;
Tim Peters2caf8df2001-01-14 05:05:51 +00001440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 if (PyType_Ready(&mmap_object_type) < 0)
1442 return NULL;
Tim Peters2caf8df2001-01-14 05:05:51 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 module = PyModule_Create(&mmapmodule);
1445 if (module == NULL)
1446 return NULL;
1447 dict = PyModule_GetDict(module);
1448 if (!dict)
1449 return NULL;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001450 PyDict_SetItemString(dict, "error", PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 PyDict_SetItemString(dict, "mmap", (PyObject*) &mmap_object_type);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001452#ifdef PROT_EXEC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 setint(dict, "PROT_EXEC", PROT_EXEC);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001454#endif
1455#ifdef PROT_READ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 setint(dict, "PROT_READ", PROT_READ);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001457#endif
1458#ifdef PROT_WRITE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 setint(dict, "PROT_WRITE", PROT_WRITE);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001460#endif
1461
1462#ifdef MAP_SHARED
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 setint(dict, "MAP_SHARED", MAP_SHARED);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001464#endif
1465#ifdef MAP_PRIVATE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 setint(dict, "MAP_PRIVATE", MAP_PRIVATE);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001467#endif
1468#ifdef MAP_DENYWRITE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 setint(dict, "MAP_DENYWRITE", MAP_DENYWRITE);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001470#endif
1471#ifdef MAP_EXECUTABLE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 setint(dict, "MAP_EXECUTABLE", MAP_EXECUTABLE);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001473#endif
Neal Norwitz0e6bc8c2006-02-05 05:45:43 +00001474#ifdef MAP_ANONYMOUS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 setint(dict, "MAP_ANON", MAP_ANONYMOUS);
1476 setint(dict, "MAP_ANONYMOUS", MAP_ANONYMOUS);
Andrew M. Kuchling1ed7d2d2000-03-30 21:14:30 +00001477#endif
1478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 setint(dict, "PAGESIZE", (long)my_getpagesize());
Andrew M. Kuchling961fe172000-06-03 19:41:42 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 setint(dict, "ALLOCATIONGRANULARITY", (long)my_getallocationgranularity());
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001482
Justus Schwabedal5a8a84b2017-11-07 15:51:43 -05001483 setint(dict, "ACCESS_DEFAULT", ACCESS_DEFAULT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 setint(dict, "ACCESS_READ", ACCESS_READ);
1485 setint(dict, "ACCESS_WRITE", ACCESS_WRITE);
1486 setint(dict, "ACCESS_COPY", ACCESS_COPY);
1487 return module;
Tim Peters5ebfd362001-11-13 23:11:19 +00001488}