Sys-Mmap-0.21/000755 000765 000024 00000000000 15160060211 014616 5ustar00todd.rinaldostaff000000 000000 Sys-Mmap-0.21/Changes000644 000765 000024 00000010263 15160060051 016115 0ustar00todd.rinaldostaff000000 000000 Todd Rinaldo, Mar 22 2026 v0.21 Bug Fixes: * Fix segfault with non-zero offset in mmap. When mmap() was called with a non-zero offset, Perl's sv_clear would try to Safefree() the mmap'd pointer on scope exit, causing a crash. Now uses Perl's magic system to store unmap metadata safely. GH #1, PR #12 * Fix len=0 with offset inferring wrong mapped size. When mmap() was called with len=0 and a non-zero offset, the length was inferred as the full file size rather than file_size - offset, causing the mapping to extend past the end of the file. PR #14 * Resolve tied interface DESTROY munmap failures. DESTROY receives a blessed reference, not the mmap'd SV itself. Without dereferencing, the magic lookup failed and tried to munmap a garbage pointer. PR #16 Improvements: * Document len=0 with offset behavior and caveats in POD. Clarify that len=0 with offset infers remaining file size, document the offset-beyond-EOF error, and add caveat about page alignment. PR #15 Maintenance: * Modernize CI: consolidate separate linux.yml and macos.yml into a unified testsuite.yml with updated actions and containers. PR #13 Todd Rinaldo, Feb 13 2020 v0.20 * Add use warnings to improve kwalitee * Spelling error in manpage * Add MAP_POPULATE support, which has been available since Linux Kernel 2.5 Scott Walters, Mar 1 2017 v0.19 * Update the FSF's mailing address in their license; thanks to knnniggett This also gets the CPAN and github versions in sync Scott Walters, Mar 1 2017 v0.18 * MAP_HUGETLB MAP_HUGE_2MB MAP_HUGE_1GB, MAP_NORESERVE thanks to CowboyTim Todd Rinaldo August 22 2014 v0.17_01 * Track fixes in github now all issues are cleared from RT https://github.com/toddr/Sys-Mmap/issues * Turn off homepage in META since there really isn't one. * Minor fix to COW patch related to XS spacing. Scott Walters, August 21 2014, v0.17_01 * RT 91483 - croak("variable is not a string") was hitting because it was being too selective with SV type for modern perls. * RT 96043 - Updates to fix perl 5.20 COW issues * RT 96043 - Add MAP_LOCKED flag * Update contributors docs. Todd Rinaldo August 19 2011 v0.16 * Testing looks stable on all major perl versions and distros. * Release with only version bump Todd Rinaldo August 18 2011 v0.15_02 * Pause blocked. Todd Rinaldo August 18 2011 v0.15_01 * Patch from RT 70333 (Syohei YOSHIDA) to make error testing locale neutral * Add test for GLOB mmap * Make temp file larger for testing additional cases. Todd Rinaldo April 4 2011 v0.15 * cpantesters looks good besides Win32. Waiting for someone from windows world to care/submit patch Todd Rinaldo March 29 2011 v0.14_01 * Mmap could not handle files larger than 2GB if perl was not using 64bit int. Resolved the problem by taking a string and converting it via atoll, depending on _FILE_OFFSET_BITS > 32 * Added test and fix to croak if a negative offset is passed in. * initialize global variable pagesize = 0 so it'll set right the first time * Remove typemap which was only used by mmap sub. Now we're using SV, it's no longer an issue. Todd Rinaldo Sept 7 2010 v0.14 * Tests look stable. Releasing prod version of module. Todd Rinaldo Sept 1 2010 v0.13_03 * Skip unmapping of invalid variables on BSD kernels which seem to segfault on this event. Todd Rinaldo July 29 2010 v0.13_02 * Do a little better undef detection in the SV before trying to blindly unmap it. * Add tests to detect these cases Todd Rinaldo July 27 2010 v0.13_01 * RT 59754 AUTOLOAD does quoted eval. * RT 59753 Mmap.xs:14:0: warning: "_POSIX_C_SOURCE" redefined * RT 15905 bug/segmentation fault on ia64 (altix) * RT 22615 munmap($unseen) segfaults * RT 59750 Update Makefile.PL to show Module dependencies. * RT 59749 use Test::More and test interface more thoroughly. * RT 59748 use XSLoader if possible for more lightweight load * RT 59747 Don't import Carp into module by default * update META.yml Aaron Kaplan, Sep 2003, v 0.12 . cleaned up style and usage in C to fit ANSI-C . contributed documentation Scott Walters, Feb 2002, v 0.11 . tied interface to help reduce foot shooting and hoop jumping . hardwire() utility method . perl 5.6.x compatability Malcolm Beattie, 21 June 1996, v 0.10 Original author, original version . Sys-Mmap-0.21/MANIFEST000644 000765 000024 00000000503 15160060211 015745 0ustar00todd.rinaldostaff000000 000000 Artistic Changes Copying Makefile.PL MANIFEST MANIFEST.SKIP Mmap.pm Mmap.xs README t/comprehensive.t t/mmap.t t/munmap_errors.t t/offset.t xt/author/pod.t META.yml Module YAML meta-data (added by MakeMaker) META.json Module JSON meta-data (added by MakeMaker) Sys-Mmap-0.21/t/000755 000765 000024 00000000000 15160060211 015061 5ustar00todd.rinaldostaff000000 000000 Sys-Mmap-0.21/xt/000755 000765 000024 00000000000 15160060211 015251 5ustar00todd.rinaldostaff000000 000000 Sys-Mmap-0.21/README000644 000765 000024 00000006447 15157401011 015514 0ustar00todd.rinaldostaff000000 000000 Mmap perl module, version alpha2 Copyright (c) 1996, Malcolm Beattie Copyright (c) 2002, Scott Walters This program is free software; you can redistribute it and/or modify it under the terms of either: a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" which comes with this kit. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either the GNU General Public License or the Artistic License for more details. You should have received a copy of the Artistic License with this kit, in the file named "Artistic". If not, you can get one from the Perl distribution. You should also have received a copy of the GNU General Public License, in the file named "Copying". If not, you can get one from the Perl distribution or else write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. DESCRIPTION The Mmap module lets you use mmap to map in a file as a perl variable rather than reading the file into dynamically allocated memory. Multiple programs may map the same file into memory, and immediately see changes by each other. Memory may be allocated not attached to a file, and shared with subprocesses. It depends on your operating system supporting UNIX or POSIX.1b mmap, of course. You may use the new OO interface, or the old map() and unmap() interface. If you use the old interface, you need to be careful. Some programming constructs may create copies of a string which, while unimportant for smallish strings, are far less welcome if you're mapping in a file which is a few gigabytes big. If you use PROT_WRITE and attempt to write to the file via the variable you need to be even more careful. One of the few ways in which you can safely write to the string in-place is by using substr as an lvalue and ensuring that the part of the string that you replace is exactly the same length. The new interface does not suffer from these problems. INSTALLATION Prerequisites are perl 5.002 and an operating system that has an implementation of mmap(2) with either the traditional or the POSIX.1b API. Perl 5.7.2 was tested with this release. Type perl Makefile.PL to write a personalised Makefile for your system. If your platform supports dynamic loading then just type make make test and provided you see "All tests successful" you can install it with make install If you need/want instead to make a statically linked perl which contains the module, then type make perl make test Documentation is included in pod format in Mmap.pm itself. The "make install" step will install an Mmap(3) man page or else you can use perldoc Mmap which will find the documentation whether it has been installed or if you run it from the Mmap distribution directory. BUGS You must explicitly use munmap() rather than letting perl itself clean up after you since perl 5.002 can't cope with variables whose string contents live in non-malloc'd memory. Malcolm Beattie 21 Jun 1996 Documentation updated to include information on OO interface 6/2002 Scott Walters Sys-Mmap-0.21/Copying000644 000765 000024 00000030525 15157401011 016161 0ustar00todd.rinaldostaff000000 000000 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! Sys-Mmap-0.21/MANIFEST.SKIP000644 000765 000024 00000000054 15160060162 016520 0ustar00todd.rinaldostaff000000 000000 ^.git ^MYMETA\.* ^MANIFEST\.bak$ ^Makefile$ Sys-Mmap-0.21/Mmap.xs000644 000765 000024 00000023526 15160057053 016106 0ustar00todd.rinaldostaff000000 000000 #ifdef __cplusplus extern "C" { #endif #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include #ifdef __cplusplus } #endif #include #include #ifndef MMAP_RETTYPE #ifndef _POSIX_C_SOURCE #define _POSIX_C_SOURCE 199309 #endif #ifdef _POSIX_VERSION #if _POSIX_VERSION >= 199309 #define MMAP_RETTYPE void * #endif #endif #endif #ifndef MMAP_RETTYPE #define MMAP_RETTYPE caddr_t #endif #ifndef MAP_FAILED #define MAP_FAILED ((caddr_t)-1) #endif static int not_here(s) char *s; { croak("%s not implemented on this architecture", s); return -1; } static double constant(name, arg) char *name; int arg; { errno = 0; switch (*name) { case 'M': if (strEQ(name, "MAP_ANON")) #ifdef MAP_ANON return MAP_ANON; #else goto not_there; #endif if (strEQ(name, "MAP_ANONYMOUS")) #ifdef MAP_ANONYMOUS return MAP_ANONYMOUS; #else goto not_there; #endif if (strEQ(name, "MAP_FILE")) #ifdef MAP_FILE return MAP_FILE; #else goto not_there; #endif if (strEQ(name, "MAP_PRIVATE")) #ifdef MAP_PRIVATE return MAP_PRIVATE; #else goto not_there; #endif if (strEQ(name, "MAP_SHARED")) #ifdef MAP_SHARED return MAP_SHARED; #else goto not_there; #endif if (strEQ(name, "MAP_LOCKED")) #ifdef MAP_LOCKED return MAP_LOCKED; #else goto not_there; #endif if (strEQ(name, "MAP_NORESERVE")) #ifdef MAP_NORESERVE return MAP_NORESERVE; #else goto not_there; #endif if (strEQ(name, "MAP_POPULATE")) #ifdef MAP_POPULATE return MAP_POPULATE; #else goto not_there; #endif if (strEQ(name, "MAP_HUGETLB")) #ifdef MAP_HUGETLB return MAP_HUGETLB; #else goto not_there; #endif if (strEQ(name, "MAP_HUGE_2MB")) #ifdef MAP_HUGE_2MB return MAP_HUGE_2MB; #else goto not_there; #endif if (strEQ(name, "MAP_HUGE_1GB")) #ifdef MAP_HUGE_1GB return MAP_HUGE_1GB; #else goto not_there; #endif break; case 'P': if (strEQ(name, "PROT_EXEC")) #ifdef PROT_EXEC return PROT_EXEC; #else goto not_there; #endif if (strEQ(name, "PROT_NONE")) #ifdef PROT_NONE return PROT_NONE; #else goto not_there; #endif if (strEQ(name, "PROT_READ")) #ifdef PROT_READ return PROT_READ; #else goto not_there; #endif if (strEQ(name, "PROT_WRITE")) #ifdef PROT_WRITE return PROT_WRITE; #else goto not_there; #endif break; default: break; } errno = EINVAL; return 0; not_there: errno = ENOENT; return 0; } static size_t pagesize = 0; /* Magic structure to track mmap info for proper cleanup */ typedef struct { void *base_addr; /* actual address returned by mmap() */ size_t total_len; /* actual length passed to mmap() (len + slop) */ } mmap_info_t; #define MMAP_MAGIC_TYPE PERL_MAGIC_ext static int mmap_magic_free(pTHX_ SV *sv, MAGIC *mg) { mmap_info_t *info = (mmap_info_t *) mg->mg_ptr; if (info) { if (info->base_addr) { munmap((MMAP_RETTYPE) info->base_addr, info->total_len); info->base_addr = NULL; } Safefree(info); mg->mg_ptr = NULL; } return 0; } static MGVTBL mmap_magic_vtbl = { 0, /* get */ 0, /* set */ 0, /* len */ 0, /* clear */ mmap_magic_free, /* free */ 0, /* copy */ 0, /* dup */ 0 /* local */ }; /* Find our mmap magic on an SV, or NULL if not present */ static MAGIC *find_mmap_magic(SV *sv) { MAGIC *mg; if (SvTYPE(sv) >= SVt_PVMG) { for (mg = SvMAGIC(sv); mg; mg = mg->mg_moremagic) { if (mg->mg_type == MMAP_MAGIC_TYPE && mg->mg_virtual == &mmap_magic_vtbl) return mg; } } return NULL; } #if _FILE_OFFSET_BITS > 32 #define get_off(a) (atoll(a)) #else #define get_off(a) (atoi(a)) #endif MODULE = Sys::Mmap PACKAGE = Sys::Mmap double constant(name,arg) char * name int arg SV * hardwire(var, addr, len) SV * var IV addr size_t len PROTOTYPE: $$$ CODE: ST(0) = &PL_sv_undef; SvUPGRADE(var, SVt_PV); SvPVX(var) = (char *) addr; SvCUR_set(var, len); SvLEN_set(var, 0); SvPOK_only(var); /*printf("ok, that var is now stuck at addr %lx\n", addr);*/ ST(0) = &PL_sv_yes; SV * mmap(var, len, prot, flags, fh = 0, off_string) SV * var size_t len int prot int flags FILE * fh SV * off_string int fd = NO_INIT MMAP_RETTYPE addr = NO_INIT off_t slop = NO_INIT off_t off = NO_INIT PROTOTYPE: $$$$*;$ CODE: if(!SvTRUE(off_string)) { off = 0; } else { off = get_off(SvPVbyte_nolen(off_string)); } if(off < 0) { croak("mmap: Cannot operate on a negative offset (%s) ", SvPVbyte_nolen(off_string)); } ST(0) = &PL_sv_undef; if(flags&MAP_ANON) { fd = -1; if (!len) { /* i WANT to return undef and set $! but perlxs and perlxstut dont tell me how... waa! */ croak("mmap: MAP_ANON specified, but no length specified. cannot infer length from file"); } } else { fd = fileno(fh); if (fd < 0) { croak("mmap: file not open or does not have associated fileno"); } if (!len) { struct stat st; if (fstat(fd, &st) == -1) { croak("mmap: no len provided, fstat failed, unable to infer length"); } if (off >= st.st_size) { croak("mmap: offset (%"IVdf") is at or beyond end of file (size %"IVdf")", (IV)off, (IV)st.st_size); } len = st.st_size - off; } } if (pagesize == 0) { pagesize = getpagesize(); } slop = (size_t) off % pagesize; addr = mmap(0, len + slop, prot, flags, fd, off - slop); if (addr == MAP_FAILED) { croak("mmap: mmap call failed: errno: %d errmsg: %s ", errno, strerror(errno)); } #if PERL_VERSION >= 20 if (SvIsCOW(var)) { sv_force_normal_flags(var, 0); } #endif SvUPGRADE(var, SVt_PV); if (!(prot & PROT_WRITE)) SvREADONLY_on(var); /* would sv_usepvn() be cleaner/better/different? would still try to realloc... */ SvPVX(var) = (char *) addr + slop; SvCUR_set(var, len); SvLEN_set(var, 0); /* must be 0 so Perl won't Safefree() the mmap'd pointer */ SvPOK_only(var); /* Attach magic to handle munmap on cleanup */ { mmap_info_t *info; MAGIC *mg; Newxz(info, 1, mmap_info_t); info->base_addr = (void *) addr; info->total_len = len + slop; mg = sv_magicext(var, NULL, MMAP_MAGIC_TYPE, &mmap_magic_vtbl, (const char *) info, 0); mg->mg_flags |= MGf_LOCAL; } ST(0) = sv_2mortal(newSVnv((IV) addr)); SV * munmap(var) SV * var PROTOTYPE: $ CODE: ST(0) = &PL_sv_undef; /* XXX refrain from dumping core if this var wasnt previously mmap'd */ if(!SvOK(var)) { /* Detect if variable is undef */ croak("undef variable not unmappable"); return; } if(SvTYPE(var) < SVt_PV || SvTYPE(var) > SVt_PVMG) { croak("variable is not a string, type is: %d", SvTYPE(var)); return; } { MAGIC *mg = find_mmap_magic(var); if (mg) { mmap_info_t *info = (mmap_info_t *) mg->mg_ptr; if (munmap((MMAP_RETTYPE) info->base_addr, info->total_len) == -1) { croak("munmap failed! errno %d %s\n", errno, strerror(errno)); return; } info->base_addr = NULL; /* prevent double munmap in magic free */ } else { /* fallback for hardwire'd or legacy variables without magic */ /* SvLEN > 0 means this is a regular Perl string, not mmap'd */ if (SvLEN(var) != 0) { errno = EINVAL; croak("munmap failed! errno %d %s\n", errno, strerror(errno)); return; } if (munmap((MMAP_RETTYPE) SvPVX(var), SvCUR(var)) == -1) { croak("munmap failed! errno %d %s\n", errno, strerror(errno)); return; } } } SvREADONLY_off(var); SvPVX(var) = 0; SvCUR_set(var, 0); SvLEN_set(var, 0); SvOK_off(var); ST(0) = &PL_sv_yes; void DESTROY(var) SV * var PROTOTYPE: $ CODE: /* XXX refrain from dumping core if this var wasnt previously mmap'd*/ /* For tied objects: DESTROY receives the blessed reference (\$mmap_sv), * not the mmap'd SV itself. Dereference to reach the actual mapping. */ if (SvROK(var)) var = SvRV(var); { MAGIC *mg = find_mmap_magic(var); if (mg) { mmap_info_t *info = (mmap_info_t *) mg->mg_ptr; if (info->base_addr) { if (munmap((MMAP_RETTYPE) info->base_addr, info->total_len) == -1) { croak("munmap failed! errno %d %s\n", errno, strerror(errno)); return; } info->base_addr = NULL; } } else { /* SvLEN > 0 means this is a regular Perl string, not mmap'd */ if (SvLEN(var) != 0) return; if (munmap((MMAP_RETTYPE) SvPVX(var), SvCUR(var)) == -1) { croak("munmap failed! errno %d %s\n", errno, strerror(errno)); return; } } } SvREADONLY_off(var); SvPVX(var) = 0; SvCUR_set(var, 0); SvLEN_set(var, 0); SvOK_off(var); /* printf("destroy ran fine, thanks\n"); */ ST(0) = &PL_sv_yes; Sys-Mmap-0.21/META.yml000644 000765 000024 00000001441 15160060211 016067 0ustar00todd.rinaldostaff000000 000000 --- abstract: 'uses mmap to map in a file as a Perl variable' author: - 'Scott Walters ' build_requires: Errno: '0' ExtUtils::MakeMaker: '0' Test::More: '0' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 1 generated_by: 'ExtUtils::MakeMaker version 7.76, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Sys-Mmap no_index: directory: - t - inc requires: DynaLoader: '0' Test::More: '0' XSLoader: '0' resources: bugtracker: https://github.com/toddr/Sys-Mmap/issues license: http://dev.perl.org/licenses/ repository: http://github.com/toddr/Sys-Mmap/tree/master version: '0.21' x_serialization_backend: 'CPAN::Meta::YAML version 0.020' Sys-Mmap-0.21/Makefile.PL000644 000765 000024 00000002207 15157401011 016574 0ustar00todd.rinaldostaff000000 000000 use strict; use warnings; use ExtUtils::MakeMaker; WriteMakefile( NAME => 'Sys::Mmap', AUTHOR => 'Scott Walters ', VERSION_FROM => 'Mmap.pm', ABSTRACT_FROM => 'Mmap.pm', PL_FILES => {}, ($ExtUtils::MakeMaker::VERSION >= 6.3002 ? ('LICENSE' => 'perl', ) : ()), PREREQ_PM => { ($] >= 5.006 ? ('XSLoader' => 0) : ()), 'DynaLoader' => 0, 'Test::More' => 0, }, dist => { COMPRESS => 'gzip -9f', SUFFIX => 'gz', }, clean => { FILES => 'Sys-Mmap-*' }, META_MERGE => { build_requires => { 'Test::More' => 0, # For testing 'Errno' => 0, # Locale independant failure validation. }, resources => { license => 'http://dev.perl.org/licenses/', # homepage => 'http://wiki.github.com/toddr/Sys-Mmap', bugtracker => 'https://github.com/toddr/Sys-Mmap/issues', repository => 'http://github.com/toddr/Sys-Mmap/tree/master', # MailingList => 'http://groups.google.com/group/Sys-Mmap', }, }, ); Sys-Mmap-0.21/Mmap.pm000644 000765 000024 00000025715 15160060057 016070 0ustar00todd.rinaldostaff000000 000000 package Sys::Mmap; =head1 NAME Sys::Mmap - uses mmap to map in a file as a Perl variable =head1 SYNOPSIS use Sys::Mmap; Sys::Mmap->new( my $str, 8192, 'structtest2.pl' ) or die $!; Sys::Mmap->new( $var, 8192 ) or die $!; mmap( $foo, 0, PROT_READ, MAP_SHARED, FILEHANDLE ) or die "mmap: $!"; @tags = $foo =~ /<(.*?)>/g; munmap($foo) or die "munmap: $!"; mmap( $bar, 8192, PROT_READ | PROT_WRITE, MAP_SHARED, FILEHANDLE ); substr( $bar, 1024, 11 ) = "Hello world"; mmap( $baz, 8192, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, STDOUT ); $addr = mmap( $baz, 8192, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, STDOUT ); Sys::Mmap::hardwire( $qux, $addr, 8192 ); =head1 DESCRIPTION The Sys::Mmap module uses the POSIX L call to map in a file as a Perl variable. Memory access by mmap may be shared between threads or forked processes, and may be a disc file that has been mapped into memory. L depends on your operating system supporting UNIX or POSIX.1b mmap, of course. B that L now defines a C<:mmap> tag and presents mmap'd files as regular files, if that is your cup of joe. Several processes may share one copy of the file or string, saving memory, and concurrently making changes to portions of the file or string. When not used with a file, it is an alternative to SysV shared memory. Unlike SysV shared memory, there are no arbitrary size limits on the shared memory area, and sparse memory usage is handled optimally on most modern UNIX implementations. Using the C method provides a C'd interface to C that allows you to use the variable as a normal variable. If a filename is provided, the file is opened and mapped in. If the file is smaller than the length provided, the file is grown to that length. If no filename is provided, anonymous shared inheritable memory is used. Assigning to the variable will replace a section in the file corresponding to the length of the variable, leaving the remainder of the file intact and unmodified. Using C allows you to access the file at an offset, and does not place any requirements on the length argument to C or the length of the variable being inserted, provided it does not exceed the length of the memory region. This protects you from the pathological cases involved in using C directly, documented below. When calling C or C directly, you need to be careful how you use the variable. Some programming constructs may create copies of a string which, while unimportant for smallish strings, are far less welcome if you're mapping in a file which is a few gigabytes big. If you use C and attempt to write to the file via the variable you need to be even more careful. One of the few ways in which you can safely write to the string in-place is by using C as an lvalue and ensuring that the part of the string that you replace is exactly the same length. Other functions will allocate other storage for the variable, and it will no longer overlay the mapped in file. =over 4 =item Sys::Mmap->new( C, C, C ) Maps C bytes of (the contents of) C if C is provided, otherwise uses anonymous, shared inheritable memory. This memory region is inherited by any Ced children. C will now refer to the contents of that file. Any change to C will make an identical change to the file. If C is zero and a file is specified, the current length of the file will be used. (Note: the tied interface does not support C, so this always maps the full file.) If C is larger then the file, and C is provided, the file is grown to that length before being mapped. This is the preferred interface, as it requires much less caution in handling the variable. C will be tied into the "Sys::Mmap" package, and C will be called for you. Assigning to C will overwrite the beginning of the file for a length of the value being assigned in. The rest of the file or memory region after that point will be left intact. You may use C to assign at a given position: substr(VARIABLE, POSITION, LENGTH) = NEWVALUE =item mmap(VARIABLE, LENGTH, PROTECTION, FLAGS, FILEHANDLE, OFFSET) Maps C bytes of (the underlying contents of) C into your address space, starting at offset C and makes C refer to that memory. The C argument can be omitted in which case it defaults to zero. The C argument can be zero in which case a stat is done on C and the file size is used to infer the mapping length. If C is also specified, the inferred length is C (i.e. the remainder of the file from C onward). An exception is thrown if C is at or beyond the end of the file. B: the underlying C system call requires the offset to be a multiple of the system page size (typically 4096 bytes). Sys::Mmap handles non-page-aligned offsets internally by adjusting the mapping, but very large non-aligned offsets may map slightly more memory than the requested region. The C argument should be some ORed combination of the constants C, C and C, or else C. The constants C and C are unlikely to be useful here but are included for completeness. The C argument must include either C or C (the latter is unlikely to be useful here). If your platform supports it, you may also use C or C. If your platform supplies C as a non-zero constant (necessarily non-POSIX) then you should also include that in C. POSIX.1b does not specify C as a C argument and most if not all versions of Unix have C as zero. mmap returns C on failure, and the address in memory where the variable was mapped to on success. =item munmap(VARIABLE) Unmaps the part of your address space which was previously mapped in with a call to C and makes VARIABLE become undefined. munmap returns 1 on success and undef on failure. =item hardwire(VARIABLE, ADDRESS, LENGTH) Specifies the address in memory of a variable, possibly within a region you've Ced another variable to. You must use the same precautions to keep the variable from being reallocated, and use C with an exact length. If you C a region that a Ced variable lives in, the Ced variable will not automatically be Ced. You must do this manually. =item Constants The Sys::Mmap module exports the following constants into your namespace: MAP_SHARED MAP_PRIVATE MAP_ANON MAP_ANONYMOUS MAP_FILE MAP_NORESERVE MAP_POPULATE MAP_HUGETLB MAP_HUGE_2MB MAP_HUGE_1GB PROT_EXEC PROT_NONE PROT_READ PROT_WRITE Of the constants beginning with C, only C and C are defined in POSIX.1b and only C is likely to be useful. =back =head1 BUGS Scott Walters doesn't know XS, and is just winging it. There must be a better way to tell Perl not to reallocate a variable in memory... The C interface makes writing to a substring of the variable much less efficient. One user cited his application running 10-20 times slower when C<< Sys::Mmap->new() >> is used than when C is called directly. Malcolm Beattie has not reviewed Scott's work and is not responsible for any bugs, errors, omissions, stylistic failings, importabilities, or design flaws in this version of the code. There should be a tied interface to C as well. Scott Walter's spelling is awful. C will segfault Perl if the C area it was referring to is C'd out from under it. C will segfault Perl if the variable was not successfully C'd previously, or if it has since been reallocated by Perl. =head1 AUTHOR CowboyTim added support for MAP_NORESERVE, MAP_HUGETLB, MAP_HUGE_2MB, and MAP_HUGE_1GB. Thanks CowboyTim! Todd Rinaldo cleaned up code, modernized again, and merged in many fixes, 2010-2011. Scott Walters updated for Perl 5.6.x, additions, 2002. Malcolm Beattie, 21 June 1996. =cut use strict; use warnings; our $VERSION = '0.21'; our $AUTOLOAD; # For sub AUTOLOAD require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(mmap munmap MAP_ANON MAP_ANONYMOUS MAP_FILE MAP_LOCKED MAP_PRIVATE MAP_SHARED MAP_NORESERVE MAP_POPULATE MAP_HUGETLB MAP_HUGE_2MB MAP_HUGE_1GB PROT_EXEC PROT_NONE PROT_READ PROT_WRITE); sub new { if(scalar @_ < 3) { warn 'Usage: Sys::Mmap->new( $var, $desiredSize, $optFile );'; return undef; } my $type = $_[0]; my $leng = $_[2]; tie $_[1], $_[0], @_[2 .. scalar(@_)-1 ]; # tie $_[1], $type, $leng; } sub TIESCALAR { if(scalar @_ < 2) { # print "debug: got args: ", join ', ', @_, "\n"; warn 'Usage: tie $var, "Sys::Mmap", $desiredSize, $optionalFile;'; return undef; } my $me; my $fh; my $type = shift; my $leng = shift; my $file = shift; my $flags = constant('MAP_INHERIT',0)| constant('MAP_SHARED',0); if($file) { open $fh, '+>>', $file or do { warn "mmap: could not open file '$file' for append r/w"; return undef; }; # if we dont pad the file out to the specified length, we coredump my $fhsize = -s $fh; if($leng > $fhsize) { $fhsize = $leng - $fhsize; print $fh ("\000" x $fhsize) or die $!; # print $fh pack("a$fhsize", '') or die $!; # while($fhsize) { print $fh "\000"; $fhsize--; } } $flags |= constant('MAP_FILE',0); } else { $flags |= constant('MAP_ANON',0); } my $addr = mmap( $me, $leng, constant('PROT_READ',0)|constant('PROT_WRITE',0), $flags, $file ? $fh : *main::STDOUT ) or die $!; bless \$me, $type; # XXX return $addr somehow... } sub STORE { my $me = shift; my $newval = shift; substr($$me, 0, length($newval), $newval); $$me; } sub FETCH { my $me = shift; $$me; } sub AUTOLOAD { # This AUTOLOAD is used to 'autoload' constants from the constant() # XS function. If a constant is not found then control is passed # to the AUTOLOAD in AutoLoader. if ($AUTOLOAD =~ /::(_?[a-z])/) { $AutoLoader::AUTOLOAD = $AUTOLOAD; goto &AutoLoader::AUTOLOAD; } local $! = 0; my $constname = $AUTOLOAD; $constname =~ s/.*:://; return if $constname eq 'DESTROY'; my $val = constant($constname, @_ ? $_[0] : 0); if ($! == 0) { no strict 'refs'; *$AUTOLOAD = sub { $val }; } else { require Carp; Carp::croak("Your vendor has not defined Sys::Mmap macro $constname"); } goto &$AUTOLOAD; } eval { require XSLoader; XSLoader::load( 'Sys::Mmap', $VERSION ); } or do { require DynaLoader; push @ISA, 'DynaLoader'; bootstrap Sys::Mmap $VERSION; }; 1; __END__ Sys-Mmap-0.21/Artistic000644 000765 000024 00000013740 15157401011 016333 0ustar00todd.rinaldostaff000000 000000 The "Artistic License" Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder as specified below. "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package. "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as uunet.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) give non-standard executables non-standard names, and clearly document the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. You may embed this Package's interpreter within an executable of yours (by linking); this shall be construed as a mere form of aggregation, provided that the complete Standard Version of the interpreter is so embedded. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. If such scripts or library files are aggregated with this Package via the so-called "undump" or "unexec" methods of producing a binary executable image, then distribution of such an image shall neither be construed as a distribution of this Package nor shall it fall under the restrictions of Paragraphs 3 and 4, provided that you do not represent such an executable image as a Standard Version of this Package. 7. C subroutines (or comparably compiled subroutines in other languages) supplied by you and linked into this Package in order to emulate subroutines and variables of the language defined by this Package shall not be considered part of this Package, but are the equivalent of input as in Paragraph 6, provided these subroutines do not change the language in any way that would cause it to fail the regression tests for the language. 8. Aggregation of this Package with a commercial distribution is always permitted provided that the use of this Package is embedded; that is, when no overt attempt is made to make this Package's interfaces visible to the end user of the commercial distribution. Such use shall not be construed as a distribution of this Package. 9. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Sys-Mmap-0.21/META.json000644 000765 000024 00000002503 15160060211 016237 0ustar00todd.rinaldostaff000000 000000 { "abstract" : "uses mmap to map in a file as a Perl variable", "author" : [ "Scott Walters " ], "dynamic_config" : 1, "generated_by" : "ExtUtils::MakeMaker version 7.76, CPAN::Meta::Converter version 2.150010", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Sys-Mmap", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "Errno" : "0", "ExtUtils::MakeMaker" : "0", "Test::More" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "DynaLoader" : "0", "Test::More" : "0", "XSLoader" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/toddr/Sys-Mmap/issues" }, "license" : [ "http://dev.perl.org/licenses/" ], "repository" : { "url" : "http://github.com/toddr/Sys-Mmap/tree/master" } }, "version" : "0.21", "x_serialization_backend" : "JSON::PP version 4.16" } Sys-Mmap-0.21/xt/author/000755 000765 000024 00000000000 15160060211 016553 5ustar00todd.rinaldostaff000000 000000 Sys-Mmap-0.21/xt/author/pod.t000644 000765 000024 00000000306 15157401011 017524 0ustar00todd.rinaldostaff000000 000000 #!/usr/bin/env perl use strict; use warnings; use Test::More; eval 'use Test::Pod 1.00'; plan skip_all => 'Test::Pod 1.00 required for testing POD' if $@; pod_file_ok('Mmap.pm'); done_testing(); Sys-Mmap-0.21/t/munmap_errors.t000644 000765 000024 00000002122 15157401011 020137 0ustar00todd.rinaldostaff000000 000000 #!perl use strict; use warnings; use Test::More tests => 14; use Sys::Mmap; use Errno qw(EINVAL); { my $foo; eval {munmap($foo)}; like($@, qr/^undef variable not unmappable /, "munmap detects undef perl variables and fails"); } { my $foo = "234"; undef($foo); eval {munmap($foo)}; like($@, qr/^undef variable not unmappable /, "munmap detects undef perl variables and fails"); } { eval {munmap(undef)}; like($@, qr/^undef variable not unmappable /, "munmap detects undef perl variables and fails"); } SKIP: { skip "BSD kernels can't unmap a bad pointer like linux kernels can", 4 if($^O =~ m/bsd/i || $^O =~ m/darwin/i); foreach my $foo ("", "1234", "1.232", "abcdefg" ){ eval {munmap($foo)}; ok($! == EINVAL, "Unmapped strings die"); } } SKIP: { skip "BSD kernels can't unmap a bad pointer like linux kernels can", 7 if($^O =~ m/bsd/i || $^O =~ m/darwin/i); foreach my $foo (-1283843, -1, 0, 1, 2222131, 2.3451, -1213.12 ){ eval {munmap($foo)}; like($@, qr/^variable is not a string/, "munmap detects ints and floats and fails"); } } Sys-Mmap-0.21/t/offset.t000644 000765 000024 00000002450 15160057053 016547 0ustar00todd.rinaldostaff000000 000000 #! perl use strict; use warnings; use Test::More tests => 4; use Sys::Mmap; use Fcntl qw(O_WRONLY O_CREAT O_TRUNC O_RDONLY); my $temp_file = "offset.tmp"; my $file_size = 8192; # Create a file large enough to map with an offset sysopen(FOO, $temp_file, O_WRONLY|O_CREAT|O_TRUNC) or die "$temp_file: $!\n"; print FOO "A" x $file_size; close FOO; # Test 1: mmap with non-zero offset and explicit munmap { my $data; sysopen(FOO, $temp_file, O_RDONLY) or die "$temp_file: $!\n"; mmap($data, 256, PROT_READ, MAP_SHARED, FOO, 256); close FOO; is(length($data), 256, "mmap with offset returns correct length"); is($data, "A" x 256, "mmap with offset returns correct data"); munmap($data); } # Test 2: mmap with non-zero offset, DESTROY cleanup (no explicit munmap) # This is the crash from GitHub issue #1 - segfault on cleanup when offset != 0 { my $data; sysopen(FOO, $temp_file, O_RDONLY) or die "$temp_file: $!\n"; mmap($data, 256, PROT_READ, MAP_SHARED, FOO, 256); close FOO; is(length($data), 256, "mmap with offset (DESTROY path) returns correct length"); # $data goes out of scope here - DESTROY is called instead of explicit munmap # Before the fix, this would segfault } pass("Survived DESTROY with non-zero offset (no segfault)"); unlink($temp_file); Sys-Mmap-0.21/t/mmap.t000644 000765 000024 00000004027 15157401011 016206 0ustar00todd.rinaldostaff000000 000000 #! perl use strict; use warnings; use Test::More tests => 8; use Sys::Mmap; use POSIX qw(uname); use FileHandle; my $temp_file = "mmap.tmp"; my $temp_file_contents = "ABCD1234" x 1000; sysopen(FOO, $temp_file, O_WRONLY|O_CREAT|O_TRUNC) or die "$temp_file: $!\n"; print FOO $temp_file_contents; close FOO; my $foo; sysopen(FOO, $temp_file, O_RDONLY) or die "$temp_file: $!\n"; # Test negative offsets fail. is(eval { mmap($foo, 0, PROT_READ, MAP_SHARED, FOO, -100); 1}, undef, "Negative seek fails."); like($@, qr/^\Qmmap: Cannot operate on a negative offset (-100)\E/, "croaks when negative offset is passed in"); # Now map the file for real mmap($foo, 0, PROT_READ, MAP_SHARED, FOO); close FOO; is($foo, $temp_file_contents, "RO access to the file produces valid data"); munmap($foo); sysopen(FOO, $temp_file, O_RDWR) or die "$temp_file: $!\n"; mmap($foo, 0, PROT_READ|PROT_WRITE, MAP_SHARED, FOO); close FOO; # Extract the kernel version from uname so we know if we have MAP_POPULATE my $linux_kernel = ((POSIX::uname())[2]); $linux_kernel =~ s/^([0-9]+\.[0-9]+).+?\z/$1/; SKIP: { skip "Only supported on newer Linux platforms. You have $linux_kernel", 1 unless $^O eq 'linux' && $linux_kernel >= 2.5; is($foo, $temp_file_contents, "Read ahead with MAP_POPULATE"); munmap($foo); sysopen(FOO, $temp_file, O_RDWR) or die "$temp_file: $!\n"; mmap($foo, 0, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_POPULATE, FOO); close FOO; }; substr($foo, 3, 1) = "Z"; substr($temp_file_contents, 3, 1) = "Z"; is($foo, $temp_file_contents, 'Foo can be altered in RW mode'); munmap($foo); sysopen(FOO, $temp_file, O_RDONLY) or die "$temp_file: $!\n"; my $bar = ; is($bar, $temp_file_contents, 'Altered foo reflects on disk'); { my $foo; my $file_size = -s $temp_file; open(my $fh, "<", $temp_file) or die; isa_ok($fh, 'GLOB'); mmap($foo, $file_size, &Sys::Mmap::PROT_READ, &Sys::Mmap::MAP_SHARED, $fh); is($foo, $temp_file_contents, 'Read $foo, when it comes from a FileHandle'); munmap($foo); } unlink($temp_file); Sys-Mmap-0.21/t/comprehensive.t000644 000765 000024 00000015416 15160057053 020136 0ustar00todd.rinaldostaff000000 000000 #! perl use strict; use warnings; use Test::More 'no_plan'; use Sys::Mmap; use Fcntl qw(O_WRONLY O_CREAT O_TRUNC O_RDONLY O_RDWR); my $temp_file = "comprehensive.tmp"; my $file_size = 8192; # Create a test file with known content sub create_test_file { my ($size, $pattern) = @_; $pattern = "ABCD1234" unless defined $pattern; sysopen(my $fh, $temp_file, O_WRONLY|O_CREAT|O_TRUNC) or die "$temp_file: $!\n"; my $content = ($pattern x int($size / length($pattern) + 1)); $content = substr($content, 0, $size); print $fh $content; close $fh; return $content; } # ---- Tied interface tests (new / TIESCALAR) ---- { my $content = create_test_file(4096); # Collect any warnings during tied cleanup to verify no munmap failures my @warnings; local $SIG{__WARN__} = sub { push @warnings, $_[0] }; { my $var; my $obj = Sys::Mmap->new($var, 4096, $temp_file); ok(defined $obj, "tied file: new() returns a defined object"); ok(tied($var), "tied file: variable is tied after new()"); is(length($var), 4096, "tied file: tied variable has correct length"); is($var, $content, "tied file: tied variable has correct content"); # Test STORE: writing through tied interface my $new_data = "HELLO"; $var = $new_data; is(substr($var, 0, length($new_data)), $new_data, "tied file: STORE writes data at beginning"); # Rest of mapping should be unchanged is(substr($var, length($new_data), 4), substr($content, length($new_data), 4), "tied file: STORE preserves rest of data"); # Let $var and $obj go out of scope together } pass("tied file: variable cleaned up without crash"); # The DESTROY fix should prevent munmap failures on the blessed reference my @munmap_warns = grep { /munmap failed/ } @warnings; is(scalar @munmap_warns, 0, "tied file: no munmap failures during DESTROY cleanup"); } { my @warnings; local $SIG{__WARN__} = sub { push @warnings, $_[0] }; { my $var; my $obj = Sys::Mmap->new($var, 4096); ok(defined $obj, "tied anon: new() with anonymous memory returns defined object"); ok(tied($var), "tied anon: variable is tied for anonymous memory"); is(length($var), 4096, "tied anon: anonymous tied variable has correct length"); $var = "test data"; is(substr($var, 0, 9), "test data", "tied anon: STORE works on anonymous memory"); } pass("tied anon: anonymous memory cleaned up without crash"); my @munmap_warns = grep { /munmap failed/ } @warnings; is(scalar @munmap_warns, 0, "tied anon: no munmap failures during DESTROY cleanup"); } { my @warnings; local $SIG{__WARN__} = sub { push @warnings, $_[0] }; # Create a tiny file create_test_file(100); is(-s $temp_file, 100, "tied grow: initial file is 100 bytes"); { my $var; Sys::Mmap->new($var, 4096, $temp_file); ok(tied($var), "tied grow: tied to grown file"); is(length($var), 4096, "tied grow: tied variable reflects grown size"); } # File should have been grown to 4096 ok(-s $temp_file >= 4096, "tied grow: file was grown to requested length"); my @munmap_warns = grep { /munmap failed/ } @warnings; is(scalar @munmap_warns, 0, "tied grow: no munmap failures during DESTROY cleanup"); } # ---- MAP_ANON tests ---- { my $data; my $addr = mmap($data, 4096, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, *STDOUT); ok(defined $addr, "MAP_ANON: mmap succeeds"); is(length($data), 4096, "MAP_ANON: mapping has correct length"); # Anonymous memory should be zero-filled is($data, "\0" x 4096, "MAP_ANON: memory is zero-filled"); # Write and read back substr($data, 0, 5) = "Hello"; is(substr($data, 0, 5), "Hello", "MAP_ANON: can write to region"); munmap($data); } { my $data; eval { mmap($data, 0, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, *STDOUT) }; like($@, qr/MAP_ANON.*no length/i, "MAP_ANON: len=0 croaks"); } # ---- len=0 with offset: inferred length should be file_size - offset ---- { my $content = create_test_file(8192); my $data; sysopen(my $fh, $temp_file, O_RDONLY) or die "$temp_file: $!\n"; mmap($data, 0, PROT_READ, MAP_SHARED, $fh); close $fh; is(length($data), 8192, "len=0: infers full file size"); is($data, $content, "len=0: maps entire file content"); munmap($data); } { my $content = create_test_file(8192); my $offset = 4096; my $data; sysopen(my $fh, $temp_file, O_RDONLY) or die "$temp_file: $!\n"; mmap($data, 0, PROT_READ, MAP_SHARED, $fh, $offset); close $fh; is(length($data), 8192 - $offset, "len=0 with offset: infers file_size - offset"); is($data, substr($content, $offset), "len=0 with offset: content matches file from offset"); munmap($data); } { my $content = create_test_file(8192); my $offset = 256; # likely not page-aligned my $data; sysopen(my $fh, $temp_file, O_RDONLY) or die "$temp_file: $!\n"; mmap($data, 0, PROT_READ, MAP_SHARED, $fh, $offset); close $fh; is(length($data), 8192 - $offset, "len=0 with non-aligned offset: infers correct remaining size"); is($data, substr($content, $offset), "len=0 with non-aligned offset: content matches"); munmap($data); } { create_test_file(4096); my $data; sysopen(my $fh, $temp_file, O_RDONLY) or die "$temp_file: $!\n"; eval { mmap($data, 0, PROT_READ, MAP_SHARED, $fh, 4096) }; close $fh; like($@, qr/offset.*beyond end of file/i, "len=0: offset at EOF croaks"); } { create_test_file(4096); my $data; sysopen(my $fh, $temp_file, O_RDONLY) or die "$temp_file: $!\n"; eval { mmap($data, 0, PROT_READ, MAP_SHARED, $fh, 8192) }; close $fh; like($@, qr/offset.*beyond end of file/i, "len=0: offset beyond EOF croaks"); } # ---- Explicit offset with explicit length ---- { my $content = create_test_file(8192); my $offset = 4096; my $len = 1024; my $data; sysopen(my $fh, $temp_file, O_RDONLY) or die "$temp_file: $!\n"; mmap($data, $len, PROT_READ, MAP_SHARED, $fh, $offset); close $fh; is(length($data), $len, "explicit offset+length: correct length"); is($data, substr($content, $offset, $len), "explicit offset+length: correct content"); munmap($data); } # ---- DESTROY cleanup (implicit munmap via scope exit) ---- { my $content = create_test_file(8192); { my $data; sysopen(my $fh, $temp_file, O_RDONLY) or die "$temp_file: $!\n"; mmap($data, 0, PROT_READ, MAP_SHARED, $fh); close $fh; is(length($data), 8192, "DESTROY: mmap succeeded before scope exit"); # $data goes out of scope - DESTROY called implicitly } pass("DESTROY: survived without explicit munmap"); } # Cleanup unlink($temp_file);