mmapmodule.c 25.8 KB
Newer Older
1 2
/*
 /  Author: Sam Rushing <rushing@nightmare.com>
3
 /  Hacked for Unix by AMK
4
 /  $Id$
5 6 7 8 9 10 11 12 13 14

 / mmapmodule.cpp -- map a view of a file into memory
 /
 / todo: need permission flags, perhaps a 'chsize' analog
 /   not all functions check range yet!!!
 /
 /
 / Note: This module currently only deals with 32-bit file
 /   sizes.
 /
Mark Hammond's avatar
Mark Hammond committed
15 16 17
 / This version of mmapmodule.c has been changed significantly
 / from the original mmapfile.c on which it was based.
 / The original version of mmapfile is maintained by Sam at
18 19 20
 / ftp://squirl.nightmare.com/pub/python/python-ext.
*/

21 22
#include <Python.h>

23
#ifndef MS_WINDOWS
24 25 26
#define UNIX
#endif

27
#ifdef MS_WINDOWS
28
#include <windows.h>
29 30 31
static int
my_getpagesize(void)
{
32 33 34
	SYSTEM_INFO si;
	GetSystemInfo(&si);
	return si.dwPageSize;
35
}
36 37 38 39
#endif

#ifdef UNIX
#include <sys/mman.h>
40
#include <sys/stat.h>
41

42 43 44 45
#if defined(HAVE_SYSCONF) && defined(_SC_PAGESIZE)
static int
my_getpagesize(void)
{
46
	return sysconf(_SC_PAGESIZE);
47 48 49 50 51
}
#else
#define my_getpagesize getpagesize
#endif

52 53
#endif /* UNIX */

54 55 56 57 58
#include <string.h>
#include <sys/types.h>

static PyObject *mmap_module_error;

59 60 61 62 63 64 65 66
typedef enum
{
	ACCESS_DEFAULT,
	ACCESS_READ,
	ACCESS_WRITE,
	ACCESS_COPY
} access_mode;

67
typedef struct {
68 69 70 71
	PyObject_HEAD
	char *	data;
	size_t	size;
	size_t	pos;
72

73
#ifdef MS_WINDOWS
74
	HANDLE	map_handle;
Mark Hammond's avatar
Mark Hammond committed
75
	HANDLE	file_handle;
76
	char *	tagname;
77 78 79
#endif

#ifdef UNIX
80
        int fd;
81
#endif
82 83

        access_mode access;
84 85
} mmap_object;

86

87
static void
Fredrik Lundh's avatar
Fredrik Lundh committed
88
mmap_object_dealloc(mmap_object *m_obj)
89
{
90
#ifdef MS_WINDOWS
91 92 93 94
	if (m_obj->data != NULL)
		UnmapViewOfFile (m_obj->data);
	if (m_obj->map_handle != INVALID_HANDLE_VALUE)
		CloseHandle (m_obj->map_handle);
Mark Hammond's avatar
Mark Hammond committed
95 96
	if (m_obj->file_handle != INVALID_HANDLE_VALUE)
		CloseHandle (m_obj->file_handle);
97 98
	if (m_obj->tagname)
		PyMem_Free(m_obj->tagname);
99
#endif /* MS_WINDOWS */
100 101

#ifdef UNIX
102
	if (m_obj->data!=NULL) {
103
		msync(m_obj->data, m_obj->size, MS_SYNC);
104 105
		munmap(m_obj->data, m_obj->size);
	}
106 107
#endif /* UNIX */

108
	PyObject_Del(m_obj);
109 110 111
}

static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
112
mmap_close_method(mmap_object *self, PyObject *args)
113
{
114
        if (!PyArg_ParseTuple(args, ":close"))
115
		return NULL;
116
#ifdef MS_WINDOWS
Mark Hammond's avatar
Mark Hammond committed
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
	/* For each resource we maintain, we need to check
	   the value is valid, and if so, free the resource 
	   and set the member value to an invalid value so
	   the dealloc does not attempt to resource clearing
	   again.
	   TODO - should we check for errors in the close operations???
	*/
	if (self->data != NULL) {
		UnmapViewOfFile (self->data);
		self->data = NULL;
	}
	if (self->map_handle != INVALID_HANDLE_VALUE) {
		CloseHandle (self->map_handle);
		self->map_handle = INVALID_HANDLE_VALUE;
	}
	if (self->file_handle != INVALID_HANDLE_VALUE) {
		CloseHandle (self->file_handle);
		self->file_handle = INVALID_HANDLE_VALUE;
	}
136
#endif /* MS_WINDOWS */
137 138

#ifdef UNIX
139 140 141 142
	if (self->data != NULL) {
		munmap(self->data, self->size);
		self->data = NULL;
	}
143 144
#endif

145 146
	Py_INCREF (Py_None);
	return (Py_None);
147 148
}

149
#ifdef MS_WINDOWS
150 151
#define CHECK_VALID(err)						\
do {									\
152
    if (self->map_handle == INVALID_HANDLE_VALUE) {						\
153 154 155
	PyErr_SetString (PyExc_ValueError, "mmap closed or invalid");	\
	return err;							\
    }									\
156
} while (0)
157
#endif /* MS_WINDOWS */
158 159

#ifdef UNIX
160 161 162 163 164 165
#define CHECK_VALID(err)						\
do {									\
    if (self->data == NULL) {						\
	PyErr_SetString (PyExc_ValueError, "mmap closed or invalid");	\
	return err;							\
	}								\
166 167 168 169
} while (0)
#endif /* UNIX */

static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
170 171
mmap_read_byte_method(mmap_object *self,
		      PyObject *args)
172
{
173
	CHECK_VALID(NULL);
174
        if (!PyArg_ParseTuple(args, ":read_byte"))
175
		return NULL;
176
	if (self->pos < self->size) {
Tim Peters's avatar
Tim Peters committed
177
	        char value = self->data[self->pos];
178
		self->pos += 1;
Tim Peters's avatar
Tim Peters committed
179
		return Py_BuildValue("c", value);
180 181 182 183
	} else {
		PyErr_SetString (PyExc_ValueError, "read byte out of range");
		return NULL;
	}
184 185 186
}

static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
187
mmap_read_line_method(mmap_object *self,
188
		      PyObject *args)
189
{
Fredrik Lundh's avatar
Fredrik Lundh committed
190 191 192 193
	char *start = self->data+self->pos;
	char *eof = self->data+self->size;
	char *eol;
	PyObject *result;
194 195

	CHECK_VALID(NULL);
196
        if (!PyArg_ParseTuple(args, ":readline"))
197
		return NULL;
198

199 200 201 202 203 204
	eol = memchr(start, '\n', self->size - self->pos);
	if (!eol)
		eol = eof;
	else
		++eol;		/* we're interested in the position after the
				   newline. */
205
	result = PyString_FromStringAndSize(start, (eol - start));
206 207
	self->pos += (eol - start);
	return (result);
208 209 210
}

static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
211 212
mmap_read_method(mmap_object *self,
		 PyObject *args)
213
{
214 215 216 217
	long num_bytes;
	PyObject *result;

	CHECK_VALID(NULL);
Fredrik Lundh's avatar
Fredrik Lundh committed
218
	if (!PyArg_ParseTuple(args, "l:read", &num_bytes))
219 220 221 222 223 224 225 226 227
		return(NULL);

	/* silently 'adjust' out-of-range requests */
	if ((self->pos + num_bytes) > self->size) {
		num_bytes -= (self->pos+num_bytes) - self->size;
	}
	result = Py_BuildValue("s#", self->data+self->pos, num_bytes);
	self->pos += num_bytes;	 
	return (result);
228 229 230
}

static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
231 232
mmap_find_method(mmap_object *self,
		 PyObject *args)
233
{
234
	long start = self->pos;
Fredrik Lundh's avatar
Fredrik Lundh committed
235
	char *needle;
236
	int len;
237

238
	CHECK_VALID(NULL);
239
	if (!PyArg_ParseTuple (args, "s#|l:find", &needle, &len, &start)) {
240 241
		return NULL;
	} else {
242 243 244 245
		char *p;
		char *e = self->data + self->size;

                if (start < 0)
246
			start += self->size;
247
                if (start < 0)
248
			start = 0;
249
                else if ((size_t)start > self->size)
250
			start = self->size;
251

252 253 254 255 256
		for (p = self->data + start; p + len <= e; ++p) {
			int i;
			for (i = 0; i < len && needle[i] == p[i]; ++i)
				/* nothing */;
			if (i == len) {
257
				return Py_BuildValue (
258 259
					"l",
					(long) (p - self->data));
260
			}
261
		}
262 263
		return Py_BuildValue ("l", (long) -1);
	}
264 265
}

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
static int 
is_writeable(mmap_object *self)
{
	if (self->access != ACCESS_READ)
		return 1; 
	PyErr_Format(PyExc_TypeError, "mmap can't modify a readonly memory map.");
	return 0;
}

static int 
is_resizeable(mmap_object *self)
{
	if ((self->access == ACCESS_WRITE) || (self->access == ACCESS_DEFAULT))
		return 1; 
	PyErr_Format(PyExc_TypeError, 
		     "mmap can't resize a readonly or copy-on-write memory map.");
	return 0;
}


286
static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
287 288
mmap_write_method(mmap_object *self,
		  PyObject *args)
289
{
290
	int length;
Fredrik Lundh's avatar
Fredrik Lundh committed
291
	char *data;
292

293
	CHECK_VALID(NULL);
Fredrik Lundh's avatar
Fredrik Lundh committed
294
	if (!PyArg_ParseTuple (args, "s#:write", &data, &length))
295
		return(NULL);
296

297 298 299
	if (!is_writeable(self))
		return NULL;

300 301 302 303 304 305 306 307
	if ((self->pos + length) > self->size) {
		PyErr_SetString (PyExc_ValueError, "data out of range");
		return NULL;
	}
	memcpy (self->data+self->pos, data, length);
	self->pos = self->pos+length;
	Py_INCREF (Py_None);
	return (Py_None);
308 309 310
}

static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
311 312
mmap_write_byte_method(mmap_object *self,
		       PyObject *args)
313
{
314
	char value;
315

316
	CHECK_VALID(NULL);
Fredrik Lundh's avatar
Fredrik Lundh committed
317
	if (!PyArg_ParseTuple (args, "c:write_byte", &value))
318
		return(NULL);
319

320 321
	if (!is_writeable(self))
		return NULL;
322 323 324 325
	*(self->data+self->pos) = value;
	self->pos += 1;
	Py_INCREF (Py_None);
	return (Py_None);
326
}
327
 
328
static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
329 330
mmap_size_method(mmap_object *self,
		 PyObject *args)
331
{
332
	CHECK_VALID(NULL);
333
        if (!PyArg_ParseTuple(args, ":size"))
334
		return NULL;
335

336
#ifdef MS_WINDOWS
Mark Hammond's avatar
Mark Hammond committed
337
	if (self->file_handle != INVALID_HANDLE_VALUE) {
338
		return (Py_BuildValue (
339
			"l", (long)
Mark Hammond's avatar
Mark Hammond committed
340
			GetFileSize (self->file_handle, NULL)));
341
	} else {
342
		return (Py_BuildValue ("l", (long) self->size) );
343
	}
344
#endif /* MS_WINDOWS */
345 346

#ifdef UNIX
347 348 349 350 351 352
	{
		struct stat buf;
		if (-1 == fstat(self->fd, &buf)) {
			PyErr_SetFromErrno(mmap_module_error);
			return NULL;
		}
353
		return (Py_BuildValue ("l", (long) buf.st_size) );
354
	}
355 356 357 358 359 360 361 362 363 364 365 366 367
#endif /* UNIX */
}

/* This assumes that you want the entire file mapped,
 / and when recreating the map will make the new file
 / have the new size
 /
 / Is this really necessary?  This could easily be done
 / from python by just closing and re-opening with the
 / new size?
 */

static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
368 369
mmap_resize_method(mmap_object *self,
		   PyObject *args)
370
{
371 372
	unsigned long new_size;
	CHECK_VALID(NULL);
373 374
	if (!PyArg_ParseTuple (args, "l:resize", &new_size) || 
	    !is_resizeable(self)) {
375
		return NULL;
376
#ifdef MS_WINDOWS
377 378 379 380 381
	} else { 
		DWORD dwErrCode = 0;
		/* First, unmap the file view */
		UnmapViewOfFile (self->data);
		/* Close the mapping object */
Mark Hammond's avatar
Mark Hammond committed
382
		CloseHandle (self->map_handle);
383
		/* Move to the desired EOF position */
Mark Hammond's avatar
Mark Hammond committed
384
		SetFilePointer (self->file_handle,
385 386
				new_size, NULL, FILE_BEGIN);
		/* Change the size of the file */
Mark Hammond's avatar
Mark Hammond committed
387
		SetEndOfFile (self->file_handle);
388 389
		/* Create another mapping object and remap the file view */
		self->map_handle = CreateFileMapping (
Mark Hammond's avatar
Mark Hammond committed
390
			self->file_handle,
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
			NULL,
			PAGE_READWRITE,
			0,
			new_size,
			self->tagname);
		if (self->map_handle != NULL) {
			self->data = (char *) MapViewOfFile (self->map_handle,
							     FILE_MAP_WRITE,
							     0,
							     0,
							     0);
			if (self->data != NULL) {
				self->size = new_size;
				Py_INCREF (Py_None);
				return Py_None;
			} else {
				dwErrCode = GetLastError();
			}
		} else {
			dwErrCode = GetLastError();
411
		}
412 413
		PyErr_SetFromWindowsErr(dwErrCode);
		return (NULL);
414
#endif /* MS_WINDOWS */
415 416

#ifdef UNIX
417
#ifndef HAVE_MREMAP 
418 419 420 421
	} else {
		PyErr_SetString(PyExc_SystemError,
				"mmap: resizing not available--no mremap()");
		return NULL;
422
#else
423 424
	} else {
		void *newmap;
425

426
#ifdef MREMAP_MAYMOVE
427
		newmap = mremap(self->data, self->size, new_size, MREMAP_MAYMOVE);
428
#else
429
		newmap = mremap(self->data, self->size, new_size, 0);
430
#endif
431 432 433 434 435 436 437 438 439
		if (newmap == (void *)-1) 
		{
			PyErr_SetFromErrno(mmap_module_error);
			return NULL;
		}
		self->data = newmap;
		self->size = new_size;
		Py_INCREF(Py_None);
		return Py_None;
440
#endif /* HAVE_MREMAP */
441
#endif /* UNIX */
442
	}
443 444 445
}

static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
446
mmap_tell_method(mmap_object *self, PyObject *args)
447
{
448
	CHECK_VALID(NULL);
449
        if (!PyArg_ParseTuple(args, ":tell"))
450
		return NULL;
451
	return (Py_BuildValue ("l", (long) self->pos) );
452 453 454
}

static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
455
mmap_flush_method(mmap_object *self, PyObject *args)
456
{
457 458 459
	size_t offset	= 0;
	size_t size = self->size;
	CHECK_VALID(NULL);
Fredrik Lundh's avatar
Fredrik Lundh committed
460
	if (!PyArg_ParseTuple (args, "|ll:flush", &offset, &size)) {
461 462 463 464 465 466
		return NULL;
	} else if ((offset + size) > self->size) {
		PyErr_SetString (PyExc_ValueError,
				 "flush values out of range");
		return NULL;
	} else {
467
#ifdef MS_WINDOWS
468 469
		return (Py_BuildValue("l", (long)
                                      FlushViewOfFile(self->data+offset, size)));
470
#endif /* MS_WINDOWS */
471
#ifdef UNIX
472 473 474
		/* XXX semantics of return value? */
		/* XXX flags for msync? */
		if (-1 == msync(self->data + offset, size,
475
				MS_SYNC))
476 477 478
		{
			PyErr_SetFromErrno(mmap_module_error);
			return NULL;
479
		}
480
		return Py_BuildValue ("l", (long) 0);	
481 482
#endif /* UNIX */   
	}
483 484 485
}

static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
486
mmap_seek_method(mmap_object *self, PyObject *args)
487
{
488
	int dist;
489 490
	int how=0;
	CHECK_VALID(NULL);
Fredrik Lundh's avatar
Fredrik Lundh committed
491
	if (!PyArg_ParseTuple (args, "i|i:seek", &dist, &how)) {
492 493
		return(NULL);
	} else {
494
		size_t where;
495
		switch (how) {
496 497 498
		case 0: /* relative to start */
			if (dist < 0)
				goto onoutofrange;
499 500
			where = dist;
			break;
501 502 503
		case 1: /* relative to current position */
			if ((int)self->pos + dist < 0)
				goto onoutofrange;
504 505
			where = self->pos + dist;
			break;
506 507 508 509
		case 2: /* relative to end */
			if ((int)self->size + dist < 0)
				goto onoutofrange;
			where = self->size + dist;
510 511 512 513 514 515
			break;
		default:
			PyErr_SetString (PyExc_ValueError,
					 "unknown seek type");
			return NULL;
		}
516 517 518 519 520
		if (where > self->size)
			goto onoutofrange;
		self->pos = where;
		Py_INCREF (Py_None);
		return (Py_None);
521
	}
522

523
  onoutofrange:
524 525
	PyErr_SetString (PyExc_ValueError, "seek out of range");
	return NULL;
526 527 528
}

static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
529
mmap_move_method(mmap_object *self, PyObject *args)
530
{
531 532
	unsigned long dest, src, count;
	CHECK_VALID(NULL);
533 534
	if (!PyArg_ParseTuple (args, "iii:move", &dest, &src, &count) ||
	    !is_writeable(self)) {
535 536 537 538 539 540 541 542 543 544
		return NULL;
	} else {
		/* bounds check the values */
		if (/* end of source after end of data?? */
			((src+count) > self->size)
			/* dest will fit? */
			|| (dest+count > self->size)) {
			PyErr_SetString (PyExc_ValueError,
					 "source or destination out of range");
			return NULL;
545
		} else {
546 547 548
			memmove (self->data+dest, self->data+src, count);
			Py_INCREF (Py_None);
			return Py_None;
549
		}
550
	}
551 552 553
}

static struct PyMethodDef mmap_object_methods[] = {
554 555 556 557 558 559 560 561 562 563 564 565 566
	{"close",	(PyCFunction) mmap_close_method,	METH_VARARGS},
	{"find",	(PyCFunction) mmap_find_method,		METH_VARARGS},
	{"flush",	(PyCFunction) mmap_flush_method,	METH_VARARGS},
	{"move",	(PyCFunction) mmap_move_method,		METH_VARARGS},
	{"read",	(PyCFunction) mmap_read_method,		METH_VARARGS},
	{"read_byte",	(PyCFunction) mmap_read_byte_method,  	METH_VARARGS},
	{"readline",	(PyCFunction) mmap_read_line_method,	METH_VARARGS},
	{"resize",	(PyCFunction) mmap_resize_method,	METH_VARARGS},
	{"seek",	(PyCFunction) mmap_seek_method,		METH_VARARGS},
	{"size",	(PyCFunction) mmap_size_method,		METH_VARARGS},
	{"tell",	(PyCFunction) mmap_tell_method,		METH_VARARGS},
	{"write",	(PyCFunction) mmap_write_method,	METH_VARARGS},
	{"write_byte",	(PyCFunction) mmap_write_byte_method,	METH_VARARGS},
567
	{NULL,	   NULL}       /* sentinel */
568 569 570 571 572
};

/* Functions for treating an mmap'ed file as a buffer */

static int
573
mmap_buffer_getreadbuf(mmap_object *self, int index, const void **ptr)
574
{
575 576 577 578 579 580 581 582
	CHECK_VALID(-1);
	if ( index != 0 ) {
		PyErr_SetString(PyExc_SystemError,
				"Accessing non-existent mmap segment");
		return -1;
	}
	*ptr = self->data;
	return self->size;
583 584 585
}

static int
Fredrik Lundh's avatar
Fredrik Lundh committed
586
mmap_buffer_getwritebuf(mmap_object *self, int index, const void **ptr)
587
{  
588 589 590 591 592 593
	CHECK_VALID(-1);
	if ( index != 0 ) {
		PyErr_SetString(PyExc_SystemError,
				"Accessing non-existent mmap segment");
		return -1;
	}
594 595
	if (!is_writeable(self))
		return -1;
596 597
	*ptr = self->data;
	return self->size;
598 599 600
}

static int
Fredrik Lundh's avatar
Fredrik Lundh committed
601
mmap_buffer_getsegcount(mmap_object *self, int *lenp)
602
{
603 604 605 606
	CHECK_VALID(-1);
	if (lenp) 
		*lenp = self->size;
	return 1;
607 608 609
}

static int
Fredrik Lundh's avatar
Fredrik Lundh committed
610
mmap_buffer_getcharbuffer(mmap_object *self, int index, const void **ptr)
611
{
612 613 614 615 616 617 618
	if ( index != 0 ) {
		PyErr_SetString(PyExc_SystemError,
				"accessing non-existent buffer segment");
		return -1;
	}
	*ptr = (const char *)self->data;
	return self->size;
619 620 621
}

static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
622
mmap_object_getattr(mmap_object *self, char *name)
623
{
624
	return Py_FindMethod (mmap_object_methods, (PyObject *)self, name);
625 626 627
}

static int
Fredrik Lundh's avatar
Fredrik Lundh committed
628
mmap_length(mmap_object *self)
629
{
630 631
	CHECK_VALID(-1);
	return self->size;
632 633 634
}

static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
635
mmap_item(mmap_object *self, int i)
636
{
637
	CHECK_VALID(NULL);
638
	if (i < 0 || (size_t)i >= self->size) {
639 640 641 642
		PyErr_SetString(PyExc_IndexError, "mmap index out of range");
		return NULL;
	}
	return PyString_FromStringAndSize(self->data + i, 1);
643 644 645
}

static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
646
mmap_slice(mmap_object *self, int ilow, int ihigh)
647
{
648 649 650
	CHECK_VALID(NULL);
	if (ilow < 0)
		ilow = 0;
651
	else if ((size_t)ilow > self->size)
652 653 654 655 656
		ilow = self->size;
	if (ihigh < 0)
		ihigh = 0;
	if (ihigh < ilow)
		ihigh = ilow;
657
	else if ((size_t)ihigh > self->size)
658 659 660
		ihigh = self->size;
    
	return PyString_FromStringAndSize(self->data + ilow, ihigh-ilow);
661 662 663
}

static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
664
mmap_concat(mmap_object *self, PyObject *bb)
665
{
666 667 668 669
	CHECK_VALID(NULL);
	PyErr_SetString(PyExc_SystemError,
			"mmaps don't support concatenation");
	return NULL;
670 671 672
}

static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
673
mmap_repeat(mmap_object *self, int n)
674
{
675 676 677 678
	CHECK_VALID(NULL);
	PyErr_SetString(PyExc_SystemError,
			"mmaps don't support repeat operation");
	return NULL;
679 680 681
}

static int
Fredrik Lundh's avatar
Fredrik Lundh committed
682
mmap_ass_slice(mmap_object *self, int ilow, int ihigh, PyObject *v)
683
{
684
	const char *buf;
685 686 687 688

	CHECK_VALID(-1);
	if (ilow < 0)
		ilow = 0;
689
	else if ((size_t)ilow > self->size)
690 691 692 693 694
		ilow = self->size;
	if (ihigh < 0)
		ihigh = 0;
	if (ihigh < ilow)
		ihigh = ilow;
695
	else if ((size_t)ihigh > self->size)
696 697
		ihigh = self->size;
    
698 699
	if (v == NULL) {
		PyErr_SetString(PyExc_TypeError,
700
				"mmap object doesn't support slice deletion");
701 702
		return -1;
	}
703 704 705 706 707 708 709 710 711 712
	if (! (PyString_Check(v)) ) {
		PyErr_SetString(PyExc_IndexError, 
				"mmap slice assignment must be a string");
		return -1;
	}
	if ( PyString_Size(v) != (ihigh - ilow) ) {
		PyErr_SetString(PyExc_IndexError, 
				"mmap slice assignment is wrong size");
		return -1;
	}
713 714
	if (!is_writeable(self))
		return -1;
715 716 717
	buf = PyString_AsString(v);
	memcpy(self->data + ilow, buf, ihigh-ilow);
	return 0;
718 719 720
}

static int
Fredrik Lundh's avatar
Fredrik Lundh committed
721
mmap_ass_item(mmap_object *self, int i, PyObject *v)
722
{
723
	const char *buf;
724
 
725
	CHECK_VALID(-1);
726
	if (i < 0 || (size_t)i >= self->size) {
727 728 729
		PyErr_SetString(PyExc_IndexError, "mmap index out of range");
		return -1;
	}
730 731
	if (v == NULL) {
		PyErr_SetString(PyExc_TypeError,
732
				"mmap object doesn't support item deletion");
733 734
		return -1;
	}
735 736
	if (! (PyString_Check(v) && PyString_Size(v)==1) ) {
		PyErr_SetString(PyExc_IndexError, 
737
				"mmap assignment must be single-character string");
738 739
		return -1;
	}
740 741
	if (!is_writeable(self))
		return -1;
742 743 744
	buf = PyString_AsString(v);
	self->data[i] = buf[0];
	return 0;
745 746 747
}

static PySequenceMethods mmap_as_sequence = {
748 749 750 751 752 753 754
	(inquiry)mmap_length,		       /*sq_length*/
	(binaryfunc)mmap_concat,	       /*sq_concat*/
	(intargfunc)mmap_repeat,	       /*sq_repeat*/
	(intargfunc)mmap_item,		       /*sq_item*/
	(intintargfunc)mmap_slice,	       /*sq_slice*/
	(intobjargproc)mmap_ass_item,	       /*sq_ass_item*/
	(intintobjargproc)mmap_ass_slice,      /*sq_ass_slice*/
755 756 757
};

static PyBufferProcs mmap_as_buffer = {
758 759 760 761
	(getreadbufferproc)mmap_buffer_getreadbuf,
	(getwritebufferproc)mmap_buffer_getwritebuf,
	(getsegcountproc)mmap_buffer_getsegcount,
	(getcharbufferproc)mmap_buffer_getcharbuffer,
762 763 764
};

static PyTypeObject mmap_object_type = {
765 766
	PyObject_HEAD_INIT(0) /* patched in module init */
	0,					/* ob_size */
767
	"mmap.mmap",				/* tp_name */
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
	sizeof(mmap_object),			/* tp_size */
	0,					/* tp_itemsize */
	/* methods */
	(destructor) mmap_object_dealloc,	/* tp_dealloc */
	0,					/* tp_print */
	(getattrfunc) mmap_object_getattr,	/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	0,					/* tp_repr */
	0,					/* tp_as_number */
	&mmap_as_sequence,			/*tp_as_sequence*/
	0,					/*tp_as_mapping*/
	0,					/*tp_hash*/
	0,					/*tp_call*/
	0,					/*tp_str*/
	0,					/*tp_getattro*/
	0,					/*tp_setattro*/
	&mmap_as_buffer,			/*tp_as_buffer*/
	Py_TPFLAGS_HAVE_GETCHARBUFFER,		/*tp_flags*/
	0,					/*tp_doc*/
788 789
};

790 791 792 793 794 795 796 797

/* extract the map size from the given PyObject

   The map size is restricted to [0, INT_MAX] because this is the current
   Python limitation on object sizes. Although the mmap object *could* handle
   a larger map size, there is no point because all the useful operations
   (len(), slicing(), sequence indexing) are limited by a C int.

798
   Returns -1 on error, with an appropriate Python exception raised. On
799 800
   success, the map size is returned. */
static int
Fredrik Lundh's avatar
Fredrik Lundh committed
801
_GetMapSize(PyObject *o)
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
{
	if (PyInt_Check(o)) {
		long i = PyInt_AsLong(o);
		if (PyErr_Occurred())
			return -1;
		if (i < 0)
			goto onnegoverflow;
		if (i > INT_MAX)
			goto onposoverflow;
		return (int)i;
	}
	else if (PyLong_Check(o)) {
		long i = PyLong_AsLong(o);
		if (PyErr_Occurred()) {
			/* yes negative overflow is mistaken for positive overflow
			   but not worth the trouble to check sign of 'i' */
			if (PyErr_ExceptionMatches(PyExc_OverflowError))
				goto onposoverflow;
			else
				return -1;
		}
		if (i < 0)
			goto onnegoverflow;
		if (i > INT_MAX)
			goto onposoverflow;
		return (int)i;
	}
	else {
		PyErr_SetString(PyExc_TypeError,
831
				"map size must be an integral value");
832 833 834
		return -1;
	}

835
  onnegoverflow:
836
	PyErr_SetString(PyExc_OverflowError,
837
			"memory mapped size must be positive");
838 839
	return -1;

840
  onposoverflow:
841
	PyErr_SetString(PyExc_OverflowError,
842
			"memory mapped size is too large (limited by C int)");
843 844 845
	return -1;
}

846 847
#ifdef UNIX 
static PyObject *
Fredrik Lundh's avatar
Fredrik Lundh committed
848
new_mmap_object(PyObject *self, PyObject *args, PyObject *kwdict)
849
{
850 851 852
#ifdef HAVE_FSTAT
	struct stat st;
#endif
Fredrik Lundh's avatar
Fredrik Lundh committed
853
	mmap_object *m_obj;
854 855
	PyObject *map_size_obj = NULL;
	int map_size;
856
	int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ;
857 858 859 860
	access_mode access = ACCESS_DEFAULT;
	char *keywords[] = {"fileno", "length", 
			    "flags", "prot", 
			    "access", NULL};
861

862 863
	if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|iii", keywords, 
					 &fd, &map_size_obj, &flags, &prot, &access))
864
		return NULL;
865 866 867
	map_size = _GetMapSize(map_size_obj);
	if (map_size < 0)
		return NULL;
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892

	if ((access != ACCESS_DEFAULT) && 
	    ((flags != MAP_SHARED) || ( prot != (PROT_WRITE | PROT_READ))))
		return PyErr_Format(PyExc_ValueError, 
				    "mmap can't specify both access and flags, prot.");
	switch(access) {
	case ACCESS_READ:
		flags = MAP_SHARED;
		prot = PROT_READ;
		break;
	case ACCESS_WRITE:
		flags = MAP_SHARED;
		prot = PROT_READ | PROT_WRITE;
		break;
	case ACCESS_COPY:
		flags = MAP_PRIVATE;
		prot = PROT_READ | PROT_WRITE;
		break;
	case ACCESS_DEFAULT: 
		/* use the specified or default values of flags and prot */
		break;
	default:
		return PyErr_Format(PyExc_ValueError, 
				    "mmap invalid access parameter.");
	}
893 894

#ifdef HAVE_FSTAT
895 896 897 898
#  ifdef __VMS
	/* on OpenVMS we must ensure that all bytes are written to the file */
	fsync(fd);
#  endif
899 900
	if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode) &&
	    (size_t)map_size > st.st_size) {
901 902 903 904 905
		PyErr_SetString(PyExc_ValueError, 
				"mmap length is greater than file size");
		return NULL;
	}
#endif
906
	m_obj = PyObject_New (mmap_object, &mmap_object_type);
907 908 909
	if (m_obj == NULL) {return NULL;}
	m_obj->size = (size_t) map_size;
	m_obj->pos = (size_t) 0;
910
	m_obj->fd = fd;
911 912 913
	m_obj->data = mmap(NULL, map_size, 
			   prot, flags,
			   fd, 0);
914
	if (m_obj->data == (char *)-1) {
915 916 917 918
		Py_DECREF(m_obj);
		PyErr_SetFromErrno(mmap_module_error);
		return NULL;
	}
919
	m_obj->access = access;
920
	return (PyObject *)m_obj;
921 922 923
}
#endif /* UNIX */

924
#ifdef MS_WINDOWS
925
static PyObject *
926
new_mmap_object(PyObject *self, PyObject *args, PyObject *kwdict)
927
{
Fredrik Lundh's avatar
Fredrik Lundh committed
928
	mmap_object *m_obj;
929 930
	PyObject *map_size_obj = NULL;
	int map_size;
Fredrik Lundh's avatar
Fredrik Lundh committed
931
	char *tagname = "";
932 933
	DWORD dwErr = 0;
	int fileno;
Mark Hammond's avatar
Mark Hammond committed
934
	HANDLE fh = 0;
935 936 937 938 939 940 941 942 943
	access_mode   access = ACCESS_DEFAULT;
	DWORD flProtect, dwDesiredAccess;
	char *keywords[] = { "fileno", "length", 
			     "tagname", 
			     "access", NULL };

	if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|zi", keywords,
					 &fileno, &map_size_obj, 
					 &tagname, &access)) {
944
		return NULL;
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
	}

	switch(access) {
	case ACCESS_READ:
		flProtect = PAGE_READONLY;
		dwDesiredAccess = FILE_MAP_READ;
		break;
	case ACCESS_DEFAULT:  case ACCESS_WRITE:
		flProtect = PAGE_READWRITE;
		dwDesiredAccess = FILE_MAP_WRITE;
		break;
	case ACCESS_COPY:
		flProtect = PAGE_WRITECOPY;
		dwDesiredAccess = FILE_MAP_COPY;
		break;
	default:
		return PyErr_Format(PyExc_ValueError, 
				    "mmap invalid access parameter.");
	}

965 966 967 968
	map_size = _GetMapSize(map_size_obj);
	if (map_size < 0)
		return NULL;
	
969 970
	/* if an actual filename has been specified */
	if (fileno != 0) {
Mark Hammond's avatar
Mark Hammond committed
971 972
		fh = (HANDLE)_get_osfhandle(fileno);
		if (fh==(HANDLE)-1) {
973 974
			PyErr_SetFromErrno(mmap_module_error);
			return NULL;
975
		}
976
		/* Win9x appears to need us seeked to zero */
977
		lseek(fileno, 0, SEEK_SET);
978 979
	}

980
	m_obj = PyObject_New (mmap_object, &mmap_object_type);
981 982 983 984 985
	if (m_obj==NULL)
		return NULL;
	/* Set every field to an invalid marker, so we can safely
	   destruct the object in the face of failure */
	m_obj->data = NULL;
Mark Hammond's avatar
Mark Hammond committed
986
	m_obj->file_handle = INVALID_HANDLE_VALUE;
987 988 989
	m_obj->map_handle = INVALID_HANDLE_VALUE;
	m_obj->tagname = NULL;

990
	if (fh) {
991 992 993
		/* It is necessary to duplicate the handle, so the
		   Python code can close it on us */
		if (!DuplicateHandle(
994 995 996 997 998 999 1000
			GetCurrentProcess(), /* source process handle */
			fh, /* handle to be duplicated */
			GetCurrentProcess(), /* target proc handle */
			(LPHANDLE)&m_obj->file_handle, /* result */
			0, /* access - ignored due to options value */
			FALSE, /* inherited by child processes? */
			DUPLICATE_SAME_ACCESS)) { /* options */
1001 1002 1003 1004 1005
			dwErr = GetLastError();
			Py_DECREF(m_obj);
			PyErr_SetFromWindowsErr(dwErr);
			return NULL;
		}
1006
		if (!map_size) {
Mark Hammond's avatar
Mark Hammond committed
1007
			m_obj->size = GetFileSize (fh, NULL);
1008 1009
		} else {
			m_obj->size = map_size;
1010
		}
1011 1012 1013 1014 1015 1016 1017 1018
	}
	else {
		m_obj->size = map_size;
	}

	/* set the initial position */
	m_obj->pos = (size_t) 0;

1019
	/* set the tag name */
1020
	if (tagname != NULL && *tagname != '\0') {
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
		m_obj->tagname = PyMem_Malloc(strlen(tagname)+1);
		if (m_obj->tagname == NULL) {
			PyErr_NoMemory();
			Py_DECREF(m_obj);
			return NULL;
		}
		strcpy(m_obj->tagname, tagname);
	}
	else
		m_obj->tagname = NULL;

1032
	m_obj->access = access;
Mark Hammond's avatar
Mark Hammond committed
1033
	m_obj->map_handle = CreateFileMapping (m_obj->file_handle,
1034
					       NULL,
1035
					       flProtect,
1036 1037
					       0,
					       m_obj->size,
1038
					       m_obj->tagname);
1039 1040
	if (m_obj->map_handle != NULL) {
		m_obj->data = (char *) MapViewOfFile (m_obj->map_handle,
1041
						      dwDesiredAccess,
1042 1043 1044 1045 1046
						      0,
						      0,
						      0);
		if (m_obj->data != NULL) {
			return ((PyObject *) m_obj);
1047
		} else {
1048
			dwErr = GetLastError();
1049
		}
1050 1051 1052
	} else {
		dwErr = GetLastError();
	}
1053
	Py_DECREF(m_obj);
1054 1055
	PyErr_SetFromWindowsErr(dwErr);
	return (NULL);
1056
}
1057
#endif /* MS_WINDOWS */
1058 1059 1060

/* List of functions exported by this module */
static struct PyMethodDef mmap_functions[] = {
1061 1062 1063
	{"mmap",	(PyCFunction) new_mmap_object, 
	 METH_VARARGS|METH_KEYWORDS},
	{NULL,		NULL}	     /* Sentinel */
1064 1065
};

1066
PyMODINIT_FUNC
1067
	initmmap(void)
1068
{
1069
	PyObject *dict, *module;
1070 1071 1072 1073

	/* Patch the object type */
	mmap_object_type.ob_type = &PyType_Type;

1074 1075 1076 1077 1078
	module = Py_InitModule ("mmap", mmap_functions);
	dict = PyModule_GetDict (module);
	mmap_module_error = PyExc_EnvironmentError;
	Py_INCREF(mmap_module_error);
	PyDict_SetItemString (dict, "error", mmap_module_error);
1079
#ifdef PROT_EXEC
1080
	PyDict_SetItemString (dict, "PROT_EXEC", PyInt_FromLong(PROT_EXEC) );
1081 1082
#endif
#ifdef PROT_READ
1083
	PyDict_SetItemString (dict, "PROT_READ", PyInt_FromLong(PROT_READ) );
1084 1085
#endif
#ifdef PROT_WRITE
1086
	PyDict_SetItemString (dict, "PROT_WRITE", PyInt_FromLong(PROT_WRITE) );
1087 1088 1089
#endif

#ifdef MAP_SHARED
1090
	PyDict_SetItemString (dict, "MAP_SHARED", PyInt_FromLong(MAP_SHARED) );
1091 1092
#endif
#ifdef MAP_PRIVATE
1093 1094
	PyDict_SetItemString (dict, "MAP_PRIVATE",
			      PyInt_FromLong(MAP_PRIVATE) );
1095 1096
#endif
#ifdef MAP_DENYWRITE
1097 1098
	PyDict_SetItemString (dict, "MAP_DENYWRITE",
			      PyInt_FromLong(MAP_DENYWRITE) );
1099 1100
#endif
#ifdef MAP_EXECUTABLE
1101 1102
	PyDict_SetItemString (dict, "MAP_EXECUTABLE",
			      PyInt_FromLong(MAP_EXECUTABLE) );
1103 1104
#endif
#ifdef MAP_ANON
1105 1106 1107
	PyDict_SetItemString (dict, "MAP_ANON", PyInt_FromLong(MAP_ANON) );
	PyDict_SetItemString (dict, "MAP_ANONYMOUS",
			      PyInt_FromLong(MAP_ANON) );
1108 1109
#endif

1110
	PyDict_SetItemString (dict, "PAGESIZE",
1111
			      PyInt_FromLong( (long)my_getpagesize() ) );
1112

1113 1114 1115 1116 1117 1118 1119
	PyDict_SetItemString (dict, "ACCESS_READ",	
			      PyInt_FromLong(ACCESS_READ));
	PyDict_SetItemString (dict, "ACCESS_WRITE", 
			      PyInt_FromLong(ACCESS_WRITE));
	PyDict_SetItemString (dict, "ACCESS_COPY",	
			      PyInt_FromLong(ACCESS_COPY));
}