GBytes: add new g_bytes_take_zero_copy_fd() function
[platform/upstream/glib.git] / glib / gbytes.c
1 /*
2  * Copyright © 2009, 2010 Codethink Limited
3  * Copyright © 2011 Collabora Ltd.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the licence, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
17  *
18  * Author: Ryan Lortie <desrt@desrt.ca>
19  *         Stef Walter <stefw@collabora.co.uk>
20  */
21
22 #include "config.h"
23
24 #include "gbytes.h"
25
26 #include <glib/garray.h>
27 #include <glib/gstrfuncs.h>
28 #include <glib/gatomic.h>
29 #include <glib/gslice.h>
30 #include <glib/gtestutils.h>
31 #include <glib/gmem.h>
32 #include <glib/gmessages.h>
33
34 #include <string.h>
35 #include <errno.h>
36 #include <sys/stat.h>
37 #include <sys/types.h>
38
39 #ifdef G_OS_UNIX
40 #include "glib-unix.h"
41 #include <sys/mman.h>
42 #endif
43
44 /**
45  * GBytes:
46  *
47  * A simple refcounted data type representing an immutable sequence of zero or
48  * more bytes from an unspecified origin.
49  *
50  * The purpose of a #GBytes is to keep the memory region that it holds
51  * alive for as long as anyone holds a reference to the bytes.  When
52  * the last reference count is dropped, the memory is released. Multiple
53  * unrelated callers can use byte data in the #GBytes without coordinating
54  * their activities, resting assured that the byte data will not change or
55  * move while they hold a reference.
56  *
57  * A #GBytes can come from many different origins that may have
58  * different procedures for freeing the memory region.  Examples are
59  * memory from g_malloc(), from memory slices, from a #GMappedFile or
60  * memory from other allocators.
61  *
62  * #GBytes work well as keys in #GHashTable. Use g_bytes_equal() and
63  * g_bytes_hash() as parameters to g_hash_table_new() or g_hash_table_new_full().
64  * #GBytes can also be used as keys in a #GTree by passing the g_bytes_compare()
65  * function to g_tree_new().
66  *
67  * The data pointed to by this bytes must not be modified. For a mutable
68  * array of bytes see #GByteArray. Use g_bytes_unref_to_array() to create a
69  * mutable array for a #GBytes sequence. To create an immutable #GBytes from
70  * a mutable #GByteArray, use the g_byte_array_free_to_bytes() function.
71  *
72  * Since: 2.32
73  **/
74
75 struct _GBytes
76 {
77   gsize size;
78   gint  ref_count;
79   gint  type_or_fd;
80 };
81
82 typedef struct
83 {
84   GBytes bytes;
85 #if GLIB_SIZEOF_SIZE_T == 4
86   guint pad;
87 #endif
88
89   guchar data[1];
90 } GBytesInline;
91
92 /* important: the ->data field of GBytesInline should always be 'nicely
93  * aligned'.
94  */
95 G_STATIC_ASSERT (G_STRUCT_OFFSET (GBytesInline, data) % (2 * sizeof (gpointer)) == 0);
96 G_STATIC_ASSERT (G_STRUCT_OFFSET (GBytesInline, data) % 8 == 0);
97
98
99 typedef struct
100 {
101   GBytes   bytes;
102
103   gpointer data;
104 } GBytesData;
105
106 typedef struct
107 {
108   GBytesData     data_bytes;
109
110   GDestroyNotify notify;
111   gpointer       user_data;
112 } GBytesNotify;
113
114 #define G_BYTES_TYPE_INLINE        (-1)
115 #define G_BYTES_TYPE_STATIC        (-2)
116 #define G_BYTES_TYPE_FREE          (-3)
117 #define G_BYTES_TYPE_NOTIFY        (-4)
118
119 /* All bytes are either inline or subtypes of GBytesData */
120 #define G_BYTES_IS_INLINE(bytes)   ((bytes)->type_or_fd == G_BYTES_TYPE_INLINE)
121 #define G_BYTES_IS_DATA(bytes)     (!G_BYTES_IS_INLINE(bytes))
122
123 /* More specific subtypes of GBytesData */
124 #define G_BYTES_IS_STATIC(bytes)   ((bytes)->type_or_fd == G_BYTES_TYPE_STATIC)
125 #define G_BYTES_IS_FREE(bytes)     ((bytes)->type_or_fd == G_BYTES_TYPE_FREE)
126 #define G_BYTES_IS_NOTIFY(bytes)   ((bytes)->type_or_fd == G_BYTES_TYPE_NOTIFY)
127
128 /* we have a memfd if type_or_fd >= 0 */
129 #define G_BYTES_IS_MEMFD(bytes)    ((bytes)->type_or_fd >= 0)
130
131 static gpointer
132 g_bytes_allocate (guint struct_size,
133                   guint type_or_fd,
134                   gsize data_size)
135 {
136   GBytes *bytes;
137
138   bytes = g_slice_alloc (struct_size);
139   bytes->size = data_size;
140   bytes->ref_count = 1;
141   bytes->type_or_fd = type_or_fd;
142
143   return bytes;
144 }
145
146 /**
147  * g_bytes_new:
148  * @data: (transfer none) (array length=size) (element-type guint8) (allow-none):
149  *        the data to be used for the bytes
150  * @size: the size of @data
151  *
152  * Creates a new #GBytes from @data.
153  *
154  * @data is copied. If @size is 0, @data may be %NULL.
155  *
156  * Returns: (transfer full): a new #GBytes
157  *
158  * Since: 2.32
159  */
160 GBytes *
161 g_bytes_new (gconstpointer data,
162              gsize         size)
163 {
164   GBytesInline *bytes;
165
166   g_return_val_if_fail (data != NULL || size == 0, NULL);
167
168   bytes = g_bytes_allocate (G_STRUCT_OFFSET (GBytesInline, data[size]), G_BYTES_TYPE_INLINE, size);
169   memcpy (bytes->data, data, size);
170
171   return (GBytes *) bytes;
172 }
173
174 /**
175  * g_bytes_new_take_zero_copy_fd:
176  * @fd: a file descriptor capable of being zero-copy-safe
177  *
178  * Creates a new #GBytes from @fd.
179  *
180  * @fd must be capable of being made zero-copy-safe.  In concrete terms,
181  * this means that a call to g_unix_fd_ensure_zero_copy_safe() on @fd
182  * will succeed.  This call will be made before returning.
183  *
184  * This call consumes @fd, transferring ownership to the returned
185  * #GBytes.
186  *
187  * Returns: (transfer full): a new #GBytes
188  *
189  * Since: 2.44
190  */
191 #ifdef G_OS_UNIX
192 GBytes *
193 g_bytes_new_take_zero_copy_fd (gint fd)
194 {
195   GBytesData *bytes;
196   struct stat buf;
197
198   g_return_val_if_fail_se (g_unix_fd_ensure_zero_copy_safe (fd), NULL);
199
200   /* We already checked this is a memfd... */
201   g_assert_se (fstat (fd, &buf) == 0);
202
203   bytes = g_bytes_allocate (sizeof (GBytesData), fd, buf.st_size);
204   bytes->data = mmap (NULL, buf.st_size, PROT_READ, MAP_SHARED, fd, 0);
205   if (bytes->data == MAP_FAILED)
206     /* this is similar to malloc() failing, so do the same... */
207     g_error ("mmap() on memfd failed: %s\n", g_strerror (errno));
208
209   return (GBytes *) bytes;
210 }
211 #endif /* G_OS_UNIX */
212
213 /**
214  * g_bytes_new_take:
215  * @data: (transfer full) (array length=size) (element-type guint8) (allow-none):
216           the data to be used for the bytes
217  * @size: the size of @data
218  *
219  * Creates a new #GBytes from @data.
220  *
221  * After this call, @data belongs to the bytes and may no longer be
222  * modified by the caller.  g_free() will be called on @data when the
223  * bytes is no longer in use. Because of this @data must have been created by
224  * a call to g_malloc(), g_malloc0() or g_realloc() or by one of the many
225  * functions that wrap these calls (such as g_new(), g_strdup(), etc).
226  *
227  * For creating #GBytes with memory from other allocators, see
228  * g_bytes_new_with_free_func().
229  *
230  * @data may be %NULL if @size is 0.
231  *
232  * Returns: (transfer full): a new #GBytes
233  *
234  * Since: 2.32
235  */
236 GBytes *
237 g_bytes_new_take (gpointer data,
238                   gsize    size)
239 {
240   GBytesData *bytes;
241
242   bytes = g_bytes_allocate (sizeof (GBytesNotify), G_BYTES_TYPE_FREE, size);
243   bytes->data = data;
244
245   return (GBytes *) bytes;
246 }
247
248 /**
249  * g_bytes_new_static: (skip)
250  * @data: (transfer full) (array length=size) (element-type guint8) (allow-none):
251           the data to be used for the bytes
252  * @size: the size of @data
253  *
254  * Creates a new #GBytes from static data.
255  *
256  * @data must be static (ie: never modified or freed). It may be %NULL if @size
257  * is 0.
258  *
259  * Returns: (transfer full): a new #GBytes
260  *
261  * Since: 2.32
262  */
263 GBytes *
264 g_bytes_new_static (gconstpointer data,
265                     gsize         size)
266 {
267   GBytesData *bytes;
268
269   g_return_val_if_fail (data != NULL || size == 0, NULL);
270
271   bytes = g_bytes_allocate (sizeof (GBytesData), G_BYTES_TYPE_STATIC, size);
272   bytes->data = (gpointer) data;
273
274   return (GBytes *) bytes;
275 }
276
277 /**
278  * g_bytes_new_with_free_func:
279  * @data: (array length=size) (allow-none): the data to be used for the bytes
280  * @size: the size of @data
281  * @free_func: the function to call to release the data
282  * @user_data: data to pass to @free_func
283  *
284  * Creates a #GBytes from @data.
285  *
286  * When the last reference is dropped, @free_func will be called with the
287  * @user_data argument.
288  *
289  * @data must not be modified after this call is made until @free_func has
290  * been called to indicate that the bytes is no longer in use.
291  *
292  * @data may be %NULL if @size is 0.
293  *
294  * Returns: (transfer full): a new #GBytes
295  *
296  * Since: 2.32
297  */
298 GBytes *
299 g_bytes_new_with_free_func (gconstpointer  data,
300                             gsize          size,
301                             GDestroyNotify free_func,
302                             gpointer       user_data)
303 {
304   GBytesNotify *bytes;
305
306   if (!free_func)
307     return g_bytes_new_static (data, size);
308
309   bytes = g_bytes_allocate (sizeof (GBytesNotify), G_BYTES_TYPE_NOTIFY, size);
310   bytes->data_bytes.data = (gpointer) data;
311   bytes->notify = free_func;
312   bytes->user_data = user_data;
313
314   return (GBytes *) bytes;
315 }
316
317 /**
318  * g_bytes_new_from_bytes:
319  * @bytes: a #GBytes
320  * @offset: offset which subsection starts at
321  * @length: length of subsection
322  *
323  * Creates a #GBytes which is a subsection of another #GBytes. The @offset +
324  * @length may not be longer than the size of @bytes.
325  *
326  * A reference to @bytes will be held by the newly created #GBytes until
327  * the byte data is no longer needed.
328  *
329  * Returns: (transfer full): a new #GBytes
330  *
331  * Since: 2.32
332  */
333 GBytes *
334 g_bytes_new_from_bytes (GBytes  *bytes,
335                         gsize    offset,
336                         gsize    length)
337 {
338   /* Note that length may be 0. */
339   g_return_val_if_fail (bytes != NULL, NULL);
340   g_return_val_if_fail (offset <= bytes->size, NULL);
341   g_return_val_if_fail (offset + length <= bytes->size, NULL);
342
343   return g_bytes_new_with_free_func ((gchar *) g_bytes_get_data (bytes, NULL) + offset, length,
344                                      (GDestroyNotify)g_bytes_unref, g_bytes_ref (bytes));
345 }
346
347 /**
348  * g_bytes_get_data:
349  * @bytes: a #GBytes
350  * @size: (out) (allow-none): location to return size of byte data
351  *
352  * Get the byte data in the #GBytes. This data should not be modified.
353  *
354  * This function will always return the same pointer for a given #GBytes.
355  *
356  * %NULL may be returned if @size is 0. This is not guaranteed, as the #GBytes
357  * may represent an empty string with @data non-%NULL and @size as 0. %NULL will
358  * not be returned if @size is non-zero.
359  *
360  * Returns: (transfer none) (array length=size) (type guint8) (allow-none): a pointer to the
361  *          byte data, or %NULL
362  *
363  * Since: 2.32
364  */
365 gconstpointer
366 g_bytes_get_data (GBytes *bytes,
367                   gsize  *size)
368 {
369   g_return_val_if_fail (bytes != NULL, NULL);
370
371   if (size)
372     *size = bytes->size;
373
374   if (G_BYTES_IS_DATA (bytes))
375     {
376       GBytesData *data_bytes = (GBytesData *) bytes;
377
378       return data_bytes->data;
379     }
380   else if (G_BYTES_IS_INLINE (bytes))
381     {
382       GBytesInline *inline_bytes = (GBytesInline *) bytes;
383
384       return inline_bytes->data;
385     }
386   else
387     g_assert_not_reached ();
388 }
389
390 /**
391  * g_bytes_get_size:
392  * @bytes: a #GBytes
393  *
394  * Get the size of the byte data in the #GBytes.
395  *
396  * This function will always return the same value for a given #GBytes.
397  *
398  * Returns: the size
399  *
400  * Since: 2.32
401  */
402 gsize
403 g_bytes_get_size (GBytes *bytes)
404 {
405   g_return_val_if_fail (bytes != NULL, 0);
406   return bytes->size;
407 }
408
409
410 /**
411  * g_bytes_ref:
412  * @bytes: a #GBytes
413  *
414  * Increase the reference count on @bytes.
415  *
416  * Returns: the #GBytes
417  *
418  * Since: 2.32
419  */
420 GBytes *
421 g_bytes_ref (GBytes *bytes)
422 {
423   g_return_val_if_fail (bytes != NULL, NULL);
424
425   g_atomic_int_inc (&bytes->ref_count);
426
427   return bytes;
428 }
429
430 /**
431  * g_bytes_unref:
432  * @bytes: (allow-none): a #GBytes
433  *
434  * Releases a reference on @bytes.  This may result in the bytes being
435  * freed.
436  *
437  * Since: 2.32
438  */
439 void
440 g_bytes_unref (GBytes *bytes)
441 {
442   if (bytes == NULL)
443     return;
444
445   if (g_atomic_int_dec_and_test (&bytes->ref_count))
446     {
447       switch (bytes->type_or_fd)
448         {
449         case G_BYTES_TYPE_STATIC:
450           /* data does not need to be freed */
451           g_slice_free (GBytesData, (GBytesData *) bytes);
452           break;
453
454         case G_BYTES_TYPE_INLINE:
455           /* data will be freed along with struct */
456           g_slice_free1 (G_STRUCT_OFFSET (GBytesInline, data[bytes->size]), bytes);
457           break;
458
459         case G_BYTES_TYPE_FREE:
460           {
461             GBytesData *data_bytes = (GBytesData *) bytes;
462
463             g_free (data_bytes->data);
464
465             g_slice_free (GBytesData, data_bytes);
466             break;
467           }
468
469         case G_BYTES_TYPE_NOTIFY:
470           {
471             GBytesNotify *notify_bytes = (GBytesNotify *) bytes;
472
473             /* We don't create GBytesNotify if callback was NULL */
474             (* notify_bytes->notify) (notify_bytes->user_data);
475
476             g_slice_free (GBytesNotify, notify_bytes);
477             break;
478           }
479
480         default:
481           {
482             GBytesData *data_bytes = (GBytesData *) bytes;
483
484             g_assert (bytes->type_or_fd >= 0);
485
486             g_assert_se (munmap (data_bytes->data, bytes->size) == 0);
487             g_assert_se (close (bytes->type_or_fd) == 0);
488
489             g_slice_free (GBytesData, data_bytes);
490             break;
491           }
492         }
493     }
494 }
495
496 /**
497  * g_bytes_equal:
498  * @bytes1: (type GLib.Bytes): a pointer to a #GBytes
499  * @bytes2: (type GLib.Bytes): a pointer to a #GBytes to compare with @bytes1
500  *
501  * Compares the two #GBytes values being pointed to and returns
502  * %TRUE if they are equal.
503  *
504  * This function can be passed to g_hash_table_new() as the @key_equal_func
505  * parameter, when using non-%NULL #GBytes pointers as keys in a #GHashTable.
506  *
507  * Returns: %TRUE if the two keys match.
508  *
509  * Since: 2.32
510  */
511 gboolean
512 g_bytes_equal (gconstpointer bytes1,
513                gconstpointer bytes2)
514 {
515   gconstpointer d1, d2;
516   gsize s1, s2;
517
518   g_return_val_if_fail (bytes1 != NULL, FALSE);
519   g_return_val_if_fail (bytes2 != NULL, FALSE);
520
521   d1 = g_bytes_get_data ((GBytes *) bytes1, &s1);
522   d2 = g_bytes_get_data ((GBytes *) bytes2, &s2);
523
524   if (s1 != s2)
525     return FALSE;
526
527   if (d1 == d2)
528     return TRUE;
529
530   return memcmp (d1, d2, s1) == 0;
531 }
532
533 /**
534  * g_bytes_hash:
535  * @bytes: (type GLib.Bytes): a pointer to a #GBytes key
536  *
537  * Creates an integer hash code for the byte data in the #GBytes.
538  *
539  * This function can be passed to g_hash_table_new() as the @key_hash_func
540  * parameter, when using non-%NULL #GBytes pointers as keys in a #GHashTable.
541  *
542  * Returns: a hash value corresponding to the key.
543  *
544  * Since: 2.32
545  */
546 guint
547 g_bytes_hash (gconstpointer bytes)
548 {
549   const guchar *data;
550   const guchar *end;
551   gsize size;
552   guint32 h = 5381;
553
554   g_return_val_if_fail (bytes != NULL, 0);
555
556   data = g_bytes_get_data ((GBytes *) bytes, &size);
557   end = data + size;
558
559   while (data != end)
560     h = (h << 5) + h + *(data++);
561
562   return h;
563 }
564
565 /**
566  * g_bytes_compare:
567  * @bytes1: (type GLib.Bytes): a pointer to a #GBytes
568  * @bytes2: (type GLib.Bytes): a pointer to a #GBytes to compare with @bytes1
569  *
570  * Compares the two #GBytes values.
571  *
572  * This function can be used to sort GBytes instances in lexographical order.
573  *
574  * Returns: a negative value if bytes2 is lesser, a positive value if bytes2 is
575  *          greater, and zero if bytes2 is equal to bytes1
576  *
577  * Since: 2.32
578  */
579 gint
580 g_bytes_compare (gconstpointer bytes1,
581                  gconstpointer bytes2)
582 {
583   gconstpointer d1, d2;
584   gsize s1, s2;
585   gint ret;
586
587   g_return_val_if_fail (bytes1 != NULL, 0);
588   g_return_val_if_fail (bytes2 != NULL, 0);
589
590   d1 = g_bytes_get_data ((GBytes *) bytes1, &s1);
591   d2 = g_bytes_get_data ((GBytes *) bytes2, &s2);
592
593   ret = memcmp (d1, d2, MIN (s1, s2));
594   if (ret == 0 && s1 != s2)
595     ret = s1 < s2 ? -1 : 1;
596
597   return ret;
598 }
599
600 /**
601  * g_bytes_unref_to_data:
602  * @bytes: (transfer full): a #GBytes
603  * @size: location to place the length of the returned data
604  *
605  * Unreferences the bytes, and returns a pointer the same byte data
606  * contents.
607  *
608  * As an optimization, the byte data is returned without copying if this was
609  * the last reference to bytes and bytes was created with g_bytes_new(),
610  * g_bytes_new_take() or g_byte_array_free_to_bytes(). In all other cases the
611  * data is copied.
612  *
613  * Returns: (transfer full): a pointer to the same byte data, which should
614  *          be freed with g_free()
615  *
616  * Since: 2.32
617  */
618 gpointer
619 g_bytes_unref_to_data (GBytes *bytes,
620                        gsize  *size)
621 {
622   gpointer result;
623
624   g_return_val_if_fail (bytes != NULL, NULL);
625   g_return_val_if_fail (size != NULL, NULL);
626
627
628   /*
629    * Optimal path: if this is was the last reference, then we can return
630    * the data from this GBytes without copying.
631    */
632   if (G_BYTES_IS_FREE(bytes) && g_atomic_int_get (&bytes->ref_count) == 1)
633     {
634       GBytesData *data_bytes = (GBytesData *) bytes;
635
636       result = data_bytes->data;
637       *size = bytes->size;
638
639       g_slice_free (GBytesData, data_bytes);
640     }
641   else
642     {
643       gconstpointer data;
644
645       data = g_bytes_get_data (bytes, size);
646       result = g_memdup (data, *size);
647       g_bytes_unref (bytes);
648     }
649
650   return result;
651 }
652
653 /**
654  * g_bytes_unref_to_array:
655  * @bytes: (transfer full): a #GBytes
656  *
657  * Unreferences the bytes, and returns a new mutable #GByteArray containing
658  * the same byte data.
659  *
660  * As an optimization, the byte data is transferred to the array without copying
661  * if this was the last reference to bytes and bytes was created with
662  * g_bytes_new(), g_bytes_new_take() or g_byte_array_free_to_bytes(). In all
663  * other cases the data is copied.
664  *
665  * Returns: (transfer full): a new mutable #GByteArray containing the same byte data
666  *
667  * Since: 2.32
668  */
669 GByteArray *
670 g_bytes_unref_to_array (GBytes *bytes)
671 {
672   gpointer data;
673   gsize size;
674
675   g_return_val_if_fail (bytes != NULL, NULL);
676
677   data = g_bytes_unref_to_data (bytes, &size);
678   return g_byte_array_new_take (data, size);
679 }