Debian Codegraph @

upstream/mageia-cauldron/man2/mmap.2

raw
1 '\" t
2 .\" Copyright 1996, Andries E. Brouwer <[email protected]>
3 .\" Copyright 2006-2007, Michael Kerrisk <[email protected]>
4 .\" Copyright, the authors of the Linux man-pages project
5 .\"
6 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
7 .\"
8 .TH mmap 2 2026-02-11 "Linux man-pages 6.17"
9 .SH NAME
10 mmap, munmap \- map or unmap files or devices into memory
11 .SH LIBRARY
12 Standard C library
13 .RI ( libc ,\~ \-lc )
14 .SH SYNOPSIS
15 .nf
16 .B #include <sys/mman.h>
17 .P
18 .BR "void *mmap(" "size_t length;"
19 .BI " void " addr [ length "], size_t " length \
20 ", int " prot ", int " flags ,
21 .BI " int " fd ", off_t " offset );
22 .BR "int munmap(" "size_t length;"
23 .BI " void " addr [ length "], size_t " length );
24 .fi
25 .P
26 See VERSIONS for information on feature test macro requirements.
27 .SH DESCRIPTION
28 .BR mmap ()
29 creates a new mapping in the virtual address space of
30 the calling process.
31 The starting address for the new mapping is specified in
32 .IR addr .
33 The
34 .I length
35 argument specifies the length of the mapping (which must be greater than 0).
36 .P
37 If
38 .I addr
39 is NULL,
40 then the kernel chooses the (page-aligned) address
41 at which to create the mapping;
42 this is the most portable method of creating a new mapping.
43 If
44 .I addr
45 is not NULL,
46 then the kernel takes it as a hint about where to place the mapping;
47 on Linux, the kernel will pick a nearby page boundary (but always above
48 or equal to the value specified by
49 .IR /proc/sys/vm/mmap_min_addr )
50 and attempt to create the mapping there.
51 If another mapping already exists there, the kernel picks a new address that
52 may or may not depend on the hint.
53 .\" Before Linux 2.6.24, the address was rounded up to the next page
54 .\" boundary; since Linux 2.6.24, it is rounded down!
55 The address of the new mapping is returned as the result of the call.
56 .P
57 The contents of a file mapping (as opposed to an anonymous mapping;
58 see
59 .B MAP_ANONYMOUS
60 below), are initialized using
61 .I length
62 bytes starting at offset
63 .I offset
64 in the file (or other object) referred to by the file descriptor
65 .IR fd .
66 .I offset
67 must be a multiple of the page size as returned by
68 .IR sysconf(_SC_PAGE_SIZE) .
69 .P
70 After the
71 .BR mmap ()
72 call has returned, the file descriptor,
73 .IR fd ,
74 can be closed immediately without invalidating the mapping.
75 .P
76 The
77 .I prot
78 argument describes the desired memory protection of the mapping
79 (and must not conflict with the open mode of the file).
80 It is either
81 .B PROT_NONE
82 or the bitwise OR of one or more of the following flags:
83 .TP 1.1i
84 .B PROT_EXEC
85 Pages may be executed.
86 .TP
87 .B PROT_READ
88 Pages may be read.
89 .TP
90 .B PROT_WRITE
91 Pages may be written.
92 .TP
93 .B PROT_NONE
94 Pages may not be accessed.
95 .\"
96 .SS The flags argument
97 The
98 .I flags
99 argument determines whether updates to the mapping
100 are visible to other processes mapping the same region,
101 and whether updates are carried through to the underlying file.
102 This behavior is determined by including exactly one
103 of the following values in
104 .IR flags :
105 .TP
106 .B MAP_SHARED
107 Share this mapping.
108 Updates to the mapping are visible to other processes mapping the same region,
109 and (in the case of file-backed mappings)
110 are carried through to the underlying file.
111 (To precisely control when updates are carried through
112 to the underlying file requires the use of
113 .BR msync (2).)
114 .TP
115 .BR MAP_SHARED_VALIDATE " (since Linux 4.15)"
116 This flag provides the same behavior as
117 .B MAP_SHARED
118 except that
119 .B MAP_SHARED
120 mappings ignore unknown flags in
121 .IR flags .
122 By contrast, when creating a mapping using
123 .BR MAP_SHARED_VALIDATE ,
124 the kernel verifies all passed flags are known and fails the
125 mapping with the error
126 .B EOPNOTSUPP
127 for unknown flags.
128 This mapping type is also required to be able to use some mapping flags
129 (e.g.,
130 .BR MAP_SYNC ).
131 .TP
132 .B MAP_PRIVATE
133 Create a private copy-on-write mapping.
134 Updates to the mapping are not visible to other processes
135 mapping the same file, and are not carried through to
136 the underlying file.
137 It is unspecified whether changes made to the file after the
138 .BR mmap ()
139 call are visible in the mapped region.
140 .P
141 Both
142 .B MAP_SHARED
143 and
144 .B MAP_PRIVATE
145 are described in POSIX.1-2001 and POSIX.1-2008.
146 .B MAP_SHARED_VALIDATE
147 is a Linux extension.
148 .P
149 In addition, zero or more of the following values can be ORed in
150 .IR flags :
151 .TP
152 .BR MAP_32BIT " (since Linux 2.4.20, 2.6)"
153 Put the mapping into the first 2 Gigabytes of the process address space.
154 This flag is supported only on x86-64, for 64-bit programs.
155 It was added to allow thread stacks to be allocated somewhere
156 in the first 2\ GB of memory,
157 so as to improve context-switch performance on some early
158 64-bit processors.
159 .\" See http://lwn.net/Articles/294642 "Tangled up in threads", 19 Aug 08
160 Modern x86-64 processors no longer have this performance problem,
161 so use of this flag is not required on those systems.
162 The
163 .B MAP_32BIT
164 flag is ignored when
165 .B MAP_FIXED
166 is set.
167 .TP
168 .B MAP_ANON
169 Synonym for
170 .BR MAP_ANONYMOUS ;
171 provided for compatibility with other implementations.
172 .TP
173 .B MAP_ANONYMOUS
174 The mapping is not backed by any file;
175 its contents are initialized to zero.
176 The
177 .I fd
178 argument is ignored;
179 however, some implementations require
180 .I fd
181 to be \-1 if
182 .B MAP_ANONYMOUS
183 (or
184 .BR MAP_ANON )
185 is specified,
186 and portable applications should ensure this.
187 The
188 .I offset
189 argument should be zero.
190 .\" See the pgoff overflow check in do_mmap().
191 .\" See the offset check in sys_mmap in arch/x86/kernel/sys_x86_64.c.
192 Support for
193 .B MAP_ANONYMOUS
194 in conjunction with
195 .B MAP_SHARED
196 was added in Linux 2.4.
197 .TP
198 .B MAP_DENYWRITE
199 This flag is ignored.
200 .\" Introduced in 1.1.36, removed in 1.3.24.
201 (Long ago\[em]Linux 2.0 and earlier\[em]it signaled
202 that attempts to write to the underlying file should fail with
203 .BR ETXTBSY .
204 But this was a source of denial-of-service attacks.)
205 .TP
206 .B MAP_EXECUTABLE
207 This flag is ignored.
208 .\" Introduced in 1.1.38, removed in 1.3.24. Flag tested in proc_follow_link.
209 .\" (Long ago, it signaled that the underlying file is an executable.
210 .\" However, that information was not really used anywhere.)
211 .\" Linus talked about DOS related to MAP_EXECUTABLE, but he was thinking of
212 .\" MAP_DENYWRITE?
213 .TP
214 .B MAP_FILE
215 Compatibility flag.
216 Ignored.
217 .\" On some systems, this was required as the opposite of
218 .\" MAP_ANONYMOUS -- mtk, 1 May 2007
219 .TP
220 .B MAP_FIXED
221 Don't interpret
222 .I addr
223 as a hint: place the mapping at exactly that address.
224 .I addr
225 must be suitably aligned:
226 for most architectures a multiple of the page size is sufficient;
227 however,
228 some architectures may impose additional restrictions.
229 If the memory region specified by
230 .I addr
231 and
232 .I length
233 overlaps pages of any existing mapping(s), then the overlapped
234 part of the existing mapping(s) will be discarded.
235 If the specified address cannot be used,
236 .BR mmap ()
237 will fail.
238 .IP
239 Software that aspires to be portable should use the
240 .B MAP_FIXED
241 flag with care,
242 keeping in mind that the exact layout of a process's memory mappings
243 is allowed to change significantly between Linux versions,
244 C library versions, and operating system releases.
245 .I Carefully read the discussion of this flag in NOTES!
246 .TP
247 .BR MAP_FIXED_NOREPLACE " (since Linux 4.17)"
248 .\" commit a4ff8e8620d3f4f50ac4b41e8067b7d395056843
249 This flag provides behavior that is similar to
250 .B MAP_FIXED
251 with respect to the
252 .I addr
253 enforcement, but differs in that
254 .B MAP_FIXED_NOREPLACE
255 never clobbers a preexisting mapped range.
256 If the requested range would collide with an existing mapping,
257 then this call fails with the error
258 .B EEXIST.
259 This flag can therefore be used as a way to atomically
260 (with respect to other threads)
261 attempt to map an address range:
262 one thread will succeed;
263 all others will report failure.
264 .IP
265 Note that older kernels which do not recognize the
266 .B MAP_FIXED_NOREPLACE
267 flag will typically (upon detecting a collision with a preexisting mapping)
268 fall back to a
269 .RB \[lq]non- MAP_FIXED \[rq]
270 type of behavior:
271 they will return an address that is different from the requested address.
272 Therefore, backward-compatible software
273 should check the returned address against the requested address.
274 .TP
275 .B MAP_GROWSDOWN
276 This flag is used for stacks.
277 It indicates to the kernel virtual memory system that the mapping
278 should extend downward in memory.
279 The return address is one page lower than the memory area that is
280 actually created in the process's virtual address space.
281 Touching an address in the "guard" page below the mapping will cause
282 the mapping to grow by a page.
283 This growth can be repeated until the mapping grows to within a
284 page of the high end of the next lower mapping,
285 at which point touching the "guard" page will result in a
286 .B SIGSEGV
287 signal.
288 .TP
289 .BR MAP_HUGETLB " (since Linux 2.6.32)"
290 Allocate the mapping using "huge" pages.
291 See the Linux kernel source file
292 .I Documentation/admin\-guide/mm/hugetlbpage.rst
293 for further information, as well as NOTES, below.
294 .TP
295 .B MAP_HUGE_2MB
296 .TQ
297 .BR MAP_HUGE_1GB " (since Linux 3.8)"
298 .\" See https://lwn.net/Articles/533499/
299 Used in conjunction with
300 .B MAP_HUGETLB
301 to select alternative hugetlb page sizes (respectively, 2\ MB and 1\ GB)
302 on systems that support multiple hugetlb page sizes.
303 .IP
304 More generally, the desired huge page size can be configured by encoding
305 the base-2 logarithm of the desired page size in the six bits at the offset
306 .BR MAP_HUGE_SHIFT .
307 (A value of zero in this bit field provides the default huge page size;
308 the default huge page size can be discovered via the
309 .I Hugepagesize
310 field exposed by
311 .IR /proc/meminfo .)
312 Thus, the above two constants are defined as:
313 .IP
314 .in +4n
315 .EX
316 #define MAP_HUGE_2MB (21 << MAP_HUGE_SHIFT)
317 #define MAP_HUGE_1GB (30 << MAP_HUGE_SHIFT)
318 .EE
319 .in
320 .IP
321 The range of huge page sizes that are supported by the system
322 can be discovered by listing the subdirectories in
323 .IR /sys/kernel/mm/hugepages .
324 .TP
325 .BR MAP_LOCKED " (since Linux 2.5.37)"
326 Mark the mapped region to be locked in the same way as
327 .BR mlock (2).
328 This implementation will try to populate (prefault) the whole range but the
329 .BR mmap ()
330 call doesn't fail with
331 .B ENOMEM
332 if this fails.
333 Therefore major faults might happen later on.
334 So the semantic is not as strong as
335 .BR mlock (2).
336 One should use
337 .BR mmap ()
338 plus
339 .BR mlock (2)
340 when major faults are not acceptable after the initialization of the mapping.
341 The
342 .B MAP_LOCKED
343 flag is ignored in older kernels.
344 .\" If set, the mapped pages will not be swapped out.
345 .TP
346 .BR MAP_NONBLOCK " (since Linux 2.5.46)"
347 This flag is meaningful only in conjunction with
348 .BR MAP_POPULATE .
349 Don't perform read-ahead:
350 create page tables entries only for pages
351 that are already present in RAM.
352 Since Linux 2.6.23,
353 .\" commit 54cb8821de07f2ffcd28c380ce9b93d5784b40d7
354 this flag causes
355 .B MAP_POPULATE
356 to do nothing.
357 One day, the combination of
358 .B MAP_POPULATE
359 and
360 .B MAP_NONBLOCK
361 may be reimplemented.
362 .TP
363 .B MAP_NORESERVE
364 Do not reserve swap space for this mapping.
365 When swap space is reserved, one has the guarantee
366 that it is possible to modify the mapping.
367 When swap space is not reserved one might get
368 .B SIGSEGV
369 upon a write
370 if no physical memory is available.
371 See also the discussion of the file
372 .I /proc/sys/vm/overcommit_memory
373 in
374 .BR proc_sys_vm (5).
375 Before Linux 2.6, this flag had effect only for
376 private writable mappings.
377 .TP
378 .BR MAP_POPULATE " (since Linux 2.5.46)"
379 Populate (prefault) page tables for a mapping.
380 For a file mapping, this causes read-ahead on the file.
381 This will help to reduce blocking on page faults later.
382 The
383 .BR mmap ()
384 call doesn't fail if the mapping cannot be populated (for example, due
385 to limitations on the number of mapped huge pages when using
386 .BR MAP_HUGETLB ).
387 Support for
388 .B MAP_POPULATE
389 in conjunction with private mappings was added in Linux 2.6.23.
390 .TP
391 .BR MAP_STACK " (since Linux 2.6.27)"
392 Allocate the mapping at an address suitable for a process
393 or thread stack.
394 .IP
395 This flag is currently a no-op on Linux.
396 However, by employing this flag, applications can ensure that
397 they transparently obtain support if the flag
398 is implemented in the future.
399 Thus, it is used in the glibc threading implementation to allow for
400 the fact that some architectures may (later) require special treatment
401 for stack allocations.
402 .\" See http://lwn.net/Articles/294642 "Tangled up in threads", 19 Aug 08
403 .\" commit cd98a04a59e2f94fa64d5bf1e26498d27427d5e7
404 .\" http://thread.gmane.org/gmane.linux.kernel/720412
405 .\" "pthread_create() slow for many threads; also time to revisit 64b
406 .\" context switch optimization?"
407 A further reason to employ this flag is portability:
408 .B MAP_STACK
409 exists (and has an effect) on some other systems (e.g., some of the BSDs).
410 .TP
411 .BR MAP_SYNC " (since Linux 4.15)"
412 This flag is available only with the
413 .B MAP_SHARED_VALIDATE
414 mapping type;
415 mappings of type
416 .B MAP_SHARED
417 will silently ignore this flag.
418 This flag is supported only for files supporting DAX
419 (direct mapping of persistent memory).
420 For other files, creating a mapping with this flag results in an
421 .B EOPNOTSUPP
422 error.
423 .IP
424 Shared file mappings with this flag provide the guarantee that while
425 some memory is mapped writable in the address space of the process,
426 it will be visible in the same file at the same offset even after
427 the system crashes or is rebooted.
428 In conjunction with the use of appropriate CPU instructions,
429 this provides users of such mappings with a more efficient way
430 of making data modifications persistent.
431 .TP
432 .BR MAP_UNINITIALIZED " (since Linux 2.6.33)"
433 Don't clear anonymous pages.
434 This flag is intended to improve performance on embedded devices.
435 This flag is honored only if the kernel was configured with the
436 .B CONFIG_MMAP_ALLOW_UNINITIALIZED
437 option.
438 Because of the security implications,
439 that option is normally enabled only on embedded devices
440 (i.e., devices where one has complete control of the contents of user memory).
441 .P
442 Of the above flags, only
443 .B MAP_FIXED
444 is specified in POSIX.1-2001 and POSIX.1-2008.
445 However, most systems also support
446 .B MAP_ANONYMOUS
447 (or its synonym
448 .BR MAP_ANON ).
449 .\" FIXME . for later review when Issue 8 is one day released...
450 .\" POSIX may add MAP_ANON in the future
451 .\" http://austingroupbugs.net/tag_view_page.php?tag_id=8
452 .\" http://austingroupbugs.net/view.php?id=850
453 .SS munmap()
454 The
455 .BR munmap ()
456 system call deletes the mappings for the specified address range, and
457 causes further references to addresses within the range to generate
458 invalid memory references.
459 The region is also automatically unmapped
460 when the process is terminated.
461 On the other hand, closing the file
462 descriptor does not unmap the region.
463 .P
464 The address
465 .I addr
466 must be a multiple of the page size (but
467 .I length
468 need not be).
469 All pages containing a part
470 of the indicated range are unmapped, and subsequent references
471 to these pages will generate
472 .BR SIGSEGV .
473 It is not an error if the
474 indicated range does not contain any mapped pages.
475 .SH RETURN VALUE
476 On success,
477 .BR mmap ()
478 returns a pointer to the mapped area.
479 On error, the value
480 .B MAP_FAILED
481 (that is,
482 .IR "(void\ *)\ \-1" )
483 is returned, and
484 .I errno
485 is set to indicate the error.
486 .P
487 On success,
488 .BR munmap ()
489 returns 0.
490 On failure, it returns \-1, and
491 .I errno
492 is set to indicate the error (probably to
493 .BR EINVAL ).
494 .SH ERRORS
495 .TP
496 .B EACCES
497 A file descriptor refers to a non-regular file.
498 Or a file mapping was requested, but
499 .I fd
500 is not open for reading.
501 Or
502 .B MAP_SHARED
503 was requested and
504 .B PROT_WRITE
505 is set, but
506 .I fd
507 is not open in read/write
508 .RB ( O_RDWR )
509 mode.
510 Or
511 .B PROT_WRITE
512 is set, but the file is append-only.
513 .TP
514 .B EAGAIN
515 The file has been locked, or too much memory has been locked (see
516 .BR setrlimit (2)).
517 .TP
518 .B EBADF
519 .I fd
520 is not a valid file descriptor (and
521 .B MAP_ANONYMOUS
522 was not set).
523 .TP
524 .B EEXIST
525 .B MAP_FIXED_NOREPLACE
526 was specified in
527 .IR flags ,
528 and the range covered by
529 .I addr
530 and
531 .I length
532 clashes with an existing mapping.
533 .TP
534 .B EINVAL
535 We don't like
536 .IR addr ,
537 .IR length ,
538 or
539 .I offset
540 (e.g., they are too large, or not aligned on a page boundary).
541 .TP
542 .B EINVAL
543 (since Linux 2.6.12)
544 .I length
545 was 0.
546 .TP
547 .B EINVAL
548 .I flags
549 contained none of
550 .BR MAP_PRIVATE ,
551 .BR MAP_SHARED ,
552 or
553 .BR MAP_SHARED_VALIDATE .
554 .TP
555 .B ENFILE
556 .\" This is for shared anonymous segments
557 .\" [2.6.7] shmem_zero_setup()-->shmem_file_setup()-->get_empty_filp()
558 The system-wide limit on the total number of open files has been reached.
559 .\" .TP
560 .\" .B ENOEXEC
561 .\" A file could not be mapped for reading.
562 .TP
563 .B ENODEV
564 The underlying filesystem of the specified file does not support
565 memory mapping.
566 .TP
567 .B ENOMEM
568 No memory is available.
569 .TP
570 .B ENOMEM
571 The process's maximum number of mappings would have been exceeded.
572 This error can also occur for
573 .BR munmap (),
574 when unmapping a region in the middle of an existing mapping,
575 since this results in two smaller mappings on either side of
576 the region being unmapped.
577 .TP
578 .B ENOMEM
579 (since Linux 4.7)
580 The process's
581 .B RLIMIT_DATA
582 limit, described in
583 .BR getrlimit (2),
584 would have been exceeded.
585 .TP
586 .B ENOMEM
587 We don't like
588 .IR addr ,
589 because it exceeds the virtual address space of the CPU.
590 .TP
591 .B EOVERFLOW
592 On 32-bit architecture together with the large file extension
593 (i.e., using 64-bit
594 .IR off_t ):
595 the number of pages used for
596 .I length
597 plus number of pages used for
598 .I offset
599 would overflow
600 .I "unsigned long"
601 (32 bits).
602 .TP
603 .B EPERM
604 The
605 .I prot
606 argument asks for
607 .B PROT_EXEC
608 but the mapped area belongs to a file on a filesystem that
609 was mounted no-exec.
610 .\" (Since Linux 2.4.25 / Linux 2.6.0.)
611 .TP
612 .B EPERM
613 The operation was prevented by a file seal;
614 see
615 .BR fcntl (2).
616 .TP
617 .B EPERM
618 The
619 .B MAP_HUGETLB
620 flag was specified, but the caller was not privileged (did not have the
621 .B CAP_IPC_LOCK
622 capability)
623 and is not a member of the
624 .I hugetlb_shm_group
625 group;
626 see the description of
627 .I /proc/sys/vm/hugetlb_shm_group
628 in
629 .BR proc_sys_vm (5).
630 .TP
631 .B ETXTBSY
632 .B MAP_DENYWRITE
633 was set but the object specified by
634 .I fd
635 is open for writing.
636 .P
637 Use of a mapped region can result in these signals:
638 .TP
639 .B SIGSEGV
640 Attempted write into a region mapped as read-only.
641 .TP
642 .B SIGBUS
643 Attempted access to a page of the buffer that lies beyond the
644 end of the mapped file.
645 For an explanation of the treatment of the bytes in the page that
646 corresponds to the end of a mapped file that is not a multiple
647 of the page size, see NOTES.
648 .SH ATTRIBUTES
649 For an explanation of the terms used in this section, see
650 .BR attributes (7).
651 .TS
652 allbox;
653 lbx lb lb
654 l l l.
655 Interface Attribute Value
656 T{
657 .na
658 .nh
659 .BR mmap (),
660 .BR munmap ()
661 T} Thread safety MT-Safe
662 .TE
663 .SH VERSIONS
664 On some hardware architectures (e.g., i386),
665 .B PROT_WRITE
666 implies
667 .BR PROT_READ .
668 It is architecture dependent whether
669 .B PROT_READ
670 implies
671 .B PROT_EXEC
672 or not.
673 Portable programs should always set
674 .B PROT_EXEC
675 if they intend to execute code in the new mapping.
676 .P
677 The portable way to create a mapping is to specify
678 .I addr
679 as 0 (NULL), and omit
680 .B MAP_FIXED
681 from
682 .IR flags .
683 In this case, the system chooses the address for the mapping;
684 the address is chosen so as not to conflict with any existing mapping,
685 and will not be 0.
686 If the
687 .B MAP_FIXED
688 flag is specified, and
689 .I addr
690 is 0 (NULL), then the mapped address will be 0 (NULL).
691 .P
692 Certain
693 .I flags
694 constants are defined only if suitable feature test macros are defined
695 (possibly by default):
696 .B _DEFAULT_SOURCE
697 with glibc 2.19 or later;
698 or
699 .B _BSD_SOURCE
700 or
701 .B _SVID_SOURCE
702 in glibc 2.19 and earlier.
703 (Employing
704 .B _GNU_SOURCE
705 also suffices,
706 and requiring that macro specifically would have been more logical,
707 since these flags are all Linux-specific.)
708 The relevant flags are:
709 .BR MAP_32BIT ,
710 .B MAP_ANONYMOUS
711 (and the synonym
712 .BR MAP_ANON ),
713 .BR MAP_DENYWRITE ,
714 .BR MAP_EXECUTABLE ,
715 .BR MAP_FILE ,
716 .BR MAP_GROWSDOWN ,
717 .BR MAP_HUGETLB ,
718 .BR MAP_LOCKED ,
719 .BR MAP_NONBLOCK ,
720 .BR MAP_NORESERVE ,
721 .BR MAP_POPULATE ,
722 and
723 .BR MAP_STACK .
724 .SS C library/kernel differences
725 This page describes the interface provided by the glibc
726 .BR mmap ()
727 wrapper function.
728 Originally, this function invoked a system call of the same name.
729 Since Linux 2.4, that system call has been superseded by
730 .BR mmap2 (2),
731 and nowadays
732 .\" Since around glibc 2.1/2.2, depending on the platform.
733 the glibc
734 .BR mmap ()
735 wrapper function invokes
736 .BR mmap2 (2)
737 with a suitably adjusted value for
738 .IR offset .
739 .SH STANDARDS
740 POSIX.1-2024.
741 .SH HISTORY
742 SVr4,
743 4.4BSD,
744 SUSv1,
745 POSIX.1-1996.
746 .\" SVr4 documents additional error codes ENXIO and ENODEV.
747 .\" SUSv2 documents additional error codes EMFILE and EOVERFLOW.
748 .P
749 On POSIX systems on which
750 .BR mmap (),
751 .BR msync (2),
752 and
753 .BR munmap ()
754 are available,
755 .B _POSIX_MAPPED_FILES
756 is defined in
757 .I <unistd.h>
758 to a value greater than 0.
759 (See also
760 .BR sysconf (3).)
761 .\" POSIX.1-2001: It shall be defined to -1 or 0 or 200112L.
762 .\" -1: unavailable, 0: ask using sysconf().
763 .\" glibc defines it to 1.
764 .SH NOTES
765 Memory mapped by
766 .BR mmap ()
767 is preserved across
768 .BR fork (2),
769 with the same attributes.
770 .P
771 A file is mapped in multiples of the page size.
772 For a file that is not
773 a multiple of the page size,
774 the remaining bytes in the partial page at the end of the mapping
775 are zeroed when mapped,
776 and modifications to that region are not written out to the file.
777 The effect of
778 changing the size of the underlying file of a mapping on the pages that
779 correspond to added or removed regions of the file is unspecified.
780 .P
781 An application can determine which pages of a mapping are
782 currently resident in the buffer/page cache using
783 .BR mincore (2).
784 .\"
785 .SS Using MAP_FIXED safely
786 The only safe use for
787 .B MAP_FIXED
788 is where the address range specified by
789 .I addr
790 and
791 .I length
792 was previously reserved using another mapping;
793 otherwise, the use of
794 .B MAP_FIXED
795 is hazardous because it forcibly removes preexisting mappings,
796 making it easy for a multithreaded process to corrupt its own address space.
797 .P
798 For example, suppose that thread A looks through
799 .IR /proc/ pid /maps
800 in order to locate an unused address range that it can map using
801 .BR MAP_FIXED ,
802 while thread B simultaneously acquires part or all of that same
803 address range.
804 When thread A subsequently employs
805 .BR mmap(MAP_FIXED) ,
806 it will effectively clobber the mapping that thread B created.
807 In this scenario,
808 thread B need not create a mapping directly;
809 simply making a library call that,
810 internally,
811 uses
812 .BR dlopen (3)
813 to load some other shared library, will suffice.
814 The
815 .BR dlopen (3)
816 call will map the library into the process's address space.
817 Furthermore, almost any library call may be implemented in a way that
818 adds memory mappings to the address space, either with this technique,
819 or by simply allocating memory.
820 Examples include
821 .BR brk (2),
822 .BR malloc (3),
823 .BR pthread_create (3),
824 and the PAM libraries
825 .UR http:\://www.linux-pam.org
826 .UE .
827 .P
828 Since Linux 4.17, a multithreaded program can use the
829 .B MAP_FIXED_NOREPLACE
830 flag to avoid the hazard described above
831 when attempting to create a mapping at a fixed address
832 that has not been reserved by a preexisting mapping.
833 .\"
834 .SS Timestamps changes for file-backed mappings
835 For file-backed mappings, the
836 .I st_atime
837 field for the mapped file may be updated at any time between the
838 .BR mmap ()
839 and the corresponding unmapping;
840 the first reference to a mapped page
841 will update the field if it has not been already.
842 .P
843 The
844 .I st_ctime
845 and
846 .I st_mtime
847 field for a file mapped with
848 .B PROT_WRITE
849 and
850 .B MAP_SHARED
851 will be updated after
852 a write to the mapped region, and before a subsequent
853 .BR msync (2)
854 with the
855 .B MS_SYNC
856 or
857 .B MS_ASYNC
858 flag, if one occurs.
859 .\"
860 .SS Huge page (Huge TLB) mappings
861 For mappings that employ huge pages, the requirements for the arguments of
862 .BR mmap ()
863 and
864 .BR munmap ()
865 differ somewhat from the requirements for mappings
866 that use the native system page size.
867 .P
868 For
869 .BR mmap (),
870 .I offset
871 must be a multiple of the underlying huge page size.
872 The system automatically aligns
873 .I length
874 to be a multiple of the underlying huge page size.
875 .P
876 For
877 .BR munmap (),
878 .IR addr ,
879 and
880 .I length
881 must both be a multiple of the underlying huge page size.
882 .\"
883 .SH CAVEATS
884 Unlike typical
885 .BR malloc (3)
886 implementations,
887 .BR mmap ()
888 does not prevent creating objects larger than
889 .BR PTRDIFF_MAX .
890 Objects that are larger than
891 .B PTRDIFF_MAX
892 only work in limited ways in C
893 (in particular,
894 pointer subtraction results in undefined behavior
895 if the result would be bigger than
896 .BR PTRDIFF_MAX ).
897 On top of that,
898 GCC also assumes that no object is bigger than
899 .BR PTRDIFF_MAX .
900 .B PTRDIFF_MAX
901 is usually half of the address space size;
902 so for 32-bit processes,
903 it is usually
904 .B 0x7fffffff
905 (almost 2 GiB).
906 .\"
907 .SH BUGS
908 On Linux, there are no guarantees like those suggested above under
909 .BR MAP_NORESERVE .
910 By default, any process can be killed
911 at any moment when the system runs out of memory.
912 .P
913 Before Linux 2.6.7, the
914 .B MAP_POPULATE
915 flag has effect only if
916 .I prot
917 is specified as
918 .BR PROT_NONE .
919 .P
920 SUSv3 specifies that
921 .BR mmap ()
922 should fail if
923 .I length
924 is 0.
925 However, before Linux 2.6.12,
926 .BR mmap ()
927 succeeded in this case: no mapping was created and the call returned
928 .IR addr .
929 Since Linux 2.6.12,
930 .BR mmap ()
931 fails with the error
932 .B EINVAL
933 for this case.
934 .P
935 POSIX specifies that the system shall always
936 zero fill any partial page at the end
937 of the object and that system will never write any modification of the
938 object beyond its end.
939 On Linux, when you write data to such partial page after the end
940 of the object, the data stays in the page cache even after the file
941 is closed and unmapped
942 and even though the data is never written to the file itself,
943 subsequent mappings may see the modified content.
944 In some cases, this could be fixed by calling
945 .BR msync (2)
946 before the unmap takes place;
947 however, this doesn't work on
948 .BR tmpfs (5)
949 (for example, when using the POSIX shared memory interface documented in
950 .BR shm_overview (7)).
951 .SH EXAMPLES
952 .\" FIXME . Add an example here that uses an anonymous shared region for
953 .\" IPC between parent and child.
954 The following program prints part of the file specified in
955 its first command-line argument to standard output.
956 The range of bytes to be printed is specified via offset and length
957 values in the second and third command-line arguments.
958 The program creates a memory mapping of the required
959 pages of the file and then uses
960 .BR write (2)
961 to output the desired bytes.
962 .SS Program source
963 .\" SRC BEGIN (mmap.c)
964 .EX
965 #include <err.h>
966 #include <fcntl.h>
967 #include <stdio.h>
968 #include <stdlib.h>
969 #include <sys/mman.h>
970 #include <sys/stat.h>
971 #include <sys/types.h>
972 #include <unistd.h>
973 \&
974 int
975 main(int argc, char *argv[])
976 {
977 int fd;
978 char *addr;
979 off_t offset, pa_offset;
980 size_t length;
981 ssize_t s;
982 struct stat sb;
983 \&
984 if (argc < 3 || argc > 4) {
985 fprintf(stderr, "%s file offset [length]\[rs]n", argv[0]);
986 exit(EXIT_FAILURE);
987 }
988 \&
989 fd = open(argv[1], O_RDONLY);
990 if (fd == \-1)
991 err(EXIT_FAILURE, "open");
992 \&
993 if (fstat(fd, &sb) == \-1) /* To obtain file size */
994 err(EXIT_FAILURE, "fstat");
995 \&
996 offset = atoi(argv[2]);
997 pa_offset = offset & \[ti](sysconf(_SC_PAGE_SIZE) \- 1);
998 /* offset for mmap() must be page aligned */
999 \&
1000 if (offset >= sb.st_size) {
1001 fprintf(stderr, "offset is past end of file\[rs]n");
1002 exit(EXIT_FAILURE);
1003 }
1004 \&
1005 if (argc == 4) {
1006 length = atoi(argv[3]);
1007 if (offset + length > sb.st_size)
1008 length = sb.st_size \- offset;
1009 /* Can\[aq]t display bytes past end of file */
1010 \&
1011 } else { /* No length arg ==> display to end of file */
1012 length = sb.st_size \- offset;
1013 }
1014 \&
1015 addr = mmap(NULL, length + offset \- pa_offset, PROT_READ,
1016 MAP_PRIVATE, fd, pa_offset);
1017 if (addr == MAP_FAILED)
1018 err(EXIT_FAILURE, "mmap");
1019 \&
1020 s = write(STDOUT_FILENO, addr + offset \- pa_offset, length);
1021 if (s != length) {
1022 if (s == \-1)
1023 err(EXIT_FAILURE, "write");
1024 \&
1025 fprintf(stderr, "partial write");
1026 exit(EXIT_FAILURE);
1027 }
1028 \&
1029 munmap(addr, length + offset \- pa_offset);
1030 close(fd);
1031 \&
1032 exit(EXIT_SUCCESS);
1033 }
1034 .EE
1035 .\" SRC END
1036 .SH SEE ALSO
1037 .BR ftruncate (2),
1038 .BR getpagesize (2),
1039 .BR memfd_create (2),
1040 .BR mincore (2),
1041 .BR mlock (2),
1042 .BR mmap2 (2),
1043 .BR mprotect (2),
1044 .BR mremap (2),
1045 .BR msync (2),
1046 .BR remap_file_pages (2),
1047 .BR setrlimit (2),
1048 .BR shmat (2),
1049 .BR userfaultfd (2),
1050 .BR shm_open (3),
1051 .BR shm_overview (7)
1052 .P
1053 The descriptions of the following files in
1054 .BR proc (5):
1055 .IR /proc/ pid /maps ,
1056 .IR /proc/ pid /map_files ,
1057 and
1058 .IR /proc/ pid /smaps .
1059 .P
1060 B.O.\& Gallmeister, POSIX.4, O'Reilly, pp.\& 128\[en]129 and 389\[en]391.
1061 .\"
1062 .\" Repeat after me: private read-only mappings are 100% equivalent to
1063 .\" shared read-only mappings. No ifs, buts, or maybes. -- Linus