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