memfiles.nim 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Nim Contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## :Authors: Zahary Karadjov, Andreas Rumpf
  10. ##
  11. ## This module provides support for `memory mapped files`:idx:
  12. ## (Posix's `mmap`:idx:) on the different operating systems.
  13. ##
  14. ## It also provides some fast iterators over lines in text files (or
  15. ## other "line-like", variable length, delimited records).
  16. when defined(windows):
  17. import winlean
  18. when useWinUnicode and defined(nimPreviewSlimSystem):
  19. import std/widestrs
  20. elif defined(posix):
  21. import posix
  22. else:
  23. {.error: "the memfiles module is not supported on your operating system!".}
  24. import os, streams
  25. when defined(nimPreviewSlimSystem):
  26. import std/[syncio, assertions]
  27. proc newEIO(msg: string): ref IOError =
  28. new(result)
  29. result.msg = msg
  30. type
  31. MemFile* = object ## represents a memory mapped file
  32. mem*: pointer ## a pointer to the memory mapped file. The pointer
  33. ## can be used directly to change the contents of the
  34. ## file, if it was opened with write access.
  35. size*: int ## size of the memory mapped file
  36. when defined(windows):
  37. fHandle*: Handle ## **Caution**: Windows specific public field to allow
  38. ## even more low level trickery.
  39. mapHandle*: Handle ## **Caution**: Windows specific public field.
  40. wasOpened*: bool ## **Caution**: Windows specific public field.
  41. else:
  42. handle*: cint ## **Caution**: Posix specific public field.
  43. flags: cint ## **Caution**: Platform specific private field.
  44. proc mapMem*(m: var MemFile, mode: FileMode = fmRead,
  45. mappedSize = -1, offset = 0, mapFlags = cint(-1)): pointer =
  46. ## returns a pointer to a mapped portion of MemFile `m`
  47. ##
  48. ## `mappedSize` of `-1` maps to the whole file, and
  49. ## `offset` must be multiples of the PAGE SIZE of your OS
  50. if mode == fmAppend:
  51. raise newEIO("The append mode is not supported.")
  52. var readonly = mode == fmRead
  53. when defined(windows):
  54. result = mapViewOfFileEx(
  55. m.mapHandle,
  56. if readonly: FILE_MAP_READ else: FILE_MAP_READ or FILE_MAP_WRITE,
  57. int32(offset shr 32),
  58. int32(offset and 0xffffffff),
  59. WinSizeT(if mappedSize == -1: 0 else: mappedSize),
  60. nil)
  61. if result == nil:
  62. raiseOSError(osLastError())
  63. else:
  64. assert mappedSize > 0
  65. m.flags = if mapFlags == cint(-1): MAP_SHARED else: mapFlags
  66. #Ensure exactly one of MAP_PRIVATE cr MAP_SHARED is set
  67. if int(m.flags and MAP_PRIVATE) == 0:
  68. m.flags = m.flags or MAP_SHARED
  69. result = mmap(
  70. nil,
  71. mappedSize,
  72. if readonly: PROT_READ else: PROT_READ or PROT_WRITE,
  73. m.flags,
  74. m.handle, offset)
  75. if result == cast[pointer](MAP_FAILED):
  76. raiseOSError(osLastError())
  77. proc unmapMem*(f: var MemFile, p: pointer, size: int) =
  78. ## unmaps the memory region `(p, <p+size)` of the mapped file `f`.
  79. ## All changes are written back to the file system, if `f` was opened
  80. ## with write access.
  81. ##
  82. ## `size` must be of exactly the size that was requested
  83. ## via `mapMem`.
  84. when defined(windows):
  85. if unmapViewOfFile(p) == 0: raiseOSError(osLastError())
  86. else:
  87. if munmap(p, size) != 0: raiseOSError(osLastError())
  88. proc open*(filename: string, mode: FileMode = fmRead,
  89. mappedSize = -1, offset = 0, newFileSize = -1,
  90. allowRemap = false, mapFlags = cint(-1)): MemFile =
  91. ## opens a memory mapped file. If this fails, `OSError` is raised.
  92. ##
  93. ## `newFileSize` can only be set if the file does not exist and is opened
  94. ## with write access (e.g., with fmReadWrite).
  95. ##
  96. ##`mappedSize` and `offset`
  97. ## can be used to map only a slice of the file.
  98. ##
  99. ## `offset` must be multiples of the PAGE SIZE of your OS
  100. ## (usually 4K or 8K but is unique to your OS)
  101. ##
  102. ## `allowRemap` only needs to be true if you want to call `mapMem` on
  103. ## the resulting MemFile; else file handles are not kept open.
  104. ##
  105. ## `mapFlags` allows callers to override default choices for memory mapping
  106. ## flags with a bitwise mask of a variety of likely platform-specific flags
  107. ## which may be ignored or even cause `open` to fail if misspecified.
  108. ##
  109. ## Example:
  110. ##
  111. ## .. code-block:: nim
  112. ## var
  113. ## mm, mm_full, mm_half: MemFile
  114. ##
  115. ## mm = memfiles.open("/tmp/test.mmap", mode = fmWrite, newFileSize = 1024) # Create a new file
  116. ## mm.close()
  117. ##
  118. ## # Read the whole file, would fail if newFileSize was set
  119. ## mm_full = memfiles.open("/tmp/test.mmap", mode = fmReadWrite, mappedSize = -1)
  120. ##
  121. ## # Read the first 512 bytes
  122. ## mm_half = memfiles.open("/tmp/test.mmap", mode = fmReadWrite, mappedSize = 512)
  123. # The file can be resized only when write mode is used:
  124. if mode == fmAppend:
  125. raise newEIO("The append mode is not supported.")
  126. assert newFileSize == -1 or mode != fmRead
  127. var readonly = mode == fmRead
  128. template rollback =
  129. result.mem = nil
  130. result.size = 0
  131. when defined(windows):
  132. let desiredAccess = GENERIC_READ
  133. let shareMode = FILE_SHARE_READ
  134. let flags = FILE_FLAG_RANDOM_ACCESS
  135. template fail(errCode: OSErrorCode, msg: untyped) =
  136. rollback()
  137. if result.fHandle != 0: discard closeHandle(result.fHandle)
  138. if result.mapHandle != 0: discard closeHandle(result.mapHandle)
  139. raiseOSError(errCode)
  140. # return false
  141. #raise newException(IOError, msg)
  142. template callCreateFile(winApiProc, filename): untyped =
  143. winApiProc(
  144. filename,
  145. # GENERIC_ALL != (GENERIC_READ or GENERIC_WRITE)
  146. if readonly: desiredAccess else: desiredAccess or GENERIC_WRITE,
  147. if readonly: shareMode else: shareMode or FILE_SHARE_WRITE,
  148. nil,
  149. if newFileSize != -1: CREATE_ALWAYS else: OPEN_EXISTING,
  150. if readonly: FILE_ATTRIBUTE_READONLY or flags
  151. else: FILE_ATTRIBUTE_NORMAL or flags,
  152. 0)
  153. when useWinUnicode:
  154. result.fHandle = callCreateFile(createFileW, newWideCString(filename))
  155. else:
  156. result.fHandle = callCreateFile(createFileA, filename)
  157. if result.fHandle == INVALID_HANDLE_VALUE:
  158. fail(osLastError(), "error opening file")
  159. if newFileSize != -1:
  160. var
  161. sizeHigh = int32(newFileSize shr 32)
  162. sizeLow = int32(newFileSize and 0xffffffff)
  163. var status = setFilePointer(result.fHandle, sizeLow, addr(sizeHigh),
  164. FILE_BEGIN)
  165. let lastErr = osLastError()
  166. if (status == INVALID_SET_FILE_POINTER and lastErr.int32 != NO_ERROR) or
  167. (setEndOfFile(result.fHandle) == 0):
  168. fail(lastErr, "error setting file size")
  169. # since the strings are always 'nil', we simply always call
  170. # CreateFileMappingW which should be slightly faster anyway:
  171. result.mapHandle = createFileMappingW(
  172. result.fHandle, nil,
  173. if readonly: PAGE_READONLY else: PAGE_READWRITE,
  174. 0, 0, nil)
  175. if result.mapHandle == 0:
  176. fail(osLastError(), "error creating mapping")
  177. result.mem = mapViewOfFileEx(
  178. result.mapHandle,
  179. if readonly: FILE_MAP_READ else: FILE_MAP_READ or FILE_MAP_WRITE,
  180. int32(offset shr 32),
  181. int32(offset and 0xffffffff),
  182. if mappedSize == -1: 0 else: mappedSize,
  183. nil)
  184. if result.mem == nil:
  185. fail(osLastError(), "error mapping view")
  186. var hi, low: int32
  187. low = getFileSize(result.fHandle, addr(hi))
  188. if low == INVALID_FILE_SIZE:
  189. fail(osLastError(), "error getting file size")
  190. else:
  191. var fileSize = (int64(hi) shl 32) or int64(uint32(low))
  192. if mappedSize != -1: result.size = min(fileSize, mappedSize).int
  193. else: result.size = fileSize.int
  194. result.wasOpened = true
  195. if not allowRemap and result.fHandle != INVALID_HANDLE_VALUE:
  196. if closeHandle(result.fHandle) == 0:
  197. result.fHandle = INVALID_HANDLE_VALUE
  198. else:
  199. template fail(errCode: OSErrorCode, msg: string) =
  200. rollback()
  201. if result.handle != -1: discard close(result.handle)
  202. raiseOSError(errCode)
  203. var flags = (if readonly: O_RDONLY else: O_RDWR) or O_CLOEXEC
  204. if newFileSize != -1:
  205. flags = flags or O_CREAT or O_TRUNC
  206. var permissionsMode = S_IRUSR or S_IWUSR
  207. result.handle = open(filename, flags, permissionsMode)
  208. else:
  209. result.handle = open(filename, flags)
  210. if result.handle == -1:
  211. # XXX: errno is supposed to be set here
  212. # Is there an exception that wraps it?
  213. fail(osLastError(), "error opening file")
  214. if newFileSize != -1:
  215. if ftruncate(result.handle, newFileSize) == -1:
  216. fail(osLastError(), "error setting file size")
  217. if mappedSize != -1:
  218. result.size = mappedSize
  219. else:
  220. var stat: Stat
  221. if fstat(result.handle, stat) != -1:
  222. # XXX: Hmm, this could be unsafe
  223. # Why is mmap taking int anyway?
  224. result.size = int(stat.st_size)
  225. else:
  226. fail(osLastError(), "error getting file size")
  227. result.flags = if mapFlags == cint(-1): MAP_SHARED else: mapFlags
  228. #Ensure exactly one of MAP_PRIVATE cr MAP_SHARED is set
  229. if int(result.flags and MAP_PRIVATE) == 0:
  230. result.flags = result.flags or MAP_SHARED
  231. result.mem = mmap(
  232. nil,
  233. result.size,
  234. if readonly: PROT_READ else: PROT_READ or PROT_WRITE,
  235. result.flags,
  236. result.handle,
  237. offset)
  238. if result.mem == cast[pointer](MAP_FAILED):
  239. fail(osLastError(), "file mapping failed")
  240. if not allowRemap and result.handle != -1:
  241. if close(result.handle) == 0:
  242. result.handle = -1
  243. proc flush*(f: var MemFile; attempts: Natural = 3) =
  244. ## Flushes `f`'s buffer for the number of attempts equal to `attempts`.
  245. ## If were errors an exception `OSError` will be raised.
  246. var res = false
  247. var lastErr: OSErrorCode
  248. when defined(windows):
  249. for i in 1..attempts:
  250. res = flushViewOfFile(f.mem, 0) != 0
  251. if res:
  252. break
  253. lastErr = osLastError()
  254. if lastErr != ERROR_LOCK_VIOLATION.OSErrorCode:
  255. raiseOSError(lastErr)
  256. else:
  257. for i in 1..attempts:
  258. res = msync(f.mem, f.size, MS_SYNC or MS_INVALIDATE) == 0
  259. if res:
  260. break
  261. lastErr = osLastError()
  262. if lastErr != EBUSY.OSErrorCode:
  263. raiseOSError(lastErr, "error flushing mapping")
  264. when defined(posix) or defined(nimdoc):
  265. proc resize*(f: var MemFile, newFileSize: int) {.raises: [IOError, OSError].} =
  266. ## resize and re-map the file underlying an `allowRemap MemFile`.
  267. ## **Note**: this assumes the entire file is mapped read-write at offset zero.
  268. ## Also, the value of `.mem` will probably change.
  269. ## **Note**: This is not (yet) available on Windows.
  270. when defined(posix):
  271. if f.handle == -1:
  272. raise newException(IOError,
  273. "Cannot resize MemFile opened with allowRemap=false")
  274. if ftruncate(f.handle, newFileSize) == -1:
  275. raiseOSError(osLastError())
  276. when defined(linux): #Maybe NetBSD, too?
  277. #On Linux this can be over 100 times faster than a munmap,mmap cycle.
  278. proc mremap(old: pointer; oldSize, newSize: csize_t; flags: cint):
  279. pointer {.importc: "mremap", header: "<sys/mman.h>".}
  280. let newAddr = mremap(f.mem, csize_t(f.size), csize_t(newFileSize), cint(1))
  281. if newAddr == cast[pointer](MAP_FAILED):
  282. raiseOSError(osLastError())
  283. else:
  284. if munmap(f.mem, f.size) != 0:
  285. raiseOSError(osLastError())
  286. let newAddr = mmap(nil, newFileSize, PROT_READ or PROT_WRITE,
  287. f.flags, f.handle, 0)
  288. if newAddr == cast[pointer](MAP_FAILED):
  289. raiseOSError(osLastError())
  290. f.mem = newAddr
  291. f.size = newFileSize
  292. proc close*(f: var MemFile) =
  293. ## closes the memory mapped file `f`. All changes are written back to the
  294. ## file system, if `f` was opened with write access.
  295. var error = false
  296. var lastErr: OSErrorCode
  297. when defined(windows):
  298. if f.wasOpened:
  299. error = unmapViewOfFile(f.mem) == 0
  300. if not error:
  301. error = closeHandle(f.mapHandle) == 0
  302. if not error and f.fHandle != INVALID_HANDLE_VALUE:
  303. discard closeHandle(f.fHandle)
  304. f.fHandle = INVALID_HANDLE_VALUE
  305. if error:
  306. lastErr = osLastError()
  307. else:
  308. error = munmap(f.mem, f.size) != 0
  309. lastErr = osLastError()
  310. if f.handle != -1:
  311. error = (close(f.handle) != 0) or error
  312. f.size = 0
  313. f.mem = nil
  314. when defined(windows):
  315. f.fHandle = 0
  316. f.mapHandle = 0
  317. f.wasOpened = false
  318. else:
  319. f.handle = -1
  320. if error: raiseOSError(lastErr)
  321. type MemSlice* = object ## represent slice of a MemFile for iteration over delimited lines/records
  322. data*: pointer
  323. size*: int
  324. proc `==`*(x, y: MemSlice): bool =
  325. ## Compare a pair of MemSlice for strict equality.
  326. result = (x.size == y.size and equalMem(x.data, y.data, x.size))
  327. proc `$`*(ms: MemSlice): string {.inline.} =
  328. ## Return a Nim string built from a MemSlice.
  329. result.setLen(ms.size)
  330. copyMem(addr(result[0]), ms.data, ms.size)
  331. iterator memSlices*(mfile: MemFile, delim = '\l', eat = '\r'): MemSlice {.inline.} =
  332. ## Iterates over \[optional `eat`] `delim`-delimited slices in MemFile `mfile`.
  333. ##
  334. ## Default parameters parse lines ending in either Unix(\\l) or Windows(\\r\\l)
  335. ## style on on a line-by-line basis. I.e., not every line needs the same ending.
  336. ## Unlike readLine(File) & lines(File), archaic MacOS9 \\r-delimited lines
  337. ## are not supported as a third option for each line. Such archaic MacOS9
  338. ## files can be handled by passing delim='\\r', eat='\\0', though.
  339. ##
  340. ## Delimiters are not part of the returned slice. A final, unterminated line
  341. ## or record is returned just like any other.
  342. ##
  343. ## Non-default delimiters can be passed to allow iteration over other sorts
  344. ## of "line-like" variable length records. Pass eat='\\0' to be strictly
  345. ## `delim`-delimited. (Eating an optional prefix equal to '\\0' is not
  346. ## supported.)
  347. ##
  348. ## This zero copy, memchr-limited interface is probably the fastest way to
  349. ## iterate over line-like records in a file. However, returned (data,size)
  350. ## objects are not Nim strings, bounds checked Nim arrays, or even terminated
  351. ## C strings. So, care is required to access the data (e.g., think C mem*
  352. ## functions, not str* functions).
  353. ##
  354. ## Example:
  355. ##
  356. ## .. code-block:: nim
  357. ## var count = 0
  358. ## for slice in memSlices(memfiles.open("foo")):
  359. ## if slice.size > 0 and cast[cstring](slice.data)[0] != '#':
  360. ## inc(count)
  361. ## echo count
  362. proc c_memchr(cstr: pointer, c: char, n: csize_t): pointer {.
  363. importc: "memchr", header: "<string.h>".}
  364. proc `-!`(p, q: pointer): int {.inline.} = return cast[int](p) -% cast[int](q)
  365. var ms: MemSlice
  366. var ending: pointer
  367. ms.data = mfile.mem
  368. var remaining = mfile.size
  369. while remaining > 0:
  370. ending = c_memchr(ms.data, delim, csize_t(remaining))
  371. if ending == nil: # unterminated final slice
  372. ms.size = remaining # Weird case..check eat?
  373. yield ms
  374. break
  375. ms.size = ending -! ms.data # delim is NOT included
  376. if eat != '\0' and ms.size > 0 and cast[cstring](ms.data)[ms.size - 1] == eat:
  377. dec(ms.size) # trim pre-delim char
  378. yield ms
  379. ms.data = cast[pointer](cast[int](ending) +% 1) # skip delim
  380. remaining = mfile.size - (ms.data -! mfile.mem)
  381. iterator lines*(mfile: MemFile, buf: var string, delim = '\l',
  382. eat = '\r'): string {.inline.} =
  383. ## Replace contents of passed buffer with each new line, like
  384. ## `readLine(File) <syncio.html#readLine,File,string>`_.
  385. ## `delim`, `eat`, and delimiting logic is exactly as for `memSlices
  386. ## <#memSlices.i,MemFile,char,char>`_, but Nim strings are returned.
  387. ##
  388. ## Example:
  389. ##
  390. ## .. code-block:: nim
  391. ## var buffer: string = ""
  392. ## for line in lines(memfiles.open("foo"), buffer):
  393. ## echo line
  394. for ms in memSlices(mfile, delim, eat):
  395. setLen(buf, ms.size)
  396. if ms.size > 0:
  397. copyMem(addr buf[0], ms.data, ms.size)
  398. yield buf
  399. iterator lines*(mfile: MemFile, delim = '\l', eat = '\r'): string {.inline.} =
  400. ## Return each line in a file as a Nim string, like
  401. ## `lines(File) <syncio.html#lines.i,File>`_.
  402. ## `delim`, `eat`, and delimiting logic is exactly as for `memSlices
  403. ## <#memSlices.i,MemFile,char,char>`_, but Nim strings are returned.
  404. ##
  405. ## Example:
  406. ##
  407. ## .. code-block:: nim
  408. ## for line in lines(memfiles.open("foo")):
  409. ## echo line
  410. var buf = newStringOfCap(80)
  411. for line in lines(mfile, buf, delim, eat):
  412. yield buf
  413. type
  414. MemMapFileStream* = ref MemMapFileStreamObj ## a stream that encapsulates a `MemFile`
  415. MemMapFileStreamObj* = object of Stream
  416. mf: MemFile
  417. mode: FileMode
  418. pos: ByteAddress
  419. proc mmsClose(s: Stream) =
  420. MemMapFileStream(s).pos = -1
  421. close(MemMapFileStream(s).mf)
  422. proc mmsFlush(s: Stream) = flush(MemMapFileStream(s).mf)
  423. proc mmsAtEnd(s: Stream): bool = (MemMapFileStream(s).pos >= MemMapFileStream(s).mf.size) or
  424. (MemMapFileStream(s).pos < 0)
  425. proc mmsSetPosition(s: Stream, pos: int) =
  426. if pos > MemMapFileStream(s).mf.size or pos < 0:
  427. raise newEIO("cannot set pos in stream")
  428. MemMapFileStream(s).pos = pos
  429. proc mmsGetPosition(s: Stream): int = MemMapFileStream(s).pos
  430. proc mmsPeekData(s: Stream, buffer: pointer, bufLen: int): int =
  431. let startAddress = cast[ByteAddress](MemMapFileStream(s).mf.mem)
  432. let p = cast[ByteAddress](MemMapFileStream(s).pos)
  433. let l = min(bufLen, MemMapFileStream(s).mf.size - p)
  434. moveMem(buffer, cast[pointer](startAddress + p), l)
  435. result = l
  436. proc mmsReadData(s: Stream, buffer: pointer, bufLen: int): int =
  437. result = mmsPeekData(s, buffer, bufLen)
  438. inc(MemMapFileStream(s).pos, result)
  439. proc mmsWriteData(s: Stream, buffer: pointer, bufLen: int) =
  440. if MemMapFileStream(s).mode == fmRead:
  441. raise newEIO("cannot write to read-only stream")
  442. let size = MemMapFileStream(s).mf.size
  443. if MemMapFileStream(s).pos + bufLen > size:
  444. raise newEIO("cannot write to stream")
  445. let p = cast[ByteAddress](MemMapFileStream(s).mf.mem) +
  446. cast[ByteAddress](MemMapFileStream(s).pos)
  447. moveMem(cast[pointer](p), buffer, bufLen)
  448. inc(MemMapFileStream(s).pos, bufLen)
  449. proc newMemMapFileStream*(filename: string, mode: FileMode = fmRead,
  450. fileSize: int = -1): MemMapFileStream =
  451. ## creates a new stream from the file named `filename` with the mode `mode`.
  452. ## Raises ## `OSError` if the file cannot be opened. See the `system
  453. ## <system.html>`_ module for a list of available FileMode enums.
  454. ## `fileSize` can only be set if the file does not exist and is opened
  455. ## with write access (e.g., with fmReadWrite).
  456. var mf: MemFile = open(filename, mode, newFileSize = fileSize)
  457. new(result)
  458. result.mode = mode
  459. result.mf = mf
  460. result.closeImpl = mmsClose
  461. result.atEndImpl = mmsAtEnd
  462. result.setPositionImpl = mmsSetPosition
  463. result.getPositionImpl = mmsGetPosition
  464. result.readDataImpl = mmsReadData
  465. result.peekDataImpl = mmsPeekData
  466. result.writeDataImpl = mmsWriteData
  467. result.flushImpl = mmsFlush