Debian Codegraph @

upstream/debian-trixie/man2/mmap.2

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