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