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