[kdbus] sync with kdbus (kdbus.h - commit: 5ae1ecac44cb)
[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   if (buf.st_size == 0)
204     {
205       g_assert_se (close (fd) == 0);
206
207       return g_bytes_new (NULL, 0);
208     }
209
210   bytes = g_bytes_allocate (sizeof (GBytesData), fd, buf.st_size);
211   bytes->data = mmap (NULL, buf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
212   if (bytes->data == MAP_FAILED)
213     /* this is similar to malloc() failing, so do the same... */
214     g_error ("mmap() on memfd failed: %s\n", g_strerror (errno));
215
216   return (GBytes *) bytes;
217 }
218 #endif /* G_OS_UNIX */
219
220 /**
221  * g_bytes_new_take:
222  * @data: (transfer full) (array length=size) (element-type guint8) (allow-none):
223           the data to be used for the bytes
224  * @size: the size of @data
225  *
226  * Creates a new #GBytes from @data.
227  *
228  * After this call, @data belongs to the bytes and may no longer be
229  * modified by the caller.  g_free() will be called on @data when the
230  * bytes is no longer in use. Because of this @data must have been created by
231  * a call to g_malloc(), g_malloc0() or g_realloc() or by one of the many
232  * functions that wrap these calls (such as g_new(), g_strdup(), etc).
233  *
234  * For creating #GBytes with memory from other allocators, see
235  * g_bytes_new_with_free_func().
236  *
237  * @data may be %NULL if @size is 0.
238  *
239  * Returns: (transfer full): a new #GBytes
240  *
241  * Since: 2.32
242  */
243 GBytes *
244 g_bytes_new_take (gpointer data,
245                   gsize    size)
246 {
247   GBytesData *bytes;
248
249   bytes = g_bytes_allocate (sizeof (GBytesNotify), G_BYTES_TYPE_FREE, size);
250   bytes->data = data;
251
252   return (GBytes *) bytes;
253 }
254
255 /**
256  * g_bytes_new_static: (skip)
257  * @data: (transfer full) (array length=size) (element-type guint8) (allow-none):
258           the data to be used for the bytes
259  * @size: the size of @data
260  *
261  * Creates a new #GBytes from static data.
262  *
263  * @data must be static (ie: never modified or freed). It may be %NULL if @size
264  * is 0.
265  *
266  * Returns: (transfer full): a new #GBytes
267  *
268  * Since: 2.32
269  */
270 GBytes *
271 g_bytes_new_static (gconstpointer data,
272                     gsize         size)
273 {
274   GBytesData *bytes;
275
276   g_return_val_if_fail (data != NULL || size == 0, NULL);
277
278   bytes = g_bytes_allocate (sizeof (GBytesData), G_BYTES_TYPE_STATIC, size);
279   bytes->data = (gpointer) data;
280
281   return (GBytes *) bytes;
282 }
283
284 /**
285  * g_bytes_new_with_free_func:
286  * @data: (array length=size) (allow-none): the data to be used for the bytes
287  * @size: the size of @data
288  * @free_func: the function to call to release the data
289  * @user_data: data to pass to @free_func
290  *
291  * Creates a #GBytes from @data.
292  *
293  * When the last reference is dropped, @free_func will be called with the
294  * @user_data argument.
295  *
296  * @data must not be modified after this call is made until @free_func has
297  * been called to indicate that the bytes is no longer in use.
298  *
299  * @data may be %NULL if @size is 0.
300  *
301  * Returns: (transfer full): a new #GBytes
302  *
303  * Since: 2.32
304  */
305 GBytes *
306 g_bytes_new_with_free_func (gconstpointer  data,
307                             gsize          size,
308                             GDestroyNotify free_func,
309                             gpointer       user_data)
310 {
311   GBytesNotify *bytes;
312
313   if (!free_func)
314     return g_bytes_new_static (data, size);
315
316   bytes = g_bytes_allocate (sizeof (GBytesNotify), G_BYTES_TYPE_NOTIFY, size);
317   bytes->data_bytes.data = (gpointer) data;
318   bytes->notify = free_func;
319   bytes->user_data = user_data;
320
321   return (GBytes *) bytes;
322 }
323
324 /**
325  * g_bytes_new_from_bytes:
326  * @bytes: a #GBytes
327  * @offset: offset which subsection starts at
328  * @length: length of subsection
329  *
330  * Creates a #GBytes which is a subsection of another #GBytes. The @offset +
331  * @length may not be longer than the size of @bytes.
332  *
333  * A reference to @bytes will be held by the newly created #GBytes until
334  * the byte data is no longer needed.
335  *
336  * Returns: (transfer full): a new #GBytes
337  *
338  * Since: 2.32
339  */
340 GBytes *
341 g_bytes_new_from_bytes (GBytes  *bytes,
342                         gsize    offset,
343                         gsize    length)
344 {
345   /* Note that length may be 0. */
346   g_return_val_if_fail (bytes != NULL, NULL);
347   g_return_val_if_fail (offset <= bytes->size, NULL);
348   g_return_val_if_fail (offset + length <= bytes->size, NULL);
349
350   return g_bytes_new_with_free_func ((gchar *) g_bytes_get_data (bytes, NULL) + offset, length,
351                                      (GDestroyNotify)g_bytes_unref, g_bytes_ref (bytes));
352 }
353
354 /**
355  * g_bytes_get_data:
356  * @bytes: a #GBytes
357  * @size: (out) (allow-none): location to return size of byte data
358  *
359  * Get the byte data in the #GBytes. This data should not be modified.
360  *
361  * This function will always return the same pointer for a given #GBytes.
362  *
363  * %NULL may be returned if @size is 0. This is not guaranteed, as the #GBytes
364  * may represent an empty string with @data non-%NULL and @size as 0. %NULL will
365  * not be returned if @size is non-zero.
366  *
367  * Returns: (transfer none) (array length=size) (type guint8) (allow-none): a pointer to the
368  *          byte data, or %NULL
369  *
370  * Since: 2.32
371  */
372 gconstpointer
373 g_bytes_get_data (GBytes *bytes,
374                   gsize  *size)
375 {
376   g_return_val_if_fail (bytes != NULL, NULL);
377
378   if (size)
379     *size = bytes->size;
380
381   if (G_BYTES_IS_DATA (bytes))
382     {
383       GBytesData *data_bytes = (GBytesData *) bytes;
384
385       return data_bytes->data;
386     }
387   else if (G_BYTES_IS_INLINE (bytes))
388     {
389       GBytesInline *inline_bytes = (GBytesInline *) bytes;
390
391       return inline_bytes->data;
392     }
393   else
394     g_assert_not_reached ();
395 }
396
397 /**
398  * g_bytes_get_size:
399  * @bytes: a #GBytes
400  *
401  * Get the size of the byte data in the #GBytes.
402  *
403  * This function will always return the same value for a given #GBytes.
404  *
405  * Returns: the size
406  *
407  * Since: 2.32
408  */
409 gsize
410 g_bytes_get_size (GBytes *bytes)
411 {
412   g_return_val_if_fail (bytes != NULL, 0);
413   return bytes->size;
414 }
415
416 /**
417  * g_bytes_get_zero_copy_fd:
418  * @bytes: a #GBytes
419  *
420  * Gets the zero-copy fd from a #GBytes, if it has one.
421  *
422  * Returns -1 if @bytes was not created from a zero-copy fd.
423  *
424  * A #GBytes created with a zero-copy fd may have been internally
425  * converted into another type of #GBytes for any reason at all.  This
426  * function may therefore return -1 at any time, even for a #GBytes that
427  * was created with g_bytes_new_take_zero_copy_fd().
428  *
429  * The returned file descriptor belongs to @bytes.  Do not close it.
430  *
431  * Returns: a file descriptor, or -1
432  *
433  * Since: 2.44
434  */
435 gint
436 g_bytes_get_zero_copy_fd (GBytes *bytes)
437 {
438   g_return_val_if_fail (bytes != NULL, -1);
439
440   if (G_BYTES_IS_MEMFD (bytes))
441     return bytes->type_or_fd;
442   else
443     return -1;
444 }
445
446 /**
447  * g_bytes_ref:
448  * @bytes: a #GBytes
449  *
450  * Increase the reference count on @bytes.
451  *
452  * Returns: the #GBytes
453  *
454  * Since: 2.32
455  */
456 GBytes *
457 g_bytes_ref (GBytes *bytes)
458 {
459   g_return_val_if_fail (bytes != NULL, NULL);
460
461   g_atomic_int_inc (&bytes->ref_count);
462
463   return bytes;
464 }
465
466 /**
467  * g_bytes_unref:
468  * @bytes: (allow-none): a #GBytes
469  *
470  * Releases a reference on @bytes.  This may result in the bytes being
471  * freed.
472  *
473  * Since: 2.32
474  */
475 void
476 g_bytes_unref (GBytes *bytes)
477 {
478   if (bytes == NULL)
479     return;
480
481   if (g_atomic_int_dec_and_test (&bytes->ref_count))
482     {
483       switch (bytes->type_or_fd)
484         {
485         case G_BYTES_TYPE_STATIC:
486           /* data does not need to be freed */
487           g_slice_free (GBytesData, (GBytesData *) bytes);
488           break;
489
490         case G_BYTES_TYPE_INLINE:
491           /* data will be freed along with struct */
492           g_slice_free1 (G_STRUCT_OFFSET (GBytesInline, data[bytes->size]), bytes);
493           break;
494
495         case G_BYTES_TYPE_FREE:
496           {
497             GBytesData *data_bytes = (GBytesData *) bytes;
498
499             g_free (data_bytes->data);
500
501             g_slice_free (GBytesData, data_bytes);
502             break;
503           }
504
505         case G_BYTES_TYPE_NOTIFY:
506           {
507             GBytesNotify *notify_bytes = (GBytesNotify *) bytes;
508
509             /* We don't create GBytesNotify if callback was NULL */
510             (* notify_bytes->notify) (notify_bytes->user_data);
511
512             g_slice_free (GBytesNotify, notify_bytes);
513             break;
514           }
515
516         default:
517           {
518             GBytesData *data_bytes = (GBytesData *) bytes;
519
520             g_assert (bytes->type_or_fd >= 0);
521
522             g_assert_se (munmap (data_bytes->data, bytes->size) == 0);
523             g_assert_se (close (bytes->type_or_fd) == 0);
524
525             g_slice_free (GBytesData, data_bytes);
526             break;
527           }
528         }
529     }
530 }
531
532 /**
533  * g_bytes_equal:
534  * @bytes1: (type GLib.Bytes): a pointer to a #GBytes
535  * @bytes2: (type GLib.Bytes): a pointer to a #GBytes to compare with @bytes1
536  *
537  * Compares the two #GBytes values being pointed to and returns
538  * %TRUE if they are equal.
539  *
540  * This function can be passed to g_hash_table_new() as the @key_equal_func
541  * parameter, when using non-%NULL #GBytes pointers as keys in a #GHashTable.
542  *
543  * Returns: %TRUE if the two keys match.
544  *
545  * Since: 2.32
546  */
547 gboolean
548 g_bytes_equal (gconstpointer bytes1,
549                gconstpointer bytes2)
550 {
551   gconstpointer d1, d2;
552   gsize s1, s2;
553
554   g_return_val_if_fail (bytes1 != NULL, FALSE);
555   g_return_val_if_fail (bytes2 != NULL, FALSE);
556
557   d1 = g_bytes_get_data ((GBytes *) bytes1, &s1);
558   d2 = g_bytes_get_data ((GBytes *) bytes2, &s2);
559
560   if (s1 != s2)
561     return FALSE;
562
563   if (d1 == d2)
564     return TRUE;
565
566   return memcmp (d1, d2, s1) == 0;
567 }
568
569 /**
570  * g_bytes_hash:
571  * @bytes: (type GLib.Bytes): a pointer to a #GBytes key
572  *
573  * Creates an integer hash code for the byte data in the #GBytes.
574  *
575  * This function can be passed to g_hash_table_new() as the @key_hash_func
576  * parameter, when using non-%NULL #GBytes pointers as keys in a #GHashTable.
577  *
578  * Returns: a hash value corresponding to the key.
579  *
580  * Since: 2.32
581  */
582 guint
583 g_bytes_hash (gconstpointer bytes)
584 {
585   const guchar *data;
586   const guchar *end;
587   gsize size;
588   guint32 h = 5381;
589
590   g_return_val_if_fail (bytes != NULL, 0);
591
592   data = g_bytes_get_data ((GBytes *) bytes, &size);
593   end = data + size;
594
595   while (data != end)
596     h = (h << 5) + h + *(data++);
597
598   return h;
599 }
600
601 /**
602  * g_bytes_compare:
603  * @bytes1: (type GLib.Bytes): a pointer to a #GBytes
604  * @bytes2: (type GLib.Bytes): a pointer to a #GBytes to compare with @bytes1
605  *
606  * Compares the two #GBytes values.
607  *
608  * This function can be used to sort GBytes instances in lexographical order.
609  *
610  * Returns: a negative value if bytes2 is lesser, a positive value if bytes2 is
611  *          greater, and zero if bytes2 is equal to bytes1
612  *
613  * Since: 2.32
614  */
615 gint
616 g_bytes_compare (gconstpointer bytes1,
617                  gconstpointer bytes2)
618 {
619   gconstpointer d1, d2;
620   gsize s1, s2;
621   gint ret;
622
623   g_return_val_if_fail (bytes1 != NULL, 0);
624   g_return_val_if_fail (bytes2 != NULL, 0);
625
626   d1 = g_bytes_get_data ((GBytes *) bytes1, &s1);
627   d2 = g_bytes_get_data ((GBytes *) bytes2, &s2);
628
629   ret = memcmp (d1, d2, MIN (s1, s2));
630   if (ret == 0 && s1 != s2)
631     ret = s1 < s2 ? -1 : 1;
632
633   return ret;
634 }
635
636 /**
637  * g_bytes_unref_to_data:
638  * @bytes: (transfer full): a #GBytes
639  * @size: location to place the length of the returned data
640  *
641  * Unreferences the bytes, and returns a pointer the same byte data
642  * contents.
643  *
644  * As an optimization, the byte data is returned without copying if this was
645  * the last reference to bytes and bytes was created with g_bytes_new(),
646  * g_bytes_new_take() or g_byte_array_free_to_bytes(). In all other cases the
647  * data is copied.
648  *
649  * Returns: (transfer full): a pointer to the same byte data, which should
650  *          be freed with g_free()
651  *
652  * Since: 2.32
653  */
654 gpointer
655 g_bytes_unref_to_data (GBytes *bytes,
656                        gsize  *size)
657 {
658   gpointer result;
659
660   g_return_val_if_fail (bytes != NULL, NULL);
661   g_return_val_if_fail (size != NULL, NULL);
662
663
664   /*
665    * Optimal path: if this is was the last reference, then we can return
666    * the data from this GBytes without copying.
667    */
668   if (G_BYTES_IS_FREE(bytes) && g_atomic_int_get (&bytes->ref_count) == 1)
669     {
670       GBytesData *data_bytes = (GBytesData *) bytes;
671
672       result = data_bytes->data;
673       *size = bytes->size;
674
675       g_slice_free (GBytesData, data_bytes);
676     }
677   else
678     {
679       gconstpointer data;
680
681       data = g_bytes_get_data (bytes, size);
682       result = g_memdup (data, *size);
683       g_bytes_unref (bytes);
684     }
685
686   return result;
687 }
688
689 /**
690  * g_bytes_unref_to_array:
691  * @bytes: (transfer full): a #GBytes
692  *
693  * Unreferences the bytes, and returns a new mutable #GByteArray containing
694  * the same byte data.
695  *
696  * As an optimization, the byte data is transferred to the array without copying
697  * if this was the last reference to bytes and bytes was created with
698  * g_bytes_new(), g_bytes_new_take() or g_byte_array_free_to_bytes(). In all
699  * other cases the data is copied.
700  *
701  * Returns: (transfer full): a new mutable #GByteArray containing the same byte data
702  *
703  * Since: 2.32
704  */
705 GByteArray *
706 g_bytes_unref_to_array (GBytes *bytes)
707 {
708   gpointer data;
709   gsize size;
710
711   g_return_val_if_fail (bytes != NULL, NULL);
712
713   data = g_bytes_unref_to_data (bytes, &size);
714   return g_byte_array_new_take (data, size);
715 }