remove #include <glib.h> from some .c files
[platform/upstream/glib.git] / glib / gvarianttypeinfo.c
1 /*
2  * Copyright © 2008 Ryan Lortie
3  * Copyright © 2010 Codethink Limited
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 License, 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, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: Ryan Lortie <desrt@desrt.ca>
21  */
22
23 #include "gvarianttypeinfo.h"
24
25 #include <glib/gtestutils.h>
26 #include <glib/gthread.h>
27 #include <glib/ghash.h>
28
29 #include "galias.h"
30
31 /* < private >
32  * GVariantTypeInfo:
33  *
34  * This structure contains the necessary information to facilitate the
35  * serialisation and fast deserialisation of a given type of GVariant
36  * value.  A GVariant instance holds a pointer to one of these
37  * structures to provide for efficient operation.
38  *
39  * The GVariantTypeInfo structures for all of the base types, plus the
40  * "variant" type are stored in a read-only static array.
41  *
42  * For container types, a hash table and reference counting is used to
43  * ensure that only one of these structures exists for any given type.
44  * In general, a container GVariantTypeInfo will exist for a given type
45  * only if one or more GVariant instances of that type exist or if
46  * another GVariantTypeInfo has that type as a subtype.  For example, if
47  * a process contains a single GVariant instance with type "(asv)", then
48  * container GVariantTypeInfo structures will exist for "(asv)" and
49  * for "as" (note that "s" and "v" always exist in the static array).
50  *
51  * The trickiest part of GVariantTypeInfo (and in fact, the major reason
52  * for its existance) is the storage of somewhat magical constants that
53  * allow for O(1) lookups of items in tuples.  This is described below.
54  *
55  * 'container_class' is set to 'a' or 'r' if the GVariantTypeInfo is
56  * contained inside of an ArrayInfo or TupleInfo, respectively.  This
57  * allows the storage of the necessary additional information.
58  *
59  * 'fixed_size' is set to the fixed size of the type, if applicable, or
60  * 0 otherwise (since no type has a fixed size of 0).
61  *
62  * 'alignment' is set to one less than the alignment requirement for
63  * this type.  This makes many operations much more convenient.
64  */
65 struct _GVariantTypeInfo
66 {
67   gsize fixed_size;
68   guchar alignment;
69   guchar container_class;
70 };
71
72 /* Container types are reference counted.  They also need to have their
73  * type string stored explicitly since it is not merely a single letter.
74  */
75 typedef struct
76 {
77   GVariantTypeInfo info;
78
79   gchar *type_string;
80   gint ref_count;
81 } ContainerInfo;
82
83 /* For 'array' and 'maybe' types, we store some extra information on the
84  * end of the GVariantTypeInfo struct -- the element type (ie: "s" for
85  * "as").  The container GVariantTypeInfo structure holds a reference to
86  * the element typeinfo.
87  */
88 typedef struct
89 {
90   ContainerInfo container;
91
92   GVariantTypeInfo *element;
93 } ArrayInfo;
94
95 /* For 'tuple' and 'dict entry' types, we store extra information for
96  * each member -- its type and how to find it inside the serialised data
97  * in O(1) time using 4 variables -- 'i', 'a', 'b', and 'c'.  See the
98  * comment on GVariantMemberInfo in gvarianttypeinfo.h.
99  */
100 typedef struct
101 {
102   ContainerInfo container;
103
104   GVariantMemberInfo *members;
105   gsize n_members;
106 } TupleInfo;
107
108
109 /* Hard-code the base types in a constant array */
110 static const GVariantTypeInfo g_variant_type_info_basic_table[24] = {
111 #define fixed_aligned(x)  x, x - 1
112 #define unaligned         0, 0
113 #define aligned(x)        0, x - 1
114   /* 'b' */ { fixed_aligned(1) },   /* boolean */
115   /* 'c' */ { },
116   /* 'd' */ { fixed_aligned(8) },   /* double */
117   /* 'e' */ { },
118   /* 'f' */ { },
119   /* 'g' */ { unaligned        },   /* signature string */
120   /* 'h' */ { fixed_aligned(4) },   /* file handle (int32) */
121   /* 'i' */ { fixed_aligned(4) },   /* int32 */
122   /* 'j' */ { },
123   /* 'k' */ { },
124   /* 'l' */ { },
125   /* 'm' */ { },
126   /* 'n' */ { fixed_aligned(2) },   /* int16 */
127   /* 'o' */ { unaligned        },   /* object path string */
128   /* 'p' */ { },
129   /* 'q' */ { fixed_aligned(2) },   /* uint16 */
130   /* 'r' */ { },
131   /* 's' */ { unaligned        },   /* string */
132   /* 't' */ { fixed_aligned(8) },   /* uint64 */
133   /* 'u' */ { fixed_aligned(4) },   /* uint32 */
134   /* 'v' */ { aligned(8)       },   /* variant */
135   /* 'w' */ { },
136   /* 'x' */ { fixed_aligned(8) },   /* int64 */
137   /* 'y' */ { fixed_aligned(1) },   /* byte */
138 #undef fixed_aligned
139 #undef unaligned
140 #undef aligned
141 };
142
143 /* We need to have type strings to return for the base types.  We store
144  * those in another array.  Since all base type strings are single
145  * characters this is easy.  By not storing pointers to strings into the
146  * GVariantTypeInfo itself, we save a bunch of relocations.
147  */
148 static const char g_variant_type_info_basic_chars[24][2] = {
149   "b", " ", "d", " ", " ", "g", "h", "i", " ", " ", " ", " ",
150   "n", "o", " ", "q", " ", "s", "t", "u", "v", " ", "x", "y"
151 };
152
153 /* sanity checks to make debugging easier */
154 static void
155 g_variant_type_info_check (const GVariantTypeInfo *info,
156                            char                    container_class)
157 {
158   g_assert (!container_class || info->container_class == container_class);
159
160   /* alignment can only be one of these */
161   g_assert (info->alignment == 0 || info->alignment == 1 ||
162             info->alignment == 3 || info->alignment == 7);
163
164   if (info->container_class)
165     {
166       ContainerInfo *container = (ContainerInfo *) info;
167
168       /* extra checks for containers */
169       g_assert_cmpint (container->ref_count, >, 0);
170       g_assert (container->type_string != NULL);
171     }
172   else
173     {
174       gint index;
175
176       /* if not a container, then ensure that it is a valid member of
177        * the basic types table
178        */
179       index = info - g_variant_type_info_basic_table;
180
181       g_assert (G_N_ELEMENTS (g_variant_type_info_basic_table) == 24);
182       g_assert (G_N_ELEMENTS (g_variant_type_info_basic_chars) == 24);
183       g_assert (0 <= index && index < 24);
184       g_assert (g_variant_type_info_basic_chars[index][0] != ' ');
185     }
186 }
187
188 /* < private >
189  * g_variant_type_info_get_type_string:
190  * @info: a #GVariantTypeInfo
191  *
192  * Gets the type string for @info.  The string is nul-terminated.
193  */
194 const gchar *
195 g_variant_type_info_get_type_string (GVariantTypeInfo *info)
196 {
197   g_variant_type_info_check (info, 0);
198
199   if (info->container_class)
200     {
201       ContainerInfo *container = (ContainerInfo *) info;
202
203       /* containers have their type string stored inside them */
204       return container->type_string;
205     }
206   else
207     {
208       gint index;
209
210       /* look up the type string in the base type array.  the call to
211        * g_variant_type_info_check() above already ensured validity.
212        */
213       index = info - g_variant_type_info_basic_table;
214
215       return g_variant_type_info_basic_chars[index];
216     }
217 }
218
219 /* < private >
220  * g_variant_type_info_query:
221  * @info: a #GVariantTypeInfo
222  * @alignment: the location to store the alignment, or %NULL
223  * @fixed_size: the location to store the fixed size, or %NULL
224  *
225  * Queries @info to determine the alignment requirements and fixed size
226  * (if any) of the type.
227  *
228  * @fixed_size, if non-%NULL is set to the fixed size of the type, or 0
229  * to indicate that the type is a variable-sized type.  No type has a
230  * fixed size of 0.
231  *
232  * @alignment, if non-%NULL, is set to one less than the required
233  * alignment of the type.  For example, for a 32bit integer, @alignment
234  * would be set to 3.  This allows you to round an integer up to the
235  * proper alignment by performing the following efficient calculation:
236  *
237  *   offset += ((-offset) & alignment);
238  */
239 void
240 g_variant_type_info_query (GVariantTypeInfo *info,
241                            guint            *alignment,
242                            gsize            *fixed_size)
243 {
244   g_variant_type_info_check (info, 0);
245
246   if (alignment)
247     *alignment = info->alignment;
248
249   if (fixed_size)
250     *fixed_size = info->fixed_size;
251 }
252
253 /* == array == */
254 #define ARRAY_INFO_CLASS 'a'
255 static ArrayInfo *
256 ARRAY_INFO (GVariantTypeInfo *info)
257 {
258   g_variant_type_info_check (info, ARRAY_INFO_CLASS);
259
260   return (ArrayInfo *) info;
261 }
262
263 static void
264 array_info_free (GVariantTypeInfo *info)
265 {
266   ArrayInfo *array_info;
267
268   g_assert (info->container_class == ARRAY_INFO_CLASS);
269   array_info = (ArrayInfo *) info;
270
271   g_variant_type_info_unref (array_info->element);
272   g_slice_free (ArrayInfo, array_info);
273 }
274
275 static ContainerInfo *
276 array_info_new (const GVariantType *type)
277 {
278   ArrayInfo *info;
279
280   info = g_slice_new (ArrayInfo);
281   info->container.info.container_class = ARRAY_INFO_CLASS;
282
283   info->element = g_variant_type_info_get (g_variant_type_element (type));
284   info->container.info.alignment = info->element->alignment;
285   info->container.info.fixed_size = 0;
286
287   return (ContainerInfo *) info;
288 }
289
290 /* < private >
291  * g_variant_type_info_element:
292  * @info: a #GVariantTypeInfo for an array or maybe type
293  *
294  * Returns the element type for the array or maybe type.  A reference is
295  * not added, so the caller must add their own.
296  */
297 GVariantTypeInfo *
298 g_variant_type_info_element (GVariantTypeInfo *info)
299 {
300   return ARRAY_INFO (info)->element;
301 }
302
303 /* < private >
304  * g_variant_type_query_element:
305  * @info: a #GVariantTypeInfo for an array or maybe type
306  * @alignment: the location to store the alignment, or %NULL
307  * @fixed_size: the location to store the fixed size, or %NULL
308  *
309  * Returns the alignment requires and fixed size (if any) for the
310  * element type of the array.  This call is a convenience wrapper around
311  * g_variant_type_info_element() and g_variant_type_info_query().
312  */
313 void
314 g_variant_type_info_query_element (GVariantTypeInfo *info,
315                                    guint            *alignment,
316                                    gsize            *fixed_size)
317 {
318   g_variant_type_info_query (ARRAY_INFO (info)->element,
319                              alignment, fixed_size);
320 }
321
322 /* == tuple == */
323 #define TUPLE_INFO_CLASS 'r'
324 static TupleInfo *
325 TUPLE_INFO (GVariantTypeInfo *info)
326 {
327   g_variant_type_info_check (info, TUPLE_INFO_CLASS);
328
329   return (TupleInfo *) info;
330 }
331
332 static void
333 tuple_info_free (GVariantTypeInfo *info)
334 {
335   TupleInfo *tuple_info;
336   gint i;
337
338   g_assert (info->container_class == TUPLE_INFO_CLASS);
339   tuple_info = (TupleInfo *) info;
340
341   for (i = 0; i < tuple_info->n_members; i++)
342     g_variant_type_info_unref (tuple_info->members[i].type_info);
343
344   g_slice_free1 (sizeof (GVariantMemberInfo) * tuple_info->n_members,
345                  tuple_info->members);
346   g_slice_free (TupleInfo, tuple_info);
347 }
348
349 static void
350 tuple_allocate_members (const GVariantType  *type,
351                         GVariantMemberInfo **members,
352                         gsize               *n_members)
353 {
354   const GVariantType *item_type;
355   gsize i = 0;
356
357   *n_members = g_variant_type_n_items (type);
358   *members = g_slice_alloc (sizeof (GVariantMemberInfo) * *n_members);
359
360   item_type = g_variant_type_first (type);
361   while (item_type)
362     {
363       GVariantMemberInfo *member = &(*members)[i++];
364
365       member->type_info = g_variant_type_info_get (item_type);
366       item_type = g_variant_type_next (item_type);
367
368       if (member->type_info->fixed_size)
369         member->ending_type = G_VARIANT_MEMBER_ENDING_FIXED;
370       else if (item_type == NULL)
371         member->ending_type = G_VARIANT_MEMBER_ENDING_LAST;
372       else
373         member->ending_type = G_VARIANT_MEMBER_ENDING_OFFSET;
374     }
375
376   g_assert (i == *n_members);
377 }
378
379 /* this is g_variant_type_info_query for a given member of the tuple.
380  * before the access is done, it is ensured that the item is within
381  * range and %FALSE is returned if not.
382  */
383 static gboolean
384 tuple_get_item (TupleInfo          *info,
385                 GVariantMemberInfo *item,
386                 gsize              *d,
387                 gsize              *e)
388 {
389   if (&info->members[info->n_members] == item)
390     return FALSE;
391
392   *d = item->type_info->alignment;
393   *e = item->type_info->fixed_size;
394   return TRUE;
395 }
396
397 /* Read the documentation for #GVariantMemberInfo in gvarianttype.h
398  * before attempting to understand this.
399  *
400  * This function adds one set of "magic constant" values (for one item
401  * in the tuple) to the table.
402  *
403  * The algorithm in tuple_generate_table() calculates values of 'a', 'b'
404  * and 'c' for each item, such that the procedure for finding the item
405  * is to start at the end of the previous variable-sized item, add 'a',
406  * then round up to the nearest multiple of 'b', then then add 'c'.
407  * Note that 'b' is stored in the usual "one less than" form.  ie:
408  *
409  *   start = ROUND_UP(prev_end + a, (b + 1)) + c;
410  *
411  * We tweak these values a little to allow for a slightly easier
412  * computation and more compact storage.
413  */
414 static void
415 tuple_table_append (GVariantMemberInfo **items,
416                     gsize                i,
417                     gsize                a,
418                     gsize                b,
419                     gsize                c)
420 {
421   GVariantMemberInfo *item = (*items)++;
422
423   /* We can shift multiples of the alignment size from 'c' into 'a'.
424    * As long as we're shifting whole multiples, it won't affect the
425    * result.  This means that we can take the "aligned" portion off of
426    * 'c' and add it into 'a'.
427    *
428    *  Imagine (for sake of clarity) that ROUND_10 rounds up to the
429    *  nearest 10.  It is clear that:
430    *
431    *   ROUND_10(a) + c == ROUND_10(a + 10*(c / 10)) + (c % 10)
432    *
433    * ie: remove the 10s portion of 'c' and add it onto 'a'.
434    *
435    * To put some numbers on it, imagine we start with a = 34 and c = 27:
436    *
437    *  ROUND_10(34) + 27 = 40 + 27 = 67
438    *
439    * but also, we can split 27 up into 20 and 7 and do this:
440    *
441    *  ROUND_10(34 + 20) + 7 = ROUND_10(54) + 7 = 60 + 7 = 67
442    *                ^^    ^
443    * without affecting the result.  We do that here.
444    *
445    * This reduction in the size of 'c' means that we can store it in a
446    * gchar instead of a gsize.  Due to how the structure is packed, this
447    * ends up saving us 'two pointer sizes' per item in each tuple when
448    * allocating using GSlice.
449    */
450   a += ~b & c;    /* take the "aligned" part of 'c' and add to 'a' */
451   c &= b;         /* chop 'c' to contain only the unaligned part */
452
453
454   /* Finally, we made one last adjustment.  Recall:
455    *
456    *   start = ROUND_UP(prev_end + a, (b + 1)) + c;
457    *
458    * Forgetting the '+ c' for the moment:
459    *
460    *   ROUND_UP(prev_end + a, (b + 1));
461    *
462    * we can do a "round up" operation by adding 1 less than the amount
463    * to round up to, then rounding down.  ie:
464    *
465    *   #define ROUND_UP(x, y)    ROUND_DOWN(x + (y-1), y)
466    *
467    * Of course, for rounding down to a power of two, we can just mask
468    * out the appropriate number of low order bits:
469    *
470    *   #define ROUND_DOWN(x, y)  (x & ~(y - 1))
471    *
472    * Which gives us
473    *
474    *   #define ROUND_UP(x, y)    (x + (y - 1) & ~(y - 1))
475    *
476    * but recall that our alignment value 'b' is already "one less".
477    * This means that to round 'prev_end + a' up to 'b' we can just do:
478    *
479    *   ((prev_end + a) + b) & ~b
480    *
481    * Associativity, and putting the 'c' back on:
482    *
483    *   (prev_end + (a + b)) & ~b + c
484    *
485    * Now, since (a + b) is constant, we can just add 'b' to 'a' now and
486    * store that as the number to add to prev_end.  Then we use ~b as the
487    * number to take a bitwise 'and' with.  Finally, 'c' is added on.
488    *
489    * Note, however, that all the low order bits of the 'aligned' value
490    * are masked out and that all of the high order bits of 'c' have been
491    * "moved" to 'a' (in the previous step).  This means that there are
492    * no overlapping bits in the addition -- so we can do a bitwise 'or'
493    * equivalently.
494    *
495    * This means that we can now compute the start address of a given
496    * item in the tuple using the algorithm given in the documentation
497    * for #GVariantMemberInfo:
498    *
499    *   item_start = ((prev_end + a) & b) | c;
500    */
501
502   item->i = i;
503   item->a = a + b;
504   item->b = ~b;
505   item->c = c;
506 }
507
508 static gsize
509 tuple_align (gsize offset,
510              guint alignment)
511 {
512   return offset + ((-offset) & alignment);
513 }
514
515 /* This function is the heart of the algorithm for calculating 'i', 'a',
516  * 'b' and 'c' for each item in the tuple.
517  *
518  * Imagine we want to find the start of the "i" in the type "(su(qx)ni)".
519  * That's a string followed by a uint32, then a tuple containing a
520  * uint16 and a int64, then an int16, then our "i".  In order to get to
521  * our "i" we:
522  *
523  * Start at the end of the string, align to 4 (for the uint32), add 4.
524  * Align to 8, add 16 (for the tuple).  Align to 2, add 2 (for the
525  * int16).  Then we're there.  It turns out that, given 3 simple rules,
526  * we can flatten this iteration into one addition, one alignment, then
527  * one more addition.
528  *
529  * The loop below plays through each item in the tuple, querying its
530  * alignment and fixed_size into 'd' and 'e', respectively.  At all
531  * times the variables 'a', 'b', and 'c' are maintained such that in
532  * order to get to the current point, you add 'a', align to 'b' then add
533  * 'c'.  'b' is kept in "one less than" form.  For each item, the proper
534  * alignment is applied to find the values of 'a', 'b' and 'c' to get to
535  * the start of that item.  Those values are recorded into the table.
536  * The fixed size of the item (if applicable) is then added on.
537  *
538  * These 3 rules are how 'a', 'b' and 'c' are modified for alignment and
539  * addition of fixed size.  They have been proven correct but are
540  * presented here, without proof:
541  *
542  *  1) in order to "align to 'd'" where 'd' is less than or equal to the
543  *     largest level of alignment seen so far ('b'), you align 'c' to
544  *     'd'.
545  *  2) in order to "align to 'd'" where 'd' is greater than the largest
546  *     level of alignment seen so far, you add 'c' aligned to 'b' to the
547  *     value of 'a', set 'b' to 'd' (ie: increase the 'largest alignment
548  *     seen') and reset 'c' to 0.
549  *  3) in order to "add 'e'", just add 'e' to 'c'.
550  */
551 static void
552 tuple_generate_table (TupleInfo *info)
553 {
554   GVariantMemberInfo *items = info->members;
555   gsize i = -1, a = 0, b = 0, c = 0, d, e;
556
557   /* iterate over each item in the tuple.
558    *   'd' will be the alignment of the item (in one-less form)
559    *   'e' will be the fixed size (or 0 for variable-size items)
560    */
561   while (tuple_get_item (info, items, &d, &e))
562     {
563       /* align to 'd' */
564       if (d <= b)
565         c = tuple_align (c, d);                   /* rule 1 */
566       else
567         a += tuple_align (c, b), b = d, c = 0;    /* rule 2 */
568
569       /* the start of the item is at this point (ie: right after we
570        * have aligned for it).  store this information in the table.
571        */
572       tuple_table_append (&items, i, a, b, c);
573
574       /* "move past" the item by adding in its size. */
575       if (e == 0)
576         /* variable size:
577          *
578          * we'll have an offset stored to mark the end of this item, so
579          * just bump the offset index to give us a new starting point
580          * and reset all the counters.
581          */
582         i++, a = b = c = 0;
583       else
584         /* fixed size */
585         c += e;                                   /* rule 3 */
586     }
587 }
588
589 static void
590 tuple_set_base_info (TupleInfo *info)
591 {
592   GVariantTypeInfo *base = &info->container.info;
593
594   if (info->n_members > 0)
595     {
596       GVariantMemberInfo *m;
597
598       /* the alignment requirement of the tuple is the alignment
599        * requirement of its largest item.
600        */
601       base->alignment = 0;
602       for (m = info->members; m < &info->members[info->n_members]; m++)
603         /* can find the max of a list of "one less than" powers of two
604          * by 'or'ing them
605          */
606         base->alignment |= m->type_info->alignment;
607
608       m--; /* take 'm' back to the last item */
609
610       /* the structure only has a fixed size if no variable-size
611        * offsets are stored and the last item is fixed-sized too (since
612        * an offset is never stored for the last item).
613        */
614       if (m->i == -1 && m->type_info->fixed_size)
615         /* in that case, the fixed size can be found by finding the
616          * start of the last item (in the usual way) and adding its
617          * fixed size.
618          *
619          * if a tuple has a fixed size then it is always a multiple of
620          * the alignment requirement (to make packing into arrays
621          * easier) so we round up to that here.
622          */
623         base->fixed_size =
624           tuple_align (((m->a & m->b) | m->c) + m->type_info->fixed_size,
625                        base->alignment);
626       else
627         /* else, the tuple is not fixed size */
628         base->fixed_size = 0;
629     }
630   else
631     {
632       /* the empty tuple: '()'.
633        *
634        * has a size of 1 and an no alignment requirement.
635        *
636        * It has a size of 1 (not 0) for two practical reasons:
637        *
638        *  1) So we can determine how many of them are in an array
639        *     without dividing by zero or without other tricks.
640        *
641        *  2) Even if we had some trick to know the number of items in
642        *     the array (as GVariant did at one time) this would open a
643        *     potential denial of service attack: an attacker could send
644        *     you an extremely small array (in terms of number of bytes)
645        *     containing trillions of zero-sized items.  If you iterated
646        *     over this array you would effectively infinite-loop your
647        *     program.  By forcing a size of at least one, we bound the
648        *     amount of computation done in response to a message to a
649        *     reasonable function of the size of that message.
650        */
651       base->alignment = 0;
652       base->fixed_size = 1;
653     }
654 }
655
656 static ContainerInfo *
657 tuple_info_new (const GVariantType *type)
658 {
659   TupleInfo *info;
660
661   info = g_slice_new (TupleInfo);
662   info->container.info.container_class = TUPLE_INFO_CLASS;
663
664   tuple_allocate_members (type, &info->members, &info->n_members);
665   tuple_generate_table (info);
666   tuple_set_base_info (info);
667
668   return (ContainerInfo *) info;
669 }
670
671 /* < private >
672  * g_variant_type_info_n_members:
673  * @info: a #GVariantTypeInfo for a tuple or dictionary entry type
674  *
675  * Returns the number of members in a tuple or dictionary entry type.
676  * For a dictionary entry this will always be 2.
677  */
678 gsize
679 g_variant_type_info_n_members (GVariantTypeInfo *info)
680 {
681   return TUPLE_INFO (info)->n_members;
682 }
683
684 /* < private >
685  * g_variant_type_info_member_info:
686  * @info: a #GVariantTypeInfo for a tuple or dictionary entry type
687  * @index: the member to fetch information for
688  *
689  * Returns the #GVariantMemberInfo for a given member.  See
690  * documentation for that structure for why you would want this
691  * information.
692  *
693  * @index must refer to a valid child (ie: strictly less than
694  * g_variant_type_info_n_members() returns).
695  */
696 const GVariantMemberInfo *
697 g_variant_type_info_member_info (GVariantTypeInfo *info,
698                                  gsize             index)
699 {
700   TupleInfo *tuple_info = TUPLE_INFO (info);
701
702   if (index < tuple_info->n_members)
703     return &tuple_info->members[index];
704
705   return NULL;
706 }
707
708 /* == new/ref/unref == */
709 static GStaticRecMutex g_variant_type_info_lock = G_STATIC_REC_MUTEX_INIT;
710 static GHashTable *g_variant_type_info_table;
711
712 /* < private >
713  * g_variant_type_info_get:
714  * @type: a #GVariantType
715  *
716  * Returns a reference to a #GVariantTypeInfo for @type.
717  *
718  * If an info structure already exists for this type, a new reference is
719  * returned.  If not, the required calculations are performed and a new
720  * info structure is returned.
721  *
722  * It is appropriate to call g_variant_type_info_unref() on the return
723  * value.
724  */
725 GVariantTypeInfo *
726 g_variant_type_info_get (const GVariantType *type)
727 {
728   char type_char;
729
730   type_char = g_variant_type_peek_string (type)[0];
731
732   if (type_char == G_VARIANT_TYPE_INFO_CHAR_MAYBE ||
733       type_char == G_VARIANT_TYPE_INFO_CHAR_ARRAY ||
734       type_char == G_VARIANT_TYPE_INFO_CHAR_TUPLE ||
735       type_char == G_VARIANT_TYPE_INFO_CHAR_DICT_ENTRY)
736     {
737       GVariantTypeInfo *info;
738       gchar *type_string;
739
740       if G_UNLIKELY (g_variant_type_info_table == NULL)
741         g_variant_type_info_table = g_hash_table_new (g_str_hash,
742                                                       g_str_equal);
743
744       type_string = g_variant_type_dup_string (type);
745
746       g_static_rec_mutex_lock (&g_variant_type_info_lock);
747       info = g_hash_table_lookup (g_variant_type_info_table, type_string);
748
749       if (info == NULL)
750         {
751           ContainerInfo *container;
752
753           if (type_char == G_VARIANT_TYPE_INFO_CHAR_MAYBE ||
754               type_char == G_VARIANT_TYPE_INFO_CHAR_ARRAY)
755             {
756               container = array_info_new (type);
757             }
758           else /* tuple or dict entry */
759             {
760               container = tuple_info_new (type);
761             }
762
763           info = (GVariantTypeInfo *) container;
764           container->type_string = type_string;
765           container->ref_count = 1;
766
767           g_hash_table_insert (g_variant_type_info_table, type_string, info);
768           type_string = NULL;
769         }
770       else
771         g_variant_type_info_ref (info);
772
773       g_static_rec_mutex_unlock (&g_variant_type_info_lock);
774       g_variant_type_info_check (info, 0);
775       g_free (type_string);
776
777       return info;
778     }
779   else
780     {
781       const GVariantTypeInfo *info;
782       int index;
783
784       index = type_char - 'b';
785       g_assert (G_N_ELEMENTS (g_variant_type_info_basic_table) == 24);
786       g_assert_cmpint (0, <=, index);
787       g_assert_cmpint (index, <, 24);
788
789       info = g_variant_type_info_basic_table + index;
790       g_variant_type_info_check (info, 0);
791
792       return (GVariantTypeInfo *) info;
793     }
794 }
795
796 /* < private >
797  * g_variant_type_info_ref:
798  * @info: a #GVariantTypeInfo
799  *
800  * Adds a reference to @info.
801  */
802 GVariantTypeInfo *
803 g_variant_type_info_ref (GVariantTypeInfo *info)
804 {
805   g_variant_type_info_check (info, 0);
806
807   if (info->container_class)
808     {
809       ContainerInfo *container = (ContainerInfo *) info;
810
811       g_assert_cmpint (container->ref_count, >, 0);
812       g_atomic_int_inc (&container->ref_count);
813     }
814
815   return info;
816 }
817
818 /* < private >
819  * g_variant_type_info_unref:
820  * @info: a #GVariantTypeInfo
821  *
822  * Releases a reference held on @info.  This may result in @info being
823  * freed.
824  */
825 void
826 g_variant_type_info_unref (GVariantTypeInfo *info)
827 {
828   g_variant_type_info_check (info, 0);
829
830   if (info->container_class)
831     {
832       ContainerInfo *container = (ContainerInfo *) info;
833
834       if (g_atomic_int_dec_and_test (&container->ref_count))
835         {
836           g_static_rec_mutex_lock (&g_variant_type_info_lock);
837           g_hash_table_remove (g_variant_type_info_table,
838                                container->type_string);
839           if (g_hash_table_size (g_variant_type_info_table) == 0)
840             {
841               g_hash_table_unref (g_variant_type_info_table);
842               g_variant_type_info_table = NULL;
843             }
844           g_static_rec_mutex_unlock (&g_variant_type_info_lock);
845
846           g_free (container->type_string);
847
848           if (info->container_class == ARRAY_INFO_CLASS)
849             array_info_free (info);
850
851           else if (info->container_class == TUPLE_INFO_CLASS)
852             tuple_info_free (info);
853
854           else
855             g_assert_not_reached ();
856         }
857     }
858 }
859
860 /* used from the test cases */
861 #define assert_no_type_infos() \
862   g_assert (g_variant_type_info_table == NULL)