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