]> git.sesse.net Git - vlc/blob - modules/access/mmap.c
Set close-on-exec file for file inputs
[vlc] / modules / access / mmap.c
1 /*****************************************************************************
2  * mmap.c: memory-mapped file input
3  *****************************************************************************
4  * Copyright © 2007-2008 Rémi Denis-Courmont
5  * $Id$
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
20  *****************************************************************************/
21
22 #ifdef HAVE_CONFIG_H
23 # include <config.h>
24 #endif
25
26 #include <vlc_common.h>
27 #include <vlc_plugin.h>
28 #include <vlc_access.h>
29 #include <vlc_input.h>
30 #include <vlc_charset.h>
31 #include <vlc_interface.h>
32
33 #include <assert.h>
34
35 #include <errno.h>
36 #include <sys/types.h>
37 #include <unistd.h>
38 #include <fcntl.h>
39 #include <sys/stat.h>
40 #include <sys/mman.h>
41
42 #define FILE_MMAP_TEXT N_("Use file memory mapping")
43 #define FILE_MMAP_LONGTEXT N_( \
44     "Try to use memory mapping to read files and block devices." )
45
46 #ifndef NDEBUG
47 /*# define MMAP_DEBUG 1*/
48 #endif
49
50 static int Open (vlc_object_t *);
51 static void Close (vlc_object_t *);
52
53 vlc_module_begin();
54     set_shortname (N_("MMap"));
55     set_description (N_("Memory-mapped file input"));
56     set_category (CAT_INPUT);
57     set_subcategory (SUBCAT_INPUT_ACCESS);
58     set_capability ("access", 52);
59     add_shortcut ("file");
60     set_callbacks (Open, Close);
61 #ifdef __APPLE__
62     add_bool ("file-mmap", false, NULL,
63 #else
64     add_bool ("file-mmap", true, NULL,
65 #endif
66               FILE_MMAP_TEXT, FILE_MMAP_LONGTEXT, true);
67 vlc_module_end();
68
69 static block_t *Block (access_t *);
70 static int Seek (access_t *, int64_t);
71 static int Control (access_t *, int, va_list);
72
73 struct access_sys_t
74 {
75     size_t page_size;
76     size_t mtu;
77     int    fd;
78 };
79
80 #define MMAP_SIZE (1 << 20)
81
82 static int Open (vlc_object_t *p_this)
83 {
84     access_t *p_access = (access_t *)p_this;
85     access_sys_t *p_sys;
86     const char *path = p_access->psz_path;
87     int fd;
88
89     if (!var_CreateGetBool (p_this, "file-mmap"))
90         return VLC_EGENERIC; /* disabled */
91
92     STANDARD_BLOCK_ACCESS_INIT;
93
94     if (!strcmp (p_access->psz_path, "-"))
95         fd = dup (0);
96     else
97     {
98         msg_Dbg (p_access, "opening file %s", path);
99         fd = utf8_open (path, O_RDONLY | O_NOCTTY, 0666);
100     }
101
102     if (fd == -1)
103     {
104         msg_Warn (p_access, "cannot open %s: %m", path);
105         goto error;
106     }
107     fcntl (fd, F_SETFD, fcntl (fd, F_GETFD) | FD_CLOEXEC);
108
109     /* mmap() is only safe for regular and block special files.
110      * For other types, it may be some idiosyncrasic interface (e.g. packet
111      * sockets are a good example), if it works at all. */
112     struct stat st;
113
114     if (fstat (fd, &st))
115     {
116         msg_Err (p_access, "cannot stat %s: %m", path);
117         goto error;
118     }
119
120     if (!S_ISREG (st.st_mode) && !S_ISBLK (st.st_mode))
121     {
122         msg_Dbg (p_access, "skipping non regular file %s", path);
123         goto error;
124     }
125
126 #if defined(HAVE_FCNTL_H)
127     /* We'd rather use any available memory for reading ahead
128      * than for caching what we've already mmap'ed */
129 # if defined(F_RDAHEAD)
130     fcntl (fd, F_RDAHEAD, 1);
131 # endif
132 # if defined(F_NOCACHE)
133     fcntl (fd, F_NOCACHE, 1);
134 # endif
135 #endif
136
137     /* Autodetect mmap() support */
138     if (st.st_size > 0)
139     {
140         void *addr = mmap (NULL, 1, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
141         if (addr != MAP_FAILED)
142             munmap (addr, 1);
143         else
144             goto error;
145     }
146
147     p_sys->page_size = sysconf (_SC_PAGE_SIZE);
148     p_sys->mtu = MMAP_SIZE;
149     if (p_sys->mtu < p_sys->page_size)
150         p_sys->mtu = p_sys->page_size;
151     p_sys->fd = fd;
152
153     p_access->info.i_size = st.st_size;
154 #ifdef HAVE_POSIX_FADVISE    
155     posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
156 #endif 
157
158     return VLC_SUCCESS;
159
160 error:
161     if (fd != -1)
162         close (fd);
163     free (p_sys);
164     return VLC_EGENERIC;
165 }
166
167
168 static void Close (vlc_object_t * p_this)
169 {
170     access_t *p_access = (access_t *)p_this;
171     access_sys_t *p_sys = p_access->p_sys;
172
173     close (p_sys->fd); /* don't care about error when only reading */
174     free (p_sys);
175 }
176
177 static block_t *Block (access_t *p_access)
178 {
179     access_sys_t *p_sys = p_access->p_sys;
180
181     /* Check if file size changed... */
182     struct stat st;
183
184     if ((fstat (p_sys->fd, &st) == 0)
185      && (st.st_size != p_access->info.i_size))
186     {
187         p_access->info.i_size = st.st_size;
188         p_access->info.i_update |= INPUT_UPDATE_SIZE;
189     }
190
191     if ((uint64_t)p_access->info.i_pos >= (uint64_t)p_access->info.i_size)
192     {
193         /* We are at end of file */
194         p_access->info.b_eof = true;
195         msg_Dbg (p_access, "at end of memory mapped file");
196         return NULL;
197     }
198
199 #ifdef MMAP_DEBUG
200     int64_t dbgpos = lseek (p_sys->fd, 0, SEEK_CUR);
201     if (dbgpos != p_access->info.i_pos)
202         msg_Err (p_access, "position: 0x%08llx instead of 0x%08llx",
203                  p_access->info.i_pos, dbgpos);
204 #endif
205
206     const uintptr_t page_mask = p_sys->page_size - 1;
207     /* Start the mapping on a page boundary: */
208     off_t  outer_offset = p_access->info.i_pos & ~page_mask;
209     /* Skip useless bytes at the beginning of the first page: */
210     size_t inner_offset = p_access->info.i_pos & page_mask;
211     /* Map no more bytes than remain: */
212     size_t length = p_sys->mtu;
213     if (outer_offset + length > p_access->info.i_size)
214         length = p_access->info.i_size - outer_offset;
215
216     assert (outer_offset <= p_access->info.i_pos);          /* and */
217     assert (p_access->info.i_pos < p_access->info.i_size); /* imply */
218     assert (outer_offset < p_access->info.i_size);         /* imply */
219     assert (length > 0);
220
221     /* NOTE: We use PROT_WRITE and MAP_PRIVATE so that the block can be
222      * modified down the chain, without messing up with the underlying
223      * original file. This does NOT need open write permission. */
224     void *addr = mmap (NULL, length, PROT_READ|PROT_WRITE, MAP_PRIVATE
225 #ifdef MAP_NO_CACHE
226                        | MAP_NOCACHE
227 #endif
228                        , p_sys->fd, outer_offset);
229     if (addr == MAP_FAILED)
230     {
231         msg_Err (p_access, "memory mapping failed (%m)");
232         intf_UserFatal (p_access, false, _("File reading failed"),
233                         _("VLC could not read the file."));
234         goto fatal;
235     }
236 #ifdef HAVE_POSIX_MADVISE    
237     posix_madvise (addr, length, POSIX_MADV_SEQUENTIAL);
238 #endif
239
240     block_t *block = block_mmap_Alloc (addr, length);
241     if (block == NULL)
242         goto fatal;
243
244     block->p_buffer += inner_offset;
245     block->i_buffer -= inner_offset;
246
247 #ifdef MMAP_DEBUG
248     msg_Dbg (p_access, "mapped 0x%lx bytes at %p from offset 0x%lx",
249              (unsigned long)length, addr, (unsigned long)outer_offset);
250
251     /* Compare normal I/O with memory mapping */
252     char *buf = malloc (block->i_buffer);
253     ssize_t i_read = read (p_sys->fd, buf, block->i_buffer);
254
255     if (i_read != (ssize_t)block->i_buffer)
256         msg_Err (p_access, "read %u instead of %u bytes", (unsigned)i_read,
257                  (unsigned)block->i_buffer);
258     if (memcmp (buf, block->p_buffer, block->i_buffer))
259         msg_Err (p_access, "inconsistent data buffer");
260     free (buf);
261 #endif
262
263     p_access->info.i_pos = outer_offset + length;
264     return block;
265
266 fatal:
267     p_access->info.b_eof = true;
268     return NULL;
269 }
270
271
272 static int Seek (access_t *p_access, int64_t i_pos)
273 {
274 #ifdef MMAP_DEBUG
275     lseek (p_access->p_sys->fd, i_pos, SEEK_SET);
276 #endif
277
278     p_access->info.i_pos = i_pos;
279     p_access->info.b_eof = false;
280     return VLC_SUCCESS;
281 }
282
283
284 static int Control (access_t *p_access, int query, va_list args)
285 {
286     access_sys_t *p_sys = p_access->p_sys;
287
288     switch (query)
289     {
290         case ACCESS_CAN_SEEK:
291         case ACCESS_CAN_FASTSEEK:
292         case ACCESS_CAN_PAUSE:
293         case ACCESS_CAN_CONTROL_PACE:
294             *((bool *)va_arg (args, bool *)) = true;
295             return VLC_SUCCESS;
296
297         case ACCESS_GET_MTU:
298             *((int *)va_arg (args, int *)) = p_sys->mtu;
299             return VLC_SUCCESS;
300
301         case ACCESS_GET_PTS_DELAY:
302         {
303             int delay_ms = var_CreateGetInteger (p_access, "file-caching");
304             *((int64_t *)va_arg (args, int64_t *)) = delay_ms * INT64_C (1000);
305             return VLC_SUCCESS;
306         }
307
308         case ACCESS_GET_TITLE_INFO:
309         case ACCESS_GET_META:
310             break;
311
312         case ACCESS_SET_PAUSE_STATE:
313             return VLC_SUCCESS;
314
315         case ACCESS_SET_TITLE:
316         case ACCESS_SET_SEEKPOINT:
317         case ACCESS_SET_PRIVATE_ID_STATE:
318         case ACCESS_SET_PRIVATE_ID_CA:
319         case ACCESS_GET_PRIVATE_ID_STATE:
320         case ACCESS_GET_CONTENT_TYPE:
321             break;
322
323         default:
324             msg_Warn (p_access, "unimplemented query %d in control", query);
325     }
326
327     return VLC_EGENERIC;
328 }