├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── c_src ├── emmap.cpp └── erl_nif_compat.h ├── doc ├── README.md ├── emmap.md └── overview.edoc ├── ebin └── emmap.app ├── rebar ├── rebar.config └── src └── emmap.erl /.gitignore: -------------------------------------------------------------------------------- 1 | .eunit 2 | *~ 3 | *.so 4 | *.beam 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | all: 3 | ./rebar compile eunit 4 | 5 | clean: 6 | ./rebar clean -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Erlang MMAP `emmap` 2 | 3 | This Erlang library provides a wrapper that allows you to memory map files into the Erlang memory space. 4 | 5 | 6 | ## Basic Usage 7 | 8 | The basic usage is 9 | 10 | {ok, Mem} = emmap:open("filename", [read, shared, direct]), 11 | {ok, Binary} = file:pread(Mem, 100, 40), 12 | ... 13 | ok = file:close(Mem). 14 | 15 | The open options is a list containing zero or more of these: 16 | 17 | - `read`, `write`: Open for reading and/or writing (you can specify both). 18 | - `private`, `shared`: The file is opened with copy-on-write semantics, or sharing memory with the underlying file. 19 | - `direct`: read/pread operations do not copy memory, but rather use "resource binaries" that can change content if the underlying data is changed. This is the most performant, but also has other implications. 20 | - `lock`, `nolock` do (or do not) use a semaphore to control state changes internally in the NIF library. 21 | 22 | From this point, `Mem` can be used with the `file` operations 23 | 24 | - `{ok, Binary} = file:pread(Mem, Position, Length)` read Length bytes at Position in the file. 25 | - `ok = file:pwrite(Mem, Position, Binary)` writes to the given position. 26 | - `{ok, Binary} = file:read(Mem, Length)` read 1..Length bytes from current position, or return `eof` if pointer is at end of file. 27 | - `{ok, Pos} = file:position(Mem, Where)` see file:position/2 documentation. 28 | - `ok = file:close(Mem)` 29 | 30 | ## Notes 31 | 32 | Using the option `direct` has the effect that the mmap file is not closed until all references to binaries coming out of read/pread have been garbage collected. This is a consequence of that such binaries are referring directly to the mmap'ed memory. 33 | 34 | -------------------------------------------------------------------------------- /c_src/emmap.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include "erl_nif_compat.h" 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | static ErlNifResourceType* MMAP_RESOURCE; 11 | 12 | #ifndef MAP_NOCACHE 13 | /* No MAP_NOCACHE on Linux - just bypass this option */ 14 | #define MAP_NOCACHE (0) 15 | #endif 16 | 17 | typedef struct 18 | { 19 | size_t position; 20 | int direct; 21 | int prot; 22 | bool closed; 23 | ErlNifRWLock* rwlock; 24 | void* mem; 25 | size_t len; 26 | } mhandle; 27 | 28 | static int on_load(ErlNifEnv*, void**, ERL_NIF_TERM); 29 | 30 | static int emmap_unmap(mhandle *handle, bool from_dtor) 31 | { 32 | if (handle->mem != 0) { 33 | if (from_dtor || !handle->direct) { 34 | int result = munmap(handle->mem, handle->len); 35 | handle->mem = 0; 36 | return result; 37 | } else { 38 | handle->closed = true; 39 | } 40 | } 41 | return 0; 42 | } 43 | 44 | void emmap_dtor(ErlNifEnv* env, void* arg) 45 | { 46 | mhandle* handle = (mhandle*)arg; 47 | emmap_unmap(handle, true); 48 | 49 | // only the destructor destroys the rwlock 50 | if (handle->rwlock != 0) enif_rwlock_destroy(handle->rwlock); 51 | } 52 | 53 | #define RW_UNLOCK if (handle->rwlock != 0) enif_rwlock_rwunlock(handle->rwlock) 54 | #define RW_LOCK if (handle->rwlock != 0) enif_rwlock_rwlock(handle->rwlock) 55 | #define R_UNLOCK if (handle->rwlock != 0) enif_rwlock_runlock(handle->rwlock) 56 | #define R_LOCK if (handle->rwlock != 0) enif_rwlock_rlock(handle->rwlock) 57 | 58 | static ERL_NIF_TERM ATOM_OK; 59 | static ERL_NIF_TERM ATOM_TRUE; 60 | static ERL_NIF_TERM ATOM_FALSE; 61 | static ERL_NIF_TERM ATOM_ERROR; 62 | static ERL_NIF_TERM ATOM_LOCK; 63 | static ERL_NIF_TERM ATOM_NOLOCK; 64 | static ERL_NIF_TERM ATOM_DIRECT; 65 | static ERL_NIF_TERM ATOM_READ; 66 | static ERL_NIF_TERM ATOM_WRITE; 67 | static ERL_NIF_TERM ATOM_NONE; 68 | static ERL_NIF_TERM ATOM_PRIVATE; 69 | static ERL_NIF_TERM ATOM_SHARED; 70 | static ERL_NIF_TERM ATOM_ANON; 71 | static ERL_NIF_TERM ATOM_FILE; 72 | static ERL_NIF_TERM ATOM_FIXED; 73 | static ERL_NIF_TERM ATOM_NOCACHE; 74 | 75 | static ERL_NIF_TERM ATOM_BOF; 76 | static ERL_NIF_TERM ATOM_CUR; 77 | static ERL_NIF_TERM ATOM_EOF; 78 | 79 | static ERL_NIF_TERM emmap_open(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); 80 | static ERL_NIF_TERM emmap_read(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); 81 | static ERL_NIF_TERM emmap_read_line(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); 82 | static ERL_NIF_TERM emmap_close(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); 83 | static ERL_NIF_TERM emmap_pread(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); 84 | static ERL_NIF_TERM emmap_pwrite(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); 85 | static ERL_NIF_TERM emmap_position(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); 86 | 87 | extern "C" { 88 | 89 | static ErlNifFunc nif_funcs[] = 90 | { 91 | {"open_nif", 4, emmap_open}, 92 | {"close_nif", 1, emmap_close}, 93 | {"pread_nif", 3, emmap_pread}, 94 | {"pwrite_nif", 3, emmap_pwrite}, 95 | {"position_nif", 3, emmap_position}, 96 | {"read_nif", 2, emmap_read}, 97 | {"read_line_nif", 1, emmap_read_line}, 98 | }; 99 | 100 | ERL_NIF_INIT(emmap, nif_funcs, &on_load, NULL, NULL, NULL); 101 | }; 102 | 103 | static int on_load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info) 104 | { 105 | ErlNifResourceFlags flags = (ErlNifResourceFlags)(ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER); 106 | MMAP_RESOURCE = enif_open_resource_type_compat(env, "mmap_resource", &emmap_dtor, flags, 0); 107 | 108 | ATOM_OK = enif_make_atom(env, "ok"); 109 | ATOM_TRUE = enif_make_atom(env, "true"); 110 | ATOM_FALSE = enif_make_atom(env, "false"); 111 | ATOM_ERROR = enif_make_atom(env, "error"); 112 | 113 | ATOM_DIRECT = enif_make_atom(env, "direct"); 114 | ATOM_READ = enif_make_atom(env, "read"); 115 | ATOM_WRITE = enif_make_atom(env, "write"); 116 | ATOM_NONE = enif_make_atom(env, "none"); 117 | ATOM_PRIVATE = enif_make_atom(env, "private"); 118 | ATOM_SHARED = enif_make_atom(env, "shared"); 119 | ATOM_ANON = enif_make_atom(env, "anon"); 120 | ATOM_FILE = enif_make_atom(env, "file"); 121 | ATOM_FIXED = enif_make_atom(env, "fixed"); 122 | ATOM_NOCACHE = enif_make_atom(env, "nocache"); 123 | 124 | ATOM_BOF = enif_make_atom(env, "bof"); 125 | ATOM_CUR = enif_make_atom(env, "cur"); 126 | ATOM_EOF = enif_make_atom(env, "eof"); 127 | 128 | ATOM_LOCK = enif_make_atom(env, "lock"); 129 | ATOM_NOLOCK = enif_make_atom(env, "nolock"); 130 | 131 | return 0; 132 | } 133 | 134 | static ERL_NIF_TERM describe_error(ErlNifEnv* env, int err) { 135 | switch (err) { 136 | case EAGAIN: 137 | return enif_make_atom(env, "eagain"); 138 | case EINVAL: 139 | return enif_make_atom(env, "einval"); 140 | case ENOSPC: 141 | return enif_make_atom(env, "enospc"); 142 | case ENOENT: 143 | return enif_make_atom(env, "enoent"); 144 | case ENOMEM: 145 | return enif_make_atom(env, "enomem"); 146 | case EACCES: 147 | return enif_make_atom(env, "eacces"); 148 | case EBADF: 149 | return enif_make_atom(env, "ebadf"); 150 | case ENODEV: 151 | return enif_make_atom(env, "enodev"); 152 | case ENXIO: 153 | return enif_make_atom(env, "enxio"); 154 | case EOVERFLOW: 155 | return enif_make_atom(env, "eoverflow"); 156 | } 157 | return enif_make_tuple2(env, 158 | enif_make_atom(env, "errno"), 159 | enif_make_int(env, err)); 160 | } 161 | 162 | static ERL_NIF_TERM make_error_tuple(ErlNifEnv* env, int err) { 163 | return enif_make_tuple2(env, ATOM_ERROR, describe_error(env, err)); 164 | } 165 | 166 | 167 | int decode_flags(ErlNifEnv* env, ERL_NIF_TERM list, int *prot, int *flags, bool *direct, bool *lock) 168 | { 169 | bool l = true; 170 | bool d = false; 171 | int f = MAP_FILE; 172 | int p = 0; 173 | ERL_NIF_TERM head; 174 | while (enif_get_list_cell(env, list, &head, &list)) { 175 | 176 | if (enif_is_identical(head, ATOM_READ)) { 177 | p |= PROT_READ; 178 | } else if (enif_is_identical(head, ATOM_DIRECT)) { 179 | d = true; 180 | } else if (enif_is_identical(head, ATOM_LOCK)) { 181 | l = true; 182 | } else if (enif_is_identical(head, ATOM_NOLOCK)) { 183 | l = false; 184 | } else if (enif_is_identical(head, ATOM_WRITE)) { 185 | p |= PROT_WRITE; 186 | // } else if (enif_is_identical(head, ATOM_NONE)) { 187 | // p |= PROT_NONE; 188 | 189 | } else if (enif_is_identical(head, ATOM_PRIVATE)) { 190 | f |= MAP_PRIVATE; 191 | } else if (enif_is_identical(head, ATOM_SHARED)) { 192 | f |= MAP_SHARED; 193 | // } else if (enif_is_identical(head, ATOM_ANON)) { 194 | // f |= MAP_ANON; 195 | // } else if (enif_is_identical(head, ATOM_FILE)) { 196 | // f |= MAP_FILE; 197 | // } else if (enif_is_identical(head, ATOM_FIXED)) { 198 | // f |= MAP_FIXED; 199 | } else if (enif_is_identical(head, ATOM_NOCACHE)) { 200 | f |= MAP_NOCACHE; 201 | 202 | } else { 203 | return 0; 204 | } 205 | } 206 | 207 | // direct cannot be write 208 | if (d & ((p & PROT_WRITE) != 0)) 209 | return 0; 210 | 211 | // default to private 212 | if ((f & (MAP_SHARED|MAP_PRIVATE)) == 0) 213 | f |= MAP_PRIVATE; 214 | 215 | // default to read-only 216 | if ((p & (PROT_READ|PROT_WRITE)) == 0) 217 | p |= PROT_READ; 218 | 219 | *flags = f; 220 | *prot = p; 221 | *direct = d; 222 | *lock = l; 223 | 224 | return 1; 225 | } 226 | 227 | static ERL_NIF_TERM emmap_open(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) 228 | { 229 | int flags; 230 | int prot; 231 | bool direct, lock; 232 | unsigned long int len; 233 | unsigned long int offset; 234 | char buf[1024]; 235 | 236 | #ifndef NDEBUG 237 | if ( sizeof(long int) != sizeof(size_t) ) { 238 | abort(); 239 | } 240 | #endif 241 | 242 | if (argc == 4 243 | && enif_get_string(env, argv[0], buf, 1024, ERL_NIF_LATIN1) 244 | && enif_get_ulong(env, argv[1], &offset) 245 | && enif_get_ulong(env, argv[2], &len) 246 | && decode_flags(env, argv[3], &prot, &flags, &direct, &lock)) { 247 | 248 | int mode = (((prot & PROT_WRITE)==PROT_WRITE) ? O_RDWR : O_RDONLY); 249 | 250 | int fd = open(buf, mode); 251 | if (fd < 0) { 252 | return make_error_tuple(env, errno); 253 | } 254 | 255 | void * res = mmap(0, (size_t) len, prot, flags, fd, (size_t) offset); 256 | if (res == MAP_FAILED) { 257 | return make_error_tuple(env, errno); 258 | } 259 | 260 | close(fd); 261 | 262 | mhandle* handle = (mhandle*)enif_alloc_resource_compat(env, MMAP_RESOURCE, 263 | sizeof(mhandle)); 264 | 265 | if (lock) 266 | handle->rwlock = enif_rwlock_create((char*)"mmap"); 267 | else 268 | handle->rwlock = 0; 269 | 270 | handle->prot = prot; 271 | handle->mem = res; 272 | handle->len = len; 273 | handle->closed = false; 274 | handle->direct = direct; 275 | handle->position = 0; 276 | 277 | ERL_NIF_TERM resource = enif_make_resource(env, handle); 278 | enif_release_resource_compat(env, handle); 279 | 280 | return enif_make_tuple2(env, 281 | enif_make_atom(env, "ok"), 282 | resource); 283 | 284 | } else { 285 | return enif_make_badarg(env); 286 | } 287 | } 288 | 289 | static ERL_NIF_TERM emmap_close(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) 290 | { 291 | mhandle *handle; 292 | if (argc==1 && enif_get_resource(env, argv[0], MMAP_RESOURCE, (void**)&handle)) 293 | { 294 | int res; 295 | RW_LOCK; 296 | res = emmap_unmap(handle, false); 297 | RW_UNLOCK; 298 | 299 | if (res == 0) { 300 | return ATOM_OK; 301 | } 302 | 303 | return make_error_tuple(env, errno); 304 | } 305 | else 306 | { 307 | return enif_make_badarg(env); 308 | } 309 | } 310 | 311 | static ERL_NIF_TERM emmap_pread(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) 312 | { 313 | unsigned long pos, bytes; 314 | mhandle *handle; 315 | if (argc==3 316 | && enif_get_resource(env, argv[0], MMAP_RESOURCE, (void**)&handle) 317 | && enif_get_ulong(env, argv[1], &pos) 318 | && enif_get_ulong(env, argv[2], &bytes) 319 | && pos >= 0 320 | && bytes >= 0 321 | && pos <= handle->len 322 | ) 323 | { 324 | // Adjust bytes to behave like original file:pread/3 325 | if (pos + bytes > handle->len) bytes = handle->len - pos; 326 | 327 | ErlNifBinary bin; 328 | 329 | if ((handle->prot & PROT_READ) == 0) { 330 | return make_error_tuple(env, EACCES); 331 | } 332 | 333 | // if this mmap is direct, use a resource binary 334 | if (handle->direct) { 335 | 336 | ERL_NIF_TERM res = enif_make_resource_binary 337 | (env, handle, (void*) (((char*)handle->mem) + pos), bytes); 338 | 339 | return enif_make_tuple2(env, ATOM_OK, res); 340 | 341 | } else { 342 | 343 | // When it is non-direct, we have to allocate the binary 344 | if (!enif_alloc_binary((size_t) bytes, &bin)) { 345 | return make_error_tuple(env, ENOMEM); 346 | } 347 | 348 | R_LOCK; 349 | if (handle->closed) { 350 | R_UNLOCK; 351 | return enif_make_badarg(env); 352 | } 353 | memcpy(bin.data, (void*) (((char*)handle->mem) + pos), bytes); 354 | R_UNLOCK; 355 | 356 | ERL_NIF_TERM res = enif_make_binary(env, &bin); 357 | return enif_make_tuple2(env, ATOM_OK, res); 358 | } 359 | } 360 | else 361 | { 362 | return enif_make_badarg(env); 363 | } 364 | } 365 | 366 | static ERL_NIF_TERM emmap_pwrite(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) 367 | { 368 | ErlNifBinary bin; 369 | unsigned long pos; 370 | mhandle *handle; 371 | if (argc==3 372 | && enif_get_resource(env, argv[0], MMAP_RESOURCE, (void**)&handle) 373 | && enif_get_ulong(env, argv[1], &pos) 374 | && enif_inspect_binary(env, argv[2], &bin) 375 | && pos >= 0 376 | && (pos + bin.size) <= handle->len 377 | ) 378 | { 379 | 380 | if ((handle->prot & PROT_WRITE) == 0) { 381 | return make_error_tuple(env, EACCES); 382 | } 383 | 384 | RW_LOCK; 385 | if (handle->closed) { 386 | RW_UNLOCK; 387 | return enif_make_badarg(env); 388 | } else { 389 | memcpy((void*) (((char*)handle->mem) + pos), bin.data, bin.size); 390 | RW_UNLOCK; 391 | } 392 | 393 | return ATOM_OK; 394 | } 395 | else 396 | { 397 | return enif_make_badarg(env); 398 | } 399 | } 400 | 401 | static ERL_NIF_TERM emmap_read(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) 402 | { 403 | mhandle *handle; 404 | unsigned long bytes; 405 | 406 | if (enif_get_resource(env, argv[0], MMAP_RESOURCE, (void**)&handle) 407 | && enif_get_ulong(env, argv[1], &bytes)) { 408 | 409 | 410 | RW_LOCK; 411 | 412 | if (handle->position == handle->len) { 413 | RW_UNLOCK; 414 | return ATOM_EOF; 415 | } 416 | 417 | unsigned long new_pos = handle->position + bytes; 418 | if (new_pos > handle->len) { new_pos = handle->len; } 419 | long size = new_pos - handle->position; 420 | long start = handle->position; 421 | handle->position = new_pos; 422 | RW_UNLOCK; 423 | 424 | if (handle->direct) { 425 | 426 | ERL_NIF_TERM res = enif_make_resource_binary 427 | (env, handle, (void*) (((char*)handle->mem) + start), size); 428 | 429 | return enif_make_tuple2(env, ATOM_OK, res); 430 | 431 | } else { 432 | 433 | ErlNifBinary bin; 434 | // When it is non-direct, we have to allocate the binary 435 | if (!enif_alloc_binary((size_t) size, &bin)) { 436 | return make_error_tuple(env, ENOMEM); 437 | } 438 | 439 | memcpy(bin.data, (void*) (((char*)handle->mem) + start), size); 440 | 441 | ERL_NIF_TERM res = enif_make_binary(env, &bin); 442 | return enif_make_tuple2(env, ATOM_OK, res); 443 | } 444 | 445 | } else { 446 | return enif_make_badarg(env); 447 | } 448 | } 449 | 450 | static ERL_NIF_TERM emmap_read_line(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) 451 | { 452 | mhandle *handle; 453 | 454 | if (enif_get_resource(env, argv[0], MMAP_RESOURCE, (void**)&handle)) { 455 | 456 | RW_LOCK; 457 | 458 | if (handle->position == handle->len) { 459 | RW_UNLOCK; 460 | return ATOM_EOF; 461 | } 462 | 463 | long start = handle->position; 464 | char *current = ((char*)handle->mem) + handle->position; 465 | long linelen = 0; // Length of line without trailing \n 466 | long no_crlf_len = 0; 467 | bool have_cr = false; 468 | bool got_eof = false; 469 | 470 | // Read buffer until \n or EOF is reached 471 | while (*current != '\n') { 472 | handle->position ++; 473 | current ++; 474 | if (handle->position == handle->len) { 475 | got_eof = true; 476 | break; 477 | } 478 | } 479 | // Step to next byte if EOF is not reached 480 | if (not got_eof) { 481 | handle->position ++; 482 | } 483 | 484 | no_crlf_len = linelen = handle->position - start; 485 | 486 | if (not got_eof) { 487 | // Found LF -- exclude it from line 488 | no_crlf_len --; 489 | // If line length before \n is non-zero check if we have \r before \n 490 | if ((no_crlf_len > 0) && (*(current - 1) == '\r')) { 491 | have_cr = true; 492 | no_crlf_len --; 493 | } 494 | } 495 | 496 | RW_UNLOCK; 497 | 498 | // We must not include CR before LF in result, so use direct only without CR 499 | if ((handle->direct) && (not have_cr)) { 500 | 501 | // Include trailing LF if we have it 502 | ERL_NIF_TERM res = enif_make_resource_binary 503 | (env, handle, (void*) (((char*)handle->mem) + start), linelen); 504 | 505 | return enif_make_tuple2(env, ATOM_OK, res); 506 | 507 | } else { 508 | if (not got_eof) linelen = no_crlf_len + 1; 509 | 510 | ErlNifBinary bin; 511 | // When it is non-direct, we have to allocate the binary 512 | if (!enif_alloc_binary((size_t) linelen, &bin)) { 513 | return make_error_tuple(env, ENOMEM); 514 | } 515 | 516 | memcpy(bin.data, (void*) (((char*)handle->mem) + start), no_crlf_len); 517 | // Set trailing \n if needed 518 | if (not got_eof) *(((char*)bin.data) + no_crlf_len) = '\n'; 519 | 520 | ERL_NIF_TERM res = enif_make_binary(env, &bin); 521 | return enif_make_tuple2(env, ATOM_OK, res); 522 | } 523 | 524 | } else { 525 | return enif_make_badarg(env); 526 | } 527 | } 528 | 529 | static ERL_NIF_TERM emmap_position(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) 530 | { 531 | mhandle *handle; 532 | long position; 533 | long relpos; 534 | if (argc==3 535 | && enif_get_resource(env, argv[0], MMAP_RESOURCE, (void**)&handle) 536 | && enif_get_long(env, argv[2], &relpos) 537 | && (argv[1] == ATOM_CUR || argv[1] == ATOM_BOF || argv[1] == ATOM_EOF)) 538 | { 539 | RW_LOCK; 540 | 541 | if (argv[1] == ATOM_BOF) { 542 | position = 0L + relpos; 543 | } else if (argv[1] == ATOM_CUR) { 544 | position = handle->position + relpos; 545 | } else if (argv[1] == ATOM_EOF) { 546 | position = handle->len - relpos; 547 | } 548 | 549 | if (position < 0L || ((unsigned long)position) > handle->len) { 550 | RW_UNLOCK; 551 | return enif_make_badarg(env); 552 | } 553 | 554 | handle->position = position; 555 | RW_UNLOCK; 556 | 557 | return enif_make_tuple2(env, ATOM_OK, enif_make_ulong(env, position)); 558 | } 559 | else 560 | { 561 | return enif_make_badarg(env); 562 | } 563 | } 564 | -------------------------------------------------------------------------------- /c_src/erl_nif_compat.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2010-2011 Basho Technologies, Inc. 2 | * 3 | * This file is provided to you under the Apache License, 4 | * Version 2.0 (the "License"); you may not use this file 5 | * except in compliance with the License. You may obtain 6 | * a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, 11 | * software distributed under the License is distributed on an 12 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | * KIND, either express or implied. See the License for the 14 | * specific language governing permissions and limitations 15 | * under the License. 16 | */ 17 | 18 | #ifndef ERL_NIF_COMPAT_H_ 19 | #define ERL_NIF_COMPAT_H_ 20 | 21 | #ifdef __cplusplus 22 | extern "C" { 23 | #endif /* __cplusplus */ 24 | 25 | #include "erl_nif.h" 26 | 27 | #if ERL_NIF_MAJOR_VERSION == 1 && ERL_NIF_MINOR_VERSION == 0 28 | 29 | #define enif_open_resource_type_compat enif_open_resource_type 30 | #define enif_alloc_resource_compat enif_alloc_resource 31 | #define enif_release_resource_compat enif_release_resource 32 | #define enif_alloc_binary_compat enif_alloc_binary 33 | #define enif_alloc_compat enif_alloc 34 | #define enif_free_compat enif_free 35 | #define enif_cond_create erl_drv_cond_create 36 | #define enif_cond_destroy erl_drv_cond_destroy 37 | #define enif_cond_signal erl_drv_cond_signal 38 | #define enif_cond_broadcast erl_drv_cond_broadcast 39 | #define enif_cond_wait erl_drv_cond_wait 40 | #define ErlNifCond ErlDrvCond 41 | #endif /* R13B04 */ 42 | 43 | #if ERL_NIF_MAJOR_VERSION == 2 && ERL_NIF_MINOR_VERSION >= 0 44 | 45 | #define enif_open_resource_type_compat(E, N, D, F, T) \ 46 | enif_open_resource_type(E, NULL, N, D, F, T) 47 | 48 | #define enif_alloc_resource_compat(E, T, S) \ 49 | enif_alloc_resource(T, S) 50 | 51 | #define enif_release_resource_compat(E, H) \ 52 | enif_release_resource(H) 53 | 54 | #define enif_alloc_binary_compat(E, S, B) \ 55 | enif_alloc_binary(S, B) 56 | 57 | #define enif_alloc_compat(E, S) \ 58 | enif_alloc(S) 59 | 60 | #define enif_free_compat(E, P) \ 61 | enif_free(P) 62 | 63 | #endif /* R14 */ 64 | 65 | 66 | 67 | #ifdef __cplusplus 68 | } 69 | #endif /* __cplusplus */ 70 | 71 | #endif /* ERL_NIF_COMPAT_H_ */ 72 | -------------------------------------------------------------------------------- /doc/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | #mmap - memory mapping files for erlang# 4 | 5 | 6 | Copyright (c) 2012 Trifork 7 | 8 | 9 | __Authors:__ Kresten Krab Thorup ([`krab@trifork.com`](mailto:krab@trifork.com)). 10 | 11 | 12 | Status: 13 | ------ 14 | 15 | 16 | 17 | ##Modules## 18 | 19 | 20 | 21 |
emmap
22 | 23 | -------------------------------------------------------------------------------- /doc/emmap.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | #Module emmap# 4 | * [Data Types](#types) 5 | * [Function Index](#index) 6 | * [Function Details](#functions) 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | ##Data Types## 15 | 16 | 17 | 18 | 19 | ###mmap_file()## 20 | 21 | 22 | 23 |
mmap_file() = #file_descriptor{}
24 | 25 | 26 | 27 | ###open_option()## 28 | 29 | 30 | 31 |
open_option() = read | write | direct | lock | nolock | private | shared | nocache
32 | 33 | 34 | ##Function Index## 35 | 36 | 37 |
close/1
open/2
open/4
position/2
pread/3
pwrite/3
read/2
simple_test/0
38 | 39 | 40 | 41 | 42 | ##Function Details## 43 | 44 | 45 | 46 | ###close/1## 47 | 48 | 49 | 50 | 51 |
close(File::mmap_file()) -> ok
52 |

53 | 54 | 55 | 56 | 57 | ###open/2## 58 | 59 | 60 | 61 | 62 | `open(FileName, Options) -> any()` 63 | 64 | 65 | 66 | ###open/4## 67 | 68 | 69 | 70 | 71 |
open(File::string(), Offset::pos_integer(), Length::pos_integer(), Options::[open_option()]) -> {ok, mmap_file()} | {error, term()}
72 |

73 | 74 | 75 | 76 | 77 | ###position/2## 78 | 79 | 80 | 81 | 82 |
position(File::mmap_file(), Position::pos_integer() | {bof | cur | eof, Position::integer()}) -> {ok, pos_integer()} | {error, term()}
83 |

84 | 85 | 86 | 87 | 88 | ###pread/3## 89 | 90 | 91 | 92 | 93 |
pread(File::mmap_file(), Offset::pos_integer(), Length::pos_integer()) -> {ok, binary()} | {error, term()} | eof
94 |

95 | 96 | 97 | 98 | 99 | ###pwrite/3## 100 | 101 | 102 | 103 | 104 |
pwrite(File::mmap_file(), Position::pos_integer(), Data::binary()) -> ok | {error, term()}
105 |

106 | 107 | 108 | 109 | 110 | ###read/2## 111 | 112 | 113 | 114 | 115 |
read(File::mmap_file(), Length::pos_integer()) -> {ok, binary()} | {error, term()} | eof
116 |

117 | 118 | 119 | 120 | 121 | ###simple_test/0## 122 | 123 | 124 | 125 | 126 | `simple_test() -> any()` 127 | 128 | -------------------------------------------------------------------------------- /doc/overview.edoc: -------------------------------------------------------------------------------- 1 | @author Kresten Krab Thorup 2 | @copyright 2012 Trifork 3 | 4 | @title mmap - memory mapping files for erlang 5 | 6 | @doc 7 | Status: 8 | ------ 9 | 10 | 11 | @end 12 | -------------------------------------------------------------------------------- /ebin/emmap.app: -------------------------------------------------------------------------------- 1 | {application, emmap, 2 | [ 3 | {description, ""}, 4 | {vsn, "1.0.0"}, 5 | {modules, [ 6 | emmap 7 | ]}, 8 | {registered, []}, 9 | {applications, [ 10 | kernel, 11 | stdlib 12 | ]}, 13 | {env, []} 14 | ]}. 15 | -------------------------------------------------------------------------------- /rebar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/krestenkrab/emmap/05ae1bbc8b9b584473483023643fdc3f329a7698/rebar -------------------------------------------------------------------------------- /rebar.config: -------------------------------------------------------------------------------- 1 | {port_specs, [{"priv/emmap_nifs.so", ["c_src/*.cpp"]}]}. 2 | 3 | {port_env, [ 4 | %% Make sure to link -lstdc++ 5 | {"(linux|solaris|freebsd|netbsd|openbsd|dragonfly|darwin)", 6 | "LDFLAGS", "$LDFLAGS -lstdc++"}, 7 | {"(linux|solaris|freebsd|netbsd|openbsd|dragonfly|darwin)", 8 | "CFLAGS", "$CFLAGS -DNDEBUG"} 9 | ]}. 10 | 11 | {deps, [{edown, ".*", {git, "https://github.com/uwiger/edown.git", "HEAD"}}]}. 12 | 13 | {edoc_opts, [{doclet, edown_doclet}, 14 | {source_path, ["src", "test"]}, 15 | {stylesheet, ""}, 16 | {image, ""}, 17 | {app_default,"http://www.erlang.org/doc/man"}]}. 18 | -------------------------------------------------------------------------------- /src/emmap.erl: -------------------------------------------------------------------------------- 1 | -module(emmap). 2 | 3 | -export([open/2, open/4, close/1, pread/3, pwrite/3, read/2, read_line/1, position/2]). 4 | -on_load(init/0). 5 | 6 | -ifdef(TEST). 7 | -export([simple_test/0]). 8 | -endif. 9 | 10 | -include_lib("kernel/include/file.hrl"). 11 | 12 | -type open_option() :: 13 | read | write 14 | | direct 15 | | lock | nolock 16 | | private | shared 17 | | nocache 18 | . 19 | 20 | -type mmap_file() :: #file_descriptor{}. 21 | 22 | init() -> 23 | case code:priv_dir(emmap) of 24 | {error, bad_name} -> 25 | case code:which(?MODULE) of 26 | Filename when is_list(Filename) -> 27 | SoName = filename:join([filename:dirname(Filename),"../priv", "emmap_nifs"]); 28 | _ -> 29 | SoName = filename:join("../priv", "emmap_nifs") 30 | end; 31 | Dir -> 32 | SoName = filename:join(Dir, "emmap_nifs") 33 | end, 34 | erlang:load_nif(SoName, 0). 35 | 36 | 37 | open(FileName, Options) -> 38 | case file:read_file_info(FileName) of 39 | {ok, FileInfo} -> 40 | open(FileName, 0, FileInfo#file_info.size, Options); 41 | Error -> 42 | Error 43 | end. 44 | 45 | -spec open(File::string(), 46 | Offset::pos_integer(), 47 | Length::pos_integer(), 48 | Options::[ open_option() ]) -> 49 | {ok, mmap_file()} | {error, term()}. 50 | 51 | open(FileName, Off, Len, Options) -> 52 | case open_nif(FileName, Off, Len, Options) of 53 | {ok, Mem} -> 54 | {ok, #file_descriptor{ module=?MODULE, data=Mem }}; 55 | Error -> 56 | Error 57 | end. 58 | 59 | open_nif(_,_,_,_) -> 60 | {ok, <<>>}. 61 | 62 | -spec close(File::mmap_file()) -> ok. 63 | 64 | close(#file_descriptor{ module=?MODULE, data=Mem }) -> 65 | close_nif(Mem). 66 | 67 | close_nif(_) -> 68 | ok. 69 | 70 | -spec pread(File::mmap_file(), Offset::pos_integer(), Length::pos_integer()) -> 71 | {ok, binary()} | {error, term()} | eof. 72 | 73 | pread(#file_descriptor{ module=?MODULE, data=Mem }, Off, Len) -> 74 | pread_nif(Mem, Off, Len). 75 | 76 | pread_nif(_,_,_) -> 77 | {ok, <<>>}. 78 | 79 | -spec read(File::mmap_file(), Length::pos_integer()) -> 80 | {ok, binary()} | {error, term()} | eof. 81 | 82 | read(#file_descriptor{ module=?MODULE, data=Mem }, Len) -> 83 | read_nif(Mem, Len). 84 | 85 | read_nif(_,_) -> 86 | {ok, <<>>}. 87 | 88 | 89 | -spec read_line(File::mmap_file()) -> 90 | {ok, binary()} | {error, term()} | eof. 91 | 92 | read_line(#file_descriptor{ module=?MODULE, data=Mem }) -> 93 | read_line_nif(Mem). 94 | 95 | read_line_nif(_) -> 96 | {ok, <<>>}. 97 | 98 | 99 | -spec pwrite(File::mmap_file(), Position::pos_integer(), Data::binary()) -> 100 | ok | {error, term()}. 101 | 102 | pwrite(#file_descriptor{ module=?MODULE, data=Mem }, Off, Data) -> 103 | pwrite_nif(Mem, Off, Data). 104 | 105 | pwrite_nif(_,_,_) -> 106 | ok. 107 | 108 | -spec position(File::mmap_file(), 109 | Position::pos_integer() | {bof|cur|eof, Position::integer()} ) -> 110 | {ok, pos_integer()} | {error, term()}. 111 | position(#file_descriptor{ module=?MODULE, data=Mem}, At) 112 | when is_integer(At) -> 113 | position_nif(Mem, bof, At); 114 | position(#file_descriptor{ module=?MODULE, data=Mem}, From) 115 | when From == 'bof'; From == 'cur'; From == 'eof' -> 116 | position_nif(Mem, From, 0); 117 | position(#file_descriptor{ module=?MODULE, data=Mem}, {From, Off}) 118 | when From == 'bof'; From == 'cur'; From == 'eof' -> 119 | position_nif(Mem, From, Off). 120 | 121 | position_nif(_,_From,_Off) -> 122 | {ok, 0}. 123 | 124 | 125 | -ifdef(TEST). 126 | 127 | simple_test() -> 128 | {ok, File} = file:open("test.data", [raw, write]), 129 | ok = file:write(File, <<"abcd">>), 130 | ok = file:close(File), 131 | 132 | %% with direct+shared, the contents of a binary may change 133 | {ok, MFile} = emmap:open("test.data", 0, 4, [direct, shared, nolock]), 134 | {ok, Mem} = file:pread(MFile, 2, 2), 135 | <<"cd">> = Mem, 136 | {error, eacces} = file:pwrite(MFile, 2, <<"xx">>), 137 | 138 | {ok, MFile2} = emmap:open("test.data", 0, 4, [read, write, shared]), 139 | ok = file:pwrite(MFile2, 2, <<"xx">>), 140 | {ok, <<"xx">>} = file:pread(MFile, 2, 2), 141 | 142 | %% Woot! 143 | <<"xx">> = Mem, 144 | 145 | {ok, 0} = file:position(MFile, {cur, 0}), 146 | {ok, <<"ab">>} = file:read(MFile, 2), 147 | {ok, <<"xx">>} = file:read(MFile, 2), 148 | 149 | file:close(MFile), 150 | file:close(MFile2) . 151 | 152 | 153 | -endif. 154 | --------------------------------------------------------------------------------