4a73827ecc8f69430e26c92aaaa6bfed33c45e6c
[platform/upstream/glib.git] / glib / gmappedfile.c
1 /* GLIB - Library of useful routines for C programming
2  * gmappedfile.c: Simplified wrapper around the mmap() function.
3  *
4  * Copyright 2005 Matthias Clasen
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 #include "config.h"
23
24 #include <errno.h>
25 #include <sys/types.h> 
26 #include <sys/stat.h> 
27 #include <fcntl.h>
28 #ifdef HAVE_UNISTD_H
29 #include <unistd.h>
30 #endif
31 #ifdef HAVE_MMAP
32 #include <sys/mman.h>
33 #endif
34
35 #include "glibconfig.h"
36
37 #ifdef G_OS_WIN32
38 #include <windows.h>
39 #include <io.h>
40
41 #define fstat(a,b) _fstati64(a,b)
42 #define stat _stati64
43
44 #ifndef S_ISREG
45 #define S_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
46 #endif
47
48 #endif
49
50 #include "gconvert.h"
51 #include "gerror.h"
52 #include "gfileutils.h"
53 #include "gmappedfile.h"
54 #include "gmem.h"
55 #include "gmessages.h"
56 #include "gstdio.h"
57 #include "gstrfuncs.h"
58 #include "gatomic.h"
59 #include "gbufferprivate.h"
60
61 #include "glibintl.h"
62
63
64 #ifndef _O_BINARY
65 #define _O_BINARY 0
66 #endif
67
68 #ifndef MAP_FAILED
69 #define MAP_FAILED ((void *) -1)
70 #endif
71
72 /**
73  * GMappedFile:
74  *
75  * The #GMappedFile represents a file mapping created with
76  * g_mapped_file_new(). It has only private members and should
77  * not be accessed directly.
78  */
79
80 struct _GMappedFile
81 {
82   gchar *contents;
83   gsize  length;
84   gpointer free_func;
85   int    ref_count;
86 #ifdef G_OS_WIN32
87   HANDLE mapping;
88 #endif
89 };
90
91 /* Make sure the layout of GMappedFile is the same as GBuffer's */
92 G_STATIC_ASSERT (G_STRUCT_OFFSET (GMappedFile, contents) ==
93                  G_STRUCT_OFFSET (GBuffer, data));
94 G_STATIC_ASSERT (G_STRUCT_OFFSET (GMappedFile, length) ==
95                  G_STRUCT_OFFSET (GBuffer, size));
96 G_STATIC_ASSERT (G_STRUCT_OFFSET (GMappedFile, ref_count) ==
97                  G_STRUCT_OFFSET (GBuffer, ref_count));
98 G_STATIC_ASSERT (G_STRUCT_OFFSET (GMappedFile, free_func) ==
99                  G_STRUCT_OFFSET (GBuffer, free_func));
100
101 static void
102 g_mapped_file_destroy (GMappedFile *file)
103 {
104   if (file->length)
105     {
106 #ifdef HAVE_MMAP
107       munmap (file->contents, file->length);
108 #endif
109 #ifdef G_OS_WIN32
110       UnmapViewOfFile (file->contents);
111       CloseHandle (file->mapping);
112 #endif
113     }
114
115   g_slice_free (GMappedFile, file);
116 }
117
118 static GMappedFile*
119 mapped_file_new_from_fd (int           fd,
120                          gboolean      writable,
121                          const gchar  *filename,
122                          GError      **error)
123 {
124   GMappedFile *file;
125   struct stat st;
126
127   file = g_slice_new0 (GMappedFile);
128   file->ref_count = 1;
129   file->free_func = g_mapped_file_destroy;
130
131   if (fstat (fd, &st) == -1)
132     {
133       int save_errno = errno;
134       gchar *display_filename = filename ? g_filename_display_name (filename) : NULL;
135
136       g_set_error (error,
137                    G_FILE_ERROR,
138                    g_file_error_from_errno (save_errno),
139                    _("Failed to get attributes of file '%s%s%s%s': fstat() failed: %s"),
140                    display_filename ? display_filename : "fd",
141                    display_filename ? "' " : "",
142                    display_filename ? display_filename : "",
143                    display_filename ? "'" : "",
144                    g_strerror (save_errno));
145       g_free (display_filename);
146       goto out;
147     }
148
149   /* mmap() on size 0 will fail with EINVAL, so we avoid calling mmap()
150    * in that case -- but only if we have a regular file; we still want
151    * attempts to mmap a character device to fail, for example.
152    */
153   if (st.st_size == 0 && S_ISREG (st.st_mode))
154     {
155       file->length = 0;
156       file->contents = NULL;
157       return file;
158     }
159
160   file->contents = MAP_FAILED;
161
162 #ifdef HAVE_MMAP
163   if (st.st_size > G_MAXSIZE)
164     {
165       errno = EINVAL;
166     }
167   else
168     {      
169       file->length = (gsize) st.st_size;
170       file->contents = (gchar *) mmap (NULL,  file->length,
171                                        writable ? PROT_READ|PROT_WRITE : PROT_READ,
172                                        MAP_PRIVATE, fd, 0);
173     }
174 #endif
175 #ifdef G_OS_WIN32
176   file->length = st.st_size;
177   file->mapping = CreateFileMapping ((HANDLE) _get_osfhandle (fd), NULL,
178                                      writable ? PAGE_WRITECOPY : PAGE_READONLY,
179                                      0, 0,
180                                      NULL);
181   if (file->mapping != NULL)
182     {
183       file->contents = MapViewOfFile (file->mapping,
184                                       writable ? FILE_MAP_COPY : FILE_MAP_READ,
185                                       0, 0,
186                                       0);
187       if (file->contents == NULL)
188         {
189           file->contents = MAP_FAILED;
190           CloseHandle (file->mapping);
191           file->mapping = NULL;
192         }
193     }
194 #endif
195
196   
197   if (file->contents == MAP_FAILED)
198     {
199       int save_errno = errno;
200       gchar *display_filename = filename ? g_filename_display_name (filename) : NULL;
201
202       g_set_error (error,
203                    G_FILE_ERROR,
204                    g_file_error_from_errno (save_errno),
205                    _("Failed to map %s%s%s%s: mmap() failed: %s"),
206                    display_filename ? display_filename : "fd",
207                    display_filename ? "' " : "",
208                    display_filename ? display_filename : "",
209                    display_filename ? "'" : "",
210                    g_strerror (save_errno));
211       g_free (display_filename);
212       goto out;
213     }
214
215   return file;
216
217  out:
218   g_slice_free (GMappedFile, file);
219
220   return NULL;
221 }
222
223 /**
224  * g_mapped_file_new:
225  * @filename: The path of the file to load, in the GLib filename encoding
226  * @writable: whether the mapping should be writable
227  * @error: return location for a #GError, or %NULL
228  *
229  * Maps a file into memory. On UNIX, this is using the mmap() function.
230  *
231  * If @writable is %TRUE, the mapped buffer may be modified, otherwise
232  * it is an error to modify the mapped buffer. Modifications to the buffer
233  * are not visible to other processes mapping the same file, and are not
234  * written back to the file.
235  *
236  * Note that modifications of the underlying file might affect the contents
237  * of the #GMappedFile. Therefore, mapping should only be used if the file
238  * will not be modified, or if all modifications of the file are done
239  * atomically (e.g. using g_file_set_contents()).
240  *
241  * If @filename is the name of an empty, regular file, the function
242  * will successfully return an empty #GMappedFile. In other cases of
243  * size 0 (e.g. device files such as /dev/null), @error will be set
244  * to the #GFileError value #G_FILE_ERROR_INVAL.
245  *
246  * Return value: a newly allocated #GMappedFile which must be unref'd
247  *    with g_mapped_file_unref(), or %NULL if the mapping failed.
248  *
249  * Since: 2.8
250  */
251 GMappedFile *
252 g_mapped_file_new (const gchar  *filename,
253                    gboolean      writable,
254                    GError      **error)
255 {
256   GMappedFile *file;
257   int fd;
258
259   g_return_val_if_fail (filename != NULL, NULL);
260   g_return_val_if_fail (!error || *error == NULL, NULL);
261
262   fd = g_open (filename, (writable ? O_RDWR : O_RDONLY) | _O_BINARY, 0);
263   if (fd == -1)
264     {
265       int save_errno = errno;
266       gchar *display_filename = g_filename_display_name (filename);
267
268       g_set_error (error,
269                    G_FILE_ERROR,
270                    g_file_error_from_errno (save_errno),
271                    _("Failed to open file '%s': open() failed: %s"),
272                    display_filename,
273                    g_strerror (save_errno));
274       g_free (display_filename);
275       return NULL;
276     }
277
278   file = mapped_file_new_from_fd (fd, writable, filename, error);
279
280   close (fd);
281
282   return file;
283 }
284
285
286 /**
287  * g_mapped_file_new_from_fd:
288  * @fd: The file descriptor of the file to load
289  * @writable: whether the mapping should be writable
290  * @error: return location for a #GError, or %NULL
291  *
292  * Maps a file into memory. On UNIX, this is using the mmap() function.
293  *
294  * If @writable is %TRUE, the mapped buffer may be modified, otherwise
295  * it is an error to modify the mapped buffer. Modifications to the buffer
296  * are not visible to other processes mapping the same file, and are not
297  * written back to the file.
298  *
299  * Note that modifications of the underlying file might affect the contents
300  * of the #GMappedFile. Therefore, mapping should only be used if the file
301  * will not be modified, or if all modifications of the file are done
302  * atomically (e.g. using g_file_set_contents()).
303  *
304  * Return value: a newly allocated #GMappedFile which must be unref'd
305  *    with g_mapped_file_unref(), or %NULL if the mapping failed.
306  *
307  * Since: 2.30
308  */
309 GMappedFile *
310 g_mapped_file_new_from_fd (gint          fd,
311                            gboolean      writable,
312                            GError      **error)
313 {
314   return mapped_file_new_from_fd (fd, writable, NULL, error);
315 }
316
317 /**
318  * g_mapped_file_get_length:
319  * @file: a #GMappedFile
320  *
321  * Returns the length of the contents of a #GMappedFile.
322  *
323  * Returns: the length of the contents of @file.
324  *
325  * Since: 2.8
326  */
327 gsize
328 g_mapped_file_get_length (GMappedFile *file)
329 {
330   g_return_val_if_fail (file != NULL, 0);
331
332   return file->length;
333 }
334
335 /**
336  * g_mapped_file_get_contents:
337  * @file: a #GMappedFile
338  *
339  * Returns the contents of a #GMappedFile. 
340  *
341  * Note that the contents may not be zero-terminated,
342  * even if the #GMappedFile is backed by a text file.
343  *
344  * If the file is empty then %NULL is returned.
345  *
346  * Returns: the contents of @file, or %NULL.
347  *
348  * Since: 2.8
349  */
350 gchar *
351 g_mapped_file_get_contents (GMappedFile *file)
352 {
353   g_return_val_if_fail (file != NULL, NULL);
354
355   return file->contents;
356 }
357
358 /**
359  * g_mapped_file_free:
360  * @file: a #GMappedFile
361  *
362  * This call existed before #GMappedFile had refcounting and is currently
363  * exactly the same as g_mapped_file_unref().
364  *
365  * Since: 2.8
366  * Deprecated:2.22: Use g_mapped_file_unref() instead.
367  */
368 void
369 g_mapped_file_free (GMappedFile *file)
370 {
371   g_mapped_file_unref (file);
372 }
373
374 /**
375  * g_mapped_file_ref:
376  * @file: a #GMappedFile
377  *
378  * Increments the reference count of @file by one.  It is safe to call
379  * this function from any thread.
380  *
381  * Return value: the passed in #GMappedFile.
382  *
383  * Since: 2.22
384  **/
385 GMappedFile *
386 g_mapped_file_ref (GMappedFile *file)
387 {
388   g_return_val_if_fail (file != NULL, NULL);
389
390   g_atomic_int_inc (&file->ref_count);
391
392   return file;
393 }
394
395 /**
396  * g_mapped_file_unref:
397  * @file: a #GMappedFile
398  *
399  * Decrements the reference count of @file by one.  If the reference count
400  * drops to 0, unmaps the buffer of @file and frees it.
401  *
402  * It is safe to call this function from any thread.
403  *
404  * Since 2.22
405  **/
406 void
407 g_mapped_file_unref (GMappedFile *file)
408 {
409   g_return_if_fail (file != NULL);
410
411   if (g_atomic_int_dec_and_test (&file->ref_count))
412     g_mapped_file_destroy (file);
413 }