| 1 | /* |
| 2 | * Copyright (C) 2003 Dizzy |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or |
| 5 | * modify it under the terms of the GNU General Public License |
| 6 | * as published by the Free Software Foundation; either version 2 |
| 7 | * of the License, or (at your option) any later version. |
| 8 | * |
| 9 | * This program is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU General Public License |
| 15 | * along with this program; if not, write to the Free Software |
| 16 | * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
| 17 | */ |
| 18 | #include "common/setup_before.h" |
| 19 | #ifndef HAVE_MMAP |
| 20 | #include <cstdlib> |
| 21 | #ifdef HAVE_SYS_TYPES_H |
| 22 | # include <sys/types.h> |
| 23 | #endif |
| 24 | #ifdef HAVE_UNISTD_H |
| 25 | # include <unistd.h> |
| 26 | #endif |
| 27 | #include "common/xalloc.h" |
| 28 | #include "mmap.h" |
| 29 | #ifdef HAVE_WINDOWS_H |
| 30 | #include <Windows.h> |
| 31 | #endif |
| 32 | #ifdef WIN32 |
| 33 | # include <io.h> |
| 34 | #endif |
| 35 | #include "common/setup_after.h" |
| 36 | |
| 37 | namespace pvpgn |
| 38 | { |
| 39 | |
| 40 | extern void * pmmap(void *addr, unsigned len, int prot, int flags, int fd, unsigned offset) |
| 41 | { |
| 42 | void *mem; |
| 43 | #ifdef WIN32 |
| 44 | HANDLE hFile, hMapping; |
| 45 | |
| 46 | /* under win32 we only support readonly mappings, the only ones used in pvpgn now :) */ |
| 47 | if (prot != PROT_READ) return NULL; |
| 48 | hFile = (HANDLE)_get_osfhandle(fd); |
| 49 | if (hFile == (HANDLE)-1) return MAP_FAILED; |
| 50 | hMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); |
| 51 | if (!hMapping) return MAP_FAILED; |
| 52 | mem = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0); |
| 53 | #else /* systems without mmap or win32 */ |
| 54 | unsigned pos; |
| 55 | int res; |
| 56 | |
| 57 | mem = xmalloc(len); |
| 58 | pos = 0; |
| 59 | while (pos < len) { |
| 60 | res = read(fd, (char *)mem + pos, len - pos); |
| 61 | if (res < 0) { |
| 62 | xfree(mem); |
| 63 | return MAP_FAILED; |
| 64 | } |
| 65 | pos += res; |
| 66 | } |
| 67 | #endif |
| 68 | |
| 69 | return mem; |
| 70 | } |
| 71 | |
| 72 | extern int pmunmap(void *addr, unsigned len) |
| 73 | { |
| 74 | #ifdef WIN32 |
| 75 | UnmapViewOfFile(addr); |
| 76 | #else |
| 77 | xfree(addr); |
| 78 | #endif |
| 79 | return 0; |
| 80 | } |
| 81 | |
| 82 | } |
| 83 | |
| 84 | #else |
| 85 | typedef int filenotempty; /* make ISO standard happy */ |
| 86 | #endif |