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