File: DKArgument.m

package info (click to toggle)
dbuskit 0.1.1-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch
  • size: 3,552 kB
  • sloc: objc: 10,309; sh: 9,443; ansic: 200; makefile: 20
file content (1995 lines) | stat: -rw-r--r-- 55,448 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
/** Implementation of DKArgument class for boxing and unboxing D-Bus types.
   Copyright (C) 2010 Free Software Foundation, Inc.

   Written by:  Niels Grewe <niels.grewe@halbordnung.de>
   Created: June 2010

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free
   Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02111 USA.

   <title>DKArgument class reference</title>
   */

#import <Foundation/NSArray.h>
#import <Foundation/NSDebug.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSException.h>
#import <Foundation/NSEnumerator.h>
#import <Foundation/NSHashTable.h>
#import <Foundation/NSInvocation.h>
#import <Foundation/NSLock.h>
#import <Foundation/NSMapTable.h>
#import <Foundation/NSMethodSignature.h>
#import <Foundation/NSNull.h>
#import <Foundation/NSString.h>
#import <Foundation/NSValue.h>
#import <GNUstepBase/NSDebug+GNUstepBase.h>

#import "DKProxy+Private.h"
#import "DKEndpoint.h"
#import "DKObjectPathNode.h"
#import "DKOutgoingProxy.h"
#import "DKArgument.h"

#define INCLUDE_RUNTIME_H
#include "config.h"
#undef INCLUDE_RUNTIME_H

#include <string.h>
#include <dbus/dbus.h>

NSString *kDKArgumentDirectionIn = @"in";
NSString *kDKArgumentDirectionOut = @"out";


/*
 * Macros to call D-Bus function and check whether they returned OOM:
 */

#define DK_MARSHALLING_RAISE_OOM [NSException raise: @"DKArgumentMarshallingException"\
                                             format: @"Out of memory when marshalling argument."]

#define DK_ITER_APPEND(iter, type, addr) do {\
  if (NO == (BOOL)dbus_message_iter_append_basic(iter, type, (void*)addr))\
  {\
    DK_MARSHALLING_RAISE_OOM; \
  }\
}  while (0)

#define DK_ITER_OPEN_CONTAINER(iter, type, sig, subIter) do {\
  if (NO == (BOOL)dbus_message_iter_open_container(iter, type, sig, subIter))\
  {\
    DK_MARSHALLING_RAISE_OOM; \
  }\
} while (0)

#define DK_ITER_CLOSE_CONTAINER(iter, subIter) do {\
  if (NO == (BOOL)dbus_message_iter_close_container(iter, subIter))\
  {\
    DK_MARSHALLING_RAISE_OOM; \
  }\
} while (0)

static Class
DKObjCClassForDBusType(int type)
{
  switch (type)
  {
    case DBUS_TYPE_BYTE:
    case DBUS_TYPE_BOOLEAN:
    case DBUS_TYPE_INT16:
    case DBUS_TYPE_UINT16:
    case DBUS_TYPE_INT32:
    case DBUS_TYPE_UINT32:
    case DBUS_TYPE_INT64:
    case DBUS_TYPE_UINT64:
    case DBUS_TYPE_DOUBLE:
      return [NSNumber class];
    case DBUS_TYPE_STRING:
      return [NSString class];
    case DBUS_TYPE_OBJECT_PATH:
      return [DKProxy class];
    case DBUS_TYPE_SIGNATURE:
      return [DKArgument class];
    // Some DBUS_TYPE_ARRAYs will actually be dictionaries if they contain
    // DBUS_TYPE_DICT_ENTRies.
    case DBUS_TYPE_ARRAY:
    case DBUS_TYPE_STRUCT:
      return [NSArray class];
    // The following types have no explicit representation, they will either not
    // be handled at all, or their boxing is determined by the container resp.
    // the contained type.
    case DBUS_TYPE_INVALID:
    case DBUS_TYPE_VARIANT:
    case DBUS_TYPE_DICT_ENTRY:
    default:
      break;
  }
  return Nil;
}

/*
 * Conversion from Objective-C types to D-Bus types. NOTE: This is not meant to
 * be complete. It is just used to give some hints for the boxing of D-Bus
 * variant types. (NSValue responds to -objCType, so we can use the information
 * to construct a correctly typed DKArgument at least some of the time.)
 */
static int
DKDBusTypeForObjCType(const char* code)
{
  switch (*code)
  {
    case _C_BOOL:
      return DBUS_TYPE_BOOLEAN;
    case _C_CHR:
    case _C_SHT:
      return DBUS_TYPE_INT16;
    case _C_INT:
      return DBUS_TYPE_INT32;
    case _C_LNG_LNG:
      return DBUS_TYPE_INT64;
    case _C_UCHR:
      return DBUS_TYPE_BYTE;
    case _C_USHT:
      return DBUS_TYPE_UINT16;
    case _C_UINT:
      return DBUS_TYPE_UINT32;
    case _C_ULNG_LNG:
      return DBUS_TYPE_UINT64;
    case _C_FLT:
    case _C_DBL:
      return DBUS_TYPE_DOUBLE;
    case _C_CHARPTR:
      return DBUS_TYPE_STRING;
    case _C_ID:
      return DBUS_TYPE_VARIANT;
    case _C_ARY_B:
      return DBUS_TYPE_ARRAY;
    case _C_STRUCT_B:
      return DBUS_TYPE_STRUCT;
    default:
      return DBUS_TYPE_INVALID;
  }
  return DBUS_TYPE_INVALID;
}

/*
 * Map D-Bus types to corresponding Objective-C types. Assumes that complex
 * types are always boxed.
 */
static char*
DKUnboxedObjCTypeForDBusType(int type)
{
  switch (type)
  {
    case DBUS_TYPE_BYTE:
      return @encode(unsigned char);
    case DBUS_TYPE_BOOLEAN:
      return @encode(BOOL);
    case DBUS_TYPE_INT16:
      return @encode(int16_t);
    case DBUS_TYPE_UINT16:
      return @encode(uint16_t);
    case DBUS_TYPE_INT32:
      return @encode(int32_t);
    case DBUS_TYPE_UINT32:
      return @encode(uint32_t);
    case DBUS_TYPE_INT64:
      return @encode(int64_t);
    case DBUS_TYPE_UINT64:
      return @encode(uint64_t);
    case DBUS_TYPE_DOUBLE:
      return @encode(double);
    case DBUS_TYPE_STRING:
      return @encode(char*);
    // We always box the following types:
    case DBUS_TYPE_OBJECT_PATH:
    case DBUS_TYPE_ARRAY:
    case DBUS_TYPE_STRUCT:
    case DBUS_TYPE_VARIANT:
      return @encode(id);
    // And because we do, the following types will never appear in a signature:
    case DBUS_TYPE_INVALID:
    case DBUS_TYPE_SIGNATURE:
    case DBUS_TYPE_DICT_ENTRY:
    default:
      return '\0';
  }
  return '\0';
}
static size_t
DKUnboxedObjCTypeSizeForDBusType(int type)
{
  switch (type)
  {
    case DBUS_TYPE_BYTE:
      return sizeof(char);
    case DBUS_TYPE_BOOLEAN:
      return sizeof(BOOL);
    case DBUS_TYPE_INT16:
      return sizeof(int16_t);
    case DBUS_TYPE_UINT16:
      return sizeof(uint16_t);
    case DBUS_TYPE_INT32:
      return sizeof(int32_t);
    case DBUS_TYPE_UINT32:
      return sizeof(uint32_t);
    case DBUS_TYPE_INT64:
      return sizeof(int64_t);
    case DBUS_TYPE_UINT64:
      return sizeof(uint64_t);
    case DBUS_TYPE_DOUBLE:
      return sizeof(double);
    case DBUS_TYPE_STRING:
      return sizeof(char*);
    // We always box the following types:
    case DBUS_TYPE_OBJECT_PATH:
    case DBUS_TYPE_ARRAY:
    case DBUS_TYPE_STRUCT:
    case DBUS_TYPE_VARIANT:
      return sizeof(id);
    // And because we do, the following types will never appear in a signature:
    case DBUS_TYPE_INVALID:
    case DBUS_TYPE_SIGNATURE:
    case DBUS_TYPE_DICT_ENTRY:
    default:
      return 0;
  }
  return 0;
}

/*
 * Private Container argument subclasses:
 */

/**
 * Encapsulates containers that are structs.
 */
@interface DKStructTypeArgument: DKContainerTypeArgument
@end

/**
 * Encapsulates containers that are arrays.
 */
@interface DKArrayTypeArgument: DKContainerTypeArgument
/**
 * D-Bus considers dictionaries as arrays of dict-entries. (e.g. "a{si}" is an
 * a dictionary with string keys and integer values). You can use -isDictionary
 * to find out whether the array is a dictionary.
 */
- (BOOL) isDictionary;

/**
 * Called by DKDictEntryTypeArgument to turn an DKArrayTypeArgument into an
 * DKDictionaryTypeArgument.
 */
- (void) setIsDictionary: (BOOL)isDict;
@end

/**
 * Because D-Bus marshalls dictionaries as arrays of key/value pairs,
 * DKDictionaryTypeArgument is a subclass of DKArrayTypeArgument.
 */
@interface DKDictionaryTypeArgument: DKArrayTypeArgument
@end

/**
 * Encapsulates variant arguments.
 */
@interface DKVariantTypeArgument: DKContainerTypeArgument
/**
 * Returns an DKArgument instance that can be used to marshall/unmarshall
 * <var>object</var>.
 */
- (DKArgument*) DKArgumentWithObject: (id)object;
@end

/**
 * DKDIctEntryTypeArgument encapsulates dictionary entries, which don't really
 * appear on the Objective-C side of things. If you really want to do so, it
 * seems sensible to regard them as struct types.
 */
@interface DKDictEntryTypeArgument: DKStructTypeArgument
/**
 * Returns the argument type at key position. This is guranteed not to be a
 * container type.
 */
- (DKArgument*) keyArgument;

/**
 * Returns the argument type used for values.
 */
- (DKArgument*) valueArgument;

/**
 * Unmarshalls one key and value from <var>iter</var> and places them at the
 * addresses specified.
 */
- (void) unmarshallFromIterator: (DBusMessageIter*)iter
                          value: (id*)value
                            key: (id*)key;

/**
 * Marshalls <var>key</var> and <var>object</var> and appends them to
 * <var>iter</var>.
 */
- (void) marshallObject: (id)object
                 forKey: (id)key
           intoIterator: (DBusMessageIter*)iter;
@end


/*
 * Tables and paraphernalia for managing unboxing of objects: We want some
 * degree of flexibility on how to unbox objects of arbitrary types. To that
 * end, we define two tables:
 *
 * (1) selectorTypeMap, which maps selectors used to unbox objects to D-Bus
 *     types so that we can construct appropriate DKArguments if we encounter
 *     objects responding to the selector.
 *
 * (2) typeSelectorMap, which maps D-Bus types to hash-tables containing all
 *     selectors that can be used to obtain an unboxed value of a specified
 *     type.
 *
 * NOTE: Unfortunately, we cannot unbox container types this way.
 */
static NSMapTable *selectorTypeMap;
static NSMapTable *typeSelectorMap;
static NSLock *selectorTypeMapLock;


typedef struct
{
  SEL selector;
  int type;
} DKSelectorTypePair;


#define DK_INSTALL_TYPE_SELECTOR_PAIR(type,theSel) \
 do \
  {\
    SEL selector = theSel;\
    NSHashTable *selTable = NSCreateHashTable(NSIntHashCallBacks,\
     1); \
    NSMapInsert(selectorTypeMap,\
      (void*)selector,\
      (void*)(intptr_t)type);\
    NSMapInsert(typeSelectorMap,\
      (void*)(intptr_t)type,\
      (void*)selTable);\
    NSHashInsert(selTable,selector);\
  } while (0)


static inline void
DKInstallDefaultSelectorTypeMapping()
{
  [selectorTypeMapLock lock];
  DK_INSTALL_TYPE_SELECTOR_PAIR(DBUS_TYPE_STRING, @selector(UTF8String));
  DK_INSTALL_TYPE_SELECTOR_PAIR(DBUS_TYPE_INT64, @selector(longLongValue));
  DK_INSTALL_TYPE_SELECTOR_PAIR(DBUS_TYPE_UINT64, @selector(unsignedLongLongValue));
  DK_INSTALL_TYPE_SELECTOR_PAIR(DBUS_TYPE_INT32, @selector(intValue));
  DK_INSTALL_TYPE_SELECTOR_PAIR(DBUS_TYPE_UINT32, @selector(unsignedIntValue));
  DK_INSTALL_TYPE_SELECTOR_PAIR(DBUS_TYPE_INT16, @selector(shortValue));
  DK_INSTALL_TYPE_SELECTOR_PAIR(DBUS_TYPE_UINT16, @selector(unsignedShortValue));
  DK_INSTALL_TYPE_SELECTOR_PAIR(DBUS_TYPE_BYTE, @selector(unsignedCharValue));
  DK_INSTALL_TYPE_SELECTOR_PAIR(DBUS_TYPE_BOOLEAN, @selector(boolValue));
  DK_INSTALL_TYPE_SELECTOR_PAIR(DBUS_TYPE_DOUBLE, @selector(doubleValue));
  DK_INSTALL_TYPE_SELECTOR_PAIR(DBUS_TYPE_DOUBLE, @selector(floatValue));
  [selectorTypeMapLock unlock];
}

static inline void
DKRegisterSelectorTypePair(DKSelectorTypePair *pair)
{
  NSHashTable *selTable = nil;
  SEL selector = pair->selector;
  int type = pair->type;
  void* mapReturn = NULL;
  if (0 == selector)
  {
    return;
  }


  [selectorTypeMapLock lock];
  selTable = NSMapGet(typeSelectorMap, (void*)(intptr_t)type);

  if (!selTable)
  {
    [selectorTypeMapLock unlock];
    return;
  }

  mapReturn = NSMapInsertIfAbsent(selectorTypeMap,
    (void*)selector,
    (void*)(intptr_t)type);

  // InsertIfAbsent returns NULL if the key had been absent, which is the only
  // case where we also want to install the new type-selector mapping.
  if (NULL == mapReturn)
  {
    NSHashInsertIfAbsent(selTable, (void*)selector);
  }
  [selectorTypeMapLock unlock];
}


static SEL
DKSelectorForUnboxingObjectAsType(id object, int DBusType)
{
  SEL theSel = 0;
  NSHashTable *table = nil;
  NSHashEnumerator tableEnum;
  [selectorTypeMapLock lock];
  table = NSMapGet(typeSelectorMap, (void*)(intptr_t)DBusType);
  tableEnum = NSEnumerateHashTable(table);
  while (0 != (theSel = (SEL)NSNextHashEnumeratorItem(&tableEnum)))
  {
    if ([object respondsToSelector: theSel])
    {
      NSEndHashTableEnumeration(&tableEnum);
      [selectorTypeMapLock unlock];
      return theSel;
    }
  }
  NSEndHashTableEnumeration(&tableEnum);
  [selectorTypeMapLock unlock];
  return 0;
}

static int
DKDBusTypeForUnboxingObject(id object)
{
  int type = DBUS_TYPE_INVALID;
  // Fast case: The object implements objCType, so we can simply gather the
  // D-Bus type from the Obj-C type code.
  if ([object respondsToSelector: @selector(objCType)])
  {
    type = DKDBusTypeForObjCType([object objCType]);
  }

  /*
   * Special case: NSString. It responds to all kinds of crazy selectors,
   * converting the string to a numeric value.  So we default to returning the
   * string type for NSString.
   */
  if ([object isKindOfClass: [NSString class]])
  {
    return DBUS_TYPE_STRING;
  }

  // Slow case: We need to find a selector in the table and get the matching
  // type.
  if (DBUS_TYPE_INVALID == type)
  {
    SEL aSel = 0;
    NSMapEnumerator mapEnum;
    [selectorTypeMapLock lock];
    mapEnum = NSEnumerateMapTable(selectorTypeMap);
    while (NSNextMapEnumeratorPair(&mapEnum,
      (void**)&aSel,
      (void**)&type))
    {
      if (aSel != 0)
      {
	if ([object respondsToSelector: aSel])
	{
	  // The object responds to the selector. We need to make sure that we
	  // get a correctly sized return value by invoking the corresponding
	  // method.
	  NSMethodSignature *sig = [object methodSignatureForSelector: aSel];
	  if (type == DKDBusTypeForObjCType([sig methodReturnType]))
	  {
	    NSEndMapTableEnumeration(&mapEnum);
	    [selectorTypeMapLock unlock];
	    return type;
	  }
	}
      }
    }
    NSEndMapTableEnumeration(&mapEnum);
    [selectorTypeMapLock unlock];
  }
  return type;
}

/**
 *  DKArgument encapsulates D-Bus argument information
 */
@implementation DKArgument
+ (void) initialize
{
  if ([DKArgument class] != self)
  {
    return;
  }

  selectorTypeMap = NSCreateMapTable(NSIntMapKeyCallBacks,
    NSIntMapValueCallBacks,
    17); // We have 17 D-Bus types.
  typeSelectorMap = NSCreateMapTable(NSIntMapKeyCallBacks,
    NSObjectMapValueCallBacks,
    17); // We have 17 D-Bus types.


  selectorTypeMapLock = [NSLock new];
  DKInstallDefaultSelectorTypeMapping();

  /*
   * Take care that all subclasses are being initialized as well, so that we
   * don't get nasty suprises when multiple threads try to obtain the runtime's
   * +initialize lock.
   */

  [[[DKStructTypeArgument alloc] init] release];
  [[[DKArrayTypeArgument alloc] init] release];
  [[[DKDictionaryTypeArgument alloc] init] release];
  [[[DKVariantTypeArgument alloc] init] release];
  [[[DKDictEntryTypeArgument alloc] init] release];

}

+ (void)registerUnboxingSelector: (SEL)selector
                     forDBusType: (int)type
{

  DKSelectorTypePair pair = {selector, type};
  DKRegisterSelectorTypePair(&pair);
}

/**
 * Initializes the argument with the next single argument from
 * <var>iterator</var>. This method will not advance the iterator.
 */
- (id) initWithIterator: (DBusSignatureIter*)iterator
                   name: (NSString*)_name
                 parent: (id)_parent
{
  if (nil == (self = [super initWithName: _name
                                  parent: _parent]))
  {
    return nil;
  }

  DBusType = dbus_signature_iter_get_current_type(iterator);

  if ((dbus_type_is_container(DBusType))
    && (![self isKindOfClass: [DKContainerTypeArgument class]]))
  {
    NSDebugMLog(@"Incorrectly initalized a non-container argument with a container type, reinitializing as container type.");
    [self release];
    return [[DKContainerTypeArgument alloc] initWithIterator: iterator
                                                        name: _name
                                                      parent: _parent];
  }
  objCEquivalent = DKObjCClassForDBusType(DBusType);
  return self;
}

/* Public initializer, see publich header for documentation. */
- (id)initWithDBusSignature: (const char*)DBusTypeString
                       name: (NSString*)_name
                     parent: (id)_parent
{
  DBusSignatureIter myIter;
  if (!dbus_signature_validate_single(DBusTypeString, NULL))
  {
    NSWarnMLog(@"Not a single D-Bus type signature ('%s'), ignoring argument", DBusTypeString);
    [self release];
    return nil;
  }

  dbus_signature_iter_init(&myIter, DBusTypeString);
  return [self initWithIterator: &myIter
                           name: _name
                         parent: _parent];
}



- (void)setObjCEquivalent: (Class)class
{
  objCEquivalent = class;
}

- (Class) objCEquivalent
{
  return objCEquivalent;
}

- (void)setDBusType: (int)type
{
  DBusType = type;
}

- (int) DBusType
{
  return DBusType;
}

- (NSString*) DBusTypeSignature
{
  return [NSString stringWithCharacters: (unichar*)&DBusType length: 1];

}

- (const char*) unboxedObjCTypeChar
{
  return DKUnboxedObjCTypeForDBusType(DBusType);
}

- (size_t)unboxedObjCTypeSize
{
  return DKUnboxedObjCTypeSizeForDBusType(DBusType);
}
- (BOOL) isContainerType
{
  return NO;
}

- (id)copyWithZone: (NSZone*)zone
{
  DKArgument *newNode = [super copyWithZone: zone];
  [newNode setObjCEquivalent: objCEquivalent];
  [newNode setDBusType: DBusType];
  return newNode;
}


- (BOOL) unboxValue: (id)value
         intoBuffer: (long long*)buffer
{
  SEL aSelector = 0;
  switch (DBusType)
  {
    case DBUS_TYPE_BYTE:
       if (([value respondsToSelector: @selector(unsignedCharValue)])
         || (nil == value))
       {
	 *buffer = [value unsignedCharValue];
         return YES;
       }
       break;
    case DBUS_TYPE_BOOLEAN:
       if (([value respondsToSelector: @selector(boolValue)])
         || (nil == value))
       {
	 *buffer = [value boolValue];
	 return YES;
       }
       break;
    case DBUS_TYPE_INT16:
       if (([value respondsToSelector: @selector(shortValue)])
         || (nil == value))
       {
	 *buffer = [value shortValue];
	 return YES;
       }
       break;
    case DBUS_TYPE_INT32:
       if (([value respondsToSelector: @selector(intValue)])
         || (nil == value))
       {
	 *buffer = [value intValue];
	 return YES;
       }
       break;
    case DBUS_TYPE_UINT16:
       if (([value respondsToSelector: @selector(unsignedShortValue)])
         || (nil == value))
       {
	 *buffer = [value unsignedShortValue];
	 return YES;
       }
       break;
    case DBUS_TYPE_UINT32:
       if (([value respondsToSelector: @selector(unsignedIntValue)])
         || (nil == value))
       {
	 *buffer = [value unsignedIntValue];
	 return YES;
       }
       break;
    case DBUS_TYPE_INT64:
       if (([value respondsToSelector: @selector(longLongValue)])
         || (nil == value))
       {
	 *buffer = [value longLongValue];
	 return YES;
       }
       break;
    case DBUS_TYPE_UINT64:
       if (([value respondsToSelector: @selector(unsignedLongLongValue)])
         || (nil == value))
       {
	 *buffer = [value unsignedLongLongValue];
	 return YES;
       }
       break;
    case DBUS_TYPE_DOUBLE:
       if (([value respondsToSelector: @selector(doubleValue)])
         || (nil == value))
       {
	 union fpAndLLRep
	 {
           long long buf;
	   double val;
	 } rep;
	 rep.val = [value doubleValue];
	 *buffer = rep.buf;
	 return YES;
       }
       break;
    case DBUS_TYPE_STRING:
      if ([value respondsToSelector: @selector(UTF8String)])
      {
        *buffer = (uintptr_t)(void*)[value UTF8String];
        return YES;
      }
      else if (nil == value)
      {
        *buffer = (uintptr_t)(void*)"";
        return YES;
      }
      break;
    case DBUS_TYPE_OBJECT_PATH:
      if ([value isKindOfClass: [DKProxy class]])
      {
        DKProxy *rootProxy = [self proxyParent];
        /*
         * Handle remote objects:
         * We need to make sure that the paths are from the same proxy, because
         * that is the widest scope in which they are valid.
         */
        if ([rootProxy hasSameScopeAs: value])
        {
          *buffer = (uintptr_t)(void*)[[value _path] UTF8String];
          return YES;
        }
      }
      else if (nil == value)
      {
        *buffer = (uintptr_t)(void*)"";
        return YES;
      }
      else
      {
        DKProxy *rootProxy = [self proxyParent];
        /*
         * Handle local objects:
         * We need to find out if the proxy we derive from is an outgoing proxy.
         * If so, we can export the object via D-Bus, so that the caller can
         * interact with it.
         */
         if ([rootProxy _isLocal])
         {
 	   DKOutgoingProxy *newProxy = [DKOutgoingProxy proxyWithParent: rootProxy
	                                                         object: value];
	   *buffer = (uintptr_t)[[newProxy _path] UTF8String];
	   return YES;
         }
      }
      break;
    case DBUS_TYPE_SIGNATURE:
      if ([value respondsToSelector: @selector(DBusTypeSignature)])
      {
	*buffer = (uintptr_t)(void*)[[value DBusTypeSignature] UTF8String];
	return YES;
      }
      else if (value == nil)
      {
        *buffer = (uintptr_t)(void*)"";
        return YES;
      }
      break;
    default:
      break;
  }

  /*
   * None of the built in mappings worked. We still have a slight chance that a
   * custom selector was installed to unbox the type. So we try again by looking
   * up the selector.
   */
   aSelector = DKSelectorForUnboxingObjectAsType(value, DBusType);
   if (0 != aSelector)
   {
     NSMethodSignature *sig = [value methodSignatureForSelector: aSelector];
     // Only call it if we don't need arguments and the returnvalue fits into
     // the buffer:
     if ((2 == [sig numberOfArguments])
       && ([sig methodReturnLength] <= sizeof(long long)))
     {
       IMP unboxFun = [value methodForSelector: aSelector];

       // Cast to void* first so that we don't get any funny implicit casts
       *buffer = (long long)(uintptr_t)(void*)unboxFun(value, aSelector);
       return YES;
     }
   }

  return NO;
}

- (id) boxedValueForValueAt: (void*)buffer
{
  switch (DBusType)
  {
    case DBUS_TYPE_BYTE:
      return [objCEquivalent numberWithUnsignedChar: *(unsigned char*)buffer];
    case DBUS_TYPE_BOOLEAN:
      return [objCEquivalent numberWithBool: *(BOOL*)buffer];
    case DBUS_TYPE_INT16:
      return [objCEquivalent numberWithShort: *(int16_t*)buffer];
    case DBUS_TYPE_UINT16:
      return [objCEquivalent numberWithUnsignedShort: *(uint16_t*)buffer];
    case DBUS_TYPE_INT32:
      return [objCEquivalent numberWithInt: *(int32_t*)buffer];
    case DBUS_TYPE_UINT32:
      return [objCEquivalent numberWithUnsignedInt: *(uint32_t*)buffer];
    case DBUS_TYPE_INT64:
      return [objCEquivalent numberWithLongLong: *(int64_t*)buffer];
    case DBUS_TYPE_UINT64:
      return [objCEquivalent numberWithUnsignedLongLong: *(uint64_t*)buffer];
    case DBUS_TYPE_DOUBLE:
      return [objCEquivalent numberWithDouble: *(double*)buffer];
    case DBUS_TYPE_STRING:
      return [objCEquivalent stringWithUTF8String: *(char**)buffer];
    case DBUS_TYPE_OBJECT_PATH:
    {
      /*
       * To handle object-paths, we follow the argument/method tree back to the
       * proxy where it was created and create a new proxy with the proper
       * settings.
       */
      DKProxy *ancestor = [self proxyParent];
      NSString *service = [ancestor _service];
      DKEndpoint *endpoint = [ancestor _endpoint];
      NSString *path = [[NSString alloc] initWithUTF8String: *(char**)buffer];
      DKProxy *newProxy = [[[objCEquivalent alloc] initWithEndpoint: endpoint
	                                               andService: service
	                                                  andPath: path] autorelease];
      [path release];
      return newProxy;
    }
    case DBUS_TYPE_SIGNATURE:
      return [[[objCEquivalent alloc] initWithDBusSignature: *(char**)buffer
                                                       name: nil
                                                     parent: nil] autorelease];
    default:
      return nil;
  }
  return nil;
}


- (void) unmarshallFromIterator: (DBusMessageIter*)iter
                 intoInvocation: (NSInvocation*)inv
		        atIndex: (NSInteger)index
			 boxing: (BOOL)doBox
{
  // All basic types are guaranteed to fit into 64bit.
  uint64_t buffer = 0;

  // Type checking:
  const char *invType;
  const char *expectedType;

  // Check that the method contains the expected type.
  int iterType = dbus_message_iter_get_arg_type(iter);
  NSAssert3((iterType == DBusType),
    @"Type mismatch between D-Bus message and introspection data. Got '%ld', expected '%ld' in method %@." ,
      iterType, DBusType, [parent name]);

  if (doBox)
  {
    expectedType = @encode(id);
  }
  else
  {
    expectedType = [self unboxedObjCTypeChar];
  }

  if (index == -1)
  {
    invType = [[inv methodSignature] methodReturnType];
  }
  else
  {
    invType = [[inv methodSignature] getArgumentTypeAtIndex: index];
  }

  // Check whether the invocation has a matching call frame:
  NSAssert((0 == strcmp(invType, expectedType)),
    @"Type mismatch between introspection data and invocation.");

  dbus_message_iter_get_basic(iter, (void*)&buffer);

  if (doBox)
  {
    id value = [self boxedValueForValueAt: (void*)&buffer];
    if (index == -1)
    {
      [inv setReturnValue: &value];
    }
    else
    {
      [inv setArgument: &value
               atIndex: index];
    }
  }
  else
  {
    if (index == -1)
    {
      [inv setReturnValue: (void*)&buffer];
    }
    else
    {
      [inv setArgument: (void*)&buffer
               atIndex: index];
    }
  }
}

-(id) unmarshalledObjectFromIterator: (DBusMessageIter*)iter
{
  // All basic types are guaranteed to fit into 64bit.
  uint64_t buffer = 0;
  int iterType = dbus_message_iter_get_arg_type(iter);

  // Check that the method contains the expected type.
  NSAssert3((iterType == DBusType),
    @"Type mismatch between D-Bus message and introspection data. Got '%ld', expected '%ld' in method %@." ,
      iterType, DBusType, [parent name]);

  dbus_message_iter_get_basic(iter, (void*)&buffer);

  return [self boxedValueForValueAt: (void*)&buffer];
}

-(id) unmarshalledProxyStandinFromIterator: (DBusMessageIter*)iter
{
  const char *buffer = 0;
  DKProxy *ancestor = [self proxyParent];
  NSString *service = [ancestor _service];
  DKEndpoint *endpoint = [ancestor _endpoint];
  NSString *path = nil;
  DKProxyStandin *standin = nil;
  int iterType = dbus_message_iter_get_arg_type(iter);

  // Check that the method contains the expected type.
  NSAssert3((iterType == DBusType),
    @"Type mismatch between D-Bus message and introspection data. Got '%ld', expected '%ld' in method %@." ,
      iterType, DBusType, [parent name]);

  dbus_message_iter_get_basic(iter, (void*)&buffer);
  path = [[NSString alloc] initWithUTF8String: buffer];
  standin = [[[DKProxyStandin alloc] initWithEndpoint: endpoint
	                                      service: service
	                                         path: path] autorelease];
  [path release];
  return standin;

}

- (void) marshallArgumentAtIndex: (NSInteger)index
                  fromInvocation: (NSInvocation*)inv
                    intoIterator: (DBusMessageIter*)iter
                          boxing: (BOOL)doBox
{
  uint64_t buffer = 0;
  const char* invType;
  const char* expectedType;

  if (doBox)
  {
    expectedType = @encode(id);
  }
  else
  {
    expectedType = [self unboxedObjCTypeChar];
  }

  if (-1 == index)
  {
    invType = [[inv methodSignature] methodReturnType];
  }
  else
  {
    invType = [[inv methodSignature] getArgumentTypeAtIndex: index];
  }

  NSAssert((0 == strcmp(expectedType, invType)),
    @"Type mismatch between introspection data and invocation.");

  if (doBox)
  {
    id value = nil;

    if (-1 == index)
    {
      [inv getReturnValue: &value];
    }
    else
    {
      [inv getArgument: &value
               atIndex: index];
    }

    if (NO == [self unboxValue: value intoBuffer: (long long*)(void*)&buffer])
    {
      [NSException raise: @"DKArgumentUnboxingException"
                  format: @"Could not unbox object '%@' into D-Bus format",
        value];
    }
  }
  else
  {
    if (-1 == index)
    {
      [inv getReturnValue: (void*)&buffer];
    }
    else
    {
      [inv getArgument: (void*)&buffer
               atIndex: index];
    }
  }

  DK_ITER_APPEND(iter, DBusType, &buffer);
}

- (void) marshallObject: (id)object
           intoIterator: (DBusMessageIter*)iter
{
  long long int buffer = 0;
  if (NO == [self unboxValue: object intoBuffer: &buffer])
  {
    [NSException raise: @"DKArgumentUnboxingException"
                format: @"Could not unbox object '%@' into D-Bus format",
      object];
  }
  DK_ITER_APPEND(iter, DBusType, &buffer);
}

@end


@implementation DKContainerTypeArgument
/**
 * Initializes the container type argument with the first complete signature
 * from <var>iterator</var>. Returns <var>nil</var> if the signature does not
 * describe a container argument.
 */
- (id)initWithIterator: (DBusSignatureIter*)iterator
                  name: (NSString*)_name
                parent: (id)_parent
{
  DBusSignatureIter subIterator;
  Class concreteClass = Nil;

  // Get the type from the iterator:
  DBusType = dbus_signature_iter_get_current_type(iterator);
  if (!dbus_type_is_container(DBusType))
  {
    NSWarnMLog(@"Incorrectly initialized container type D-Bus argument ('%@' is not a container type).",
      [NSString stringWithCharacters: (unichar*)&DBusType length: 1]);
      [self release];
      return nil;
  }


  /*
   * If the initializer is called for the DKContainerTypeArgument class, we need
   * to get concrete subclass from the DBusType
   */
  if ([DKContainerTypeArgument class] == [self class])
  {
    switch (DBusType)
    {
      case DBUS_TYPE_VARIANT:
        concreteClass = [DKVariantTypeArgument class];
        break;
      case DBUS_TYPE_ARRAY:
        concreteClass = [DKArrayTypeArgument class];
        break;
      case DBUS_TYPE_STRUCT:
        concreteClass = [DKStructTypeArgument class];
        break;
      case DBUS_TYPE_DICT_ENTRY:
        concreteClass = [DKDictEntryTypeArgument class];
        break;
      default:
        NSWarnMLog(@"Cannot handle unkown container type.");
        [self release];
        return nil;
    }

    [self release];
    return [[concreteClass alloc] initWithIterator: iterator
                                              name: _name
                                            parent: _parent];
  }

  if (nil == (self = [super initWithIterator: iterator
                                        name: _name
                                      parent: _parent]))
  {
    return nil;
  }


  children = [[NSMutableArray alloc] init];

  /*
   * A shortcut is needed for variant types. libdbus classifies them as
   * containers, but it is clearly wrong about that at least with regard to
   * the signatures:
   * They have no children and dbus will fail and crash if it tries to loop
   * over their non-existent sub-arguments. Hence we return after setting the
   * subclass.
   */

  if (DBUS_TYPE_VARIANT == DBusType)
  {
    return self;
  }

  /*
   * Create an iterator for the immediate subarguments of this argument and loop
   * over it until we have all the constituent types.
   */
  dbus_signature_iter_recurse(iterator, &subIterator);
  do
  {
    Class childClass = Nil;
    DKArgument *subArgument = nil;
    int subType = dbus_signature_iter_get_current_type(&subIterator);

    if (dbus_type_is_container(subType))
    {
       childClass = [DKContainerTypeArgument class];
    }
    else
    {
      childClass = [DKArgument class];
    }

    subArgument = [[childClass alloc] initWithIterator: &subIterator
                                                  name: _name
                                                parent: self];
    if (subArgument)
    {
      [children addObject: subArgument];
      [subArgument release];
    }
  } while (dbus_signature_iter_next(&subIterator));

  /* Be smart: If we are ourselves of DBUS_TYPE_DICT_ENTRY, then a
   * DBUS_TYPE_ARRAY argument above us is actually a dictionary, so we set the
   * type accordingly.
   */
  if (DBUS_TYPE_DICT_ENTRY == DBusType)
  {
    if ([parent isKindOfClass: [DKArrayTypeArgument class]])
    {
      if (DBUS_TYPE_ARRAY == [(id)parent DBusType])
      {
	[(id)parent setIsDictionary: YES];
      }
    }
  }
  return self;
}

- (const char*) unboxedObjCTypeChar
{
  /*
   * All container types are boxed.
   */
  return @encode(id);
}

- (size_t) unboxedObjCTypeSize
{
  return sizeof(id);
}

- (id) boxedValueForValueAt: (void*)buffer
{
  // It is a bad idea to try this on a container type.
  [self shouldNotImplement: _cmd];
  return nil;
}

- (NSString*) DBusTypeSignature
{
  NSMutableString *sig = [[NSMutableString alloc] init];
  NSString *ret = nil;
  // [[children fold] stringByAppendingString: @""]
  NSEnumerator *enumerator = [children objectEnumerator];
  DKArgument *subArg = nil;
  while (nil != (subArg = [enumerator nextObject]))
  {
    [sig appendString: [subArg DBusTypeSignature]];
  }

  switch (DBusType)
  {
    case DBUS_TYPE_VARIANT:
      [sig insertString: [NSString stringWithUTF8String: DBUS_TYPE_VARIANT_AS_STRING]
                atIndex: 0];
      break;
    case DBUS_TYPE_ARRAY:
      [sig insertString: [NSString stringWithUTF8String: DBUS_TYPE_ARRAY_AS_STRING]
                atIndex: 0];
      break;
    case DBUS_TYPE_STRUCT:
      [sig insertString: [NSString stringWithUTF8String: DBUS_STRUCT_BEGIN_CHAR_AS_STRING]
                                                atIndex: 0];
      [sig appendString: [NSString stringWithUTF8String: DBUS_STRUCT_END_CHAR_AS_STRING]];
      break;
    case DBUS_TYPE_DICT_ENTRY:
      [sig insertString: [NSString stringWithUTF8String: DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING]
                                                atIndex: 0];
      [sig appendString: [NSString stringWithUTF8String: DBUS_DICT_ENTRY_END_CHAR_AS_STRING]];
      break;
    default:
      NSAssert(NO, @"Invalid D-Bus type when generating container type signature");
      break;
  }
  ret = [NSString stringWithString: sig];
  [sig release];
  return ret;
}

- (BOOL) isContainerType
{
  return YES;
}

- (NSArray*) children
{
  return children;
}

/**
 * Replaces the children with the new mutable array. Used when copying the
 * argument.
 */
- (void) setChildren: (NSMutableArray*)newChildren
{
  ASSIGN(children,newChildren);
  [children makeObjectsPerformSelector: @selector(setParent:) withObject: self];
}

- (id)copyWithZone: (NSZone*)zone
{
  DKContainerTypeArgument *newNode = [super copyWithZone: zone];
  NSMutableArray *newChildren = nil;
  newChildren = [[NSMutableArray allocWithZone: zone] initWithArray: children
                                                          copyItems: YES];
  [newNode setChildren: newChildren];
  [newChildren release];
  return newNode;
}

/*
 * Since we always box container types, we can simply set the argument/return
 * values to the object produced by unmarshalling.
 */
- (void) unmarshallFromIterator: (DBusMessageIter*)iter
                 intoInvocation: (NSInvocation*)inv
		        atIndex: (NSInteger)index
			 boxing: (BOOL)doBox
{
  id value = [self unmarshalledObjectFromIterator: iter];

  if (-1 == index)
  {
    NSAssert((0 == strcmp(@encode(id), [[inv methodSignature] methodReturnType])),
      @"Type mismatch between introspection data and invocation.");
    [inv setReturnValue: &value];
  }
  else
  {
    NSAssert((0 == strcmp(@encode(id), [[inv methodSignature] getArgumentTypeAtIndex: index])),
      @"Type mismatch between introspection data and invocation.");
    [inv setArgument: &value
             atIndex: index];
  }
}

-(id) unmarshalledObjectFromIterator: (DBusMessageIter*)iter
{
  /*
   * For the general case, we cannot determine how to unmarshall the argument.
   */
  [self subclassResponsibility: _cmd];
  return nil;
}

- (void) marshallArgumentAtIndex: (NSInteger)index
                  fromInvocation: (NSInvocation*)inv
                    intoIterator: (DBusMessageIter*)iter
                          boxing: (BOOL)doBox
{
  id value = nil;

  if (-1 == index)
  {
    NSAssert((0 == strcmp(@encode(id), [[inv methodSignature] methodReturnType])),
      @"Type mismatch between introspection data and invocation.");
    [inv getReturnValue: &value];
  }
  else
  {
    NSAssert((0 == strcmp(@encode(id), [[inv methodSignature] getArgumentTypeAtIndex: index])),
      @"Type mismatch between introspection data and invocation.");
    [inv getArgument: &value
             atIndex: index];
  }
  [self marshallObject: value
          intoIterator: iter];
}

- (void) marshallObject: (id)object
           intoIterator: (DBusMessageIter*)iter
{
  [self subclassResponsibility: _cmd];
}

- (void) dealloc
{
  [children release];
  [super dealloc];
}
@end;

@implementation DKArrayTypeArgument
- (id)initWithIterator: (DBusSignatureIter*)iterator
                  name: (NSString*)_name
                parent: (id)_parent
{
  NSUInteger childCount = 0;
  if (nil == (self = [super initWithIterator: iterator
                                        name: _name
                                      parent: _parent]))
  {
    return nil;
  }

  childCount = [children count];

  // Arrays can only have a single type:
  if (childCount != 1)
  {
    NSWarnMLog(@"Invalid number of children (%lu) for D-Bus array argument",
      childCount);
    [self release];
    return nil;
  }

  return self;
}

- (BOOL) isDictionary
{
  return NO;
}

- (void) setIsDictionary: (BOOL)isDict
{
# ifndef NDEBUG
  GSDebugAllocationRemove(isa, self);
# endif
  if (isDict)
  {
    object_setClass(self,[DKDictionaryTypeArgument class]);
    [self setObjCEquivalent: [NSDictionary class]];
  }
  else
  {
    // Not sure why somebody would want to do that
    object_setClass(self,[DKArrayTypeArgument class]);
    [self setObjCEquivalent: [NSArray class]];
  }
#ifndef NDEBUG
  GSDebugAllocationAdd(isa, self);
#endif
}

/**
 * Array type arguments only have one child that describes the type of all its
 * elements.
 */
- (DKArgument*)elementTypeArgument
{
  return [children objectAtIndex: 0];
}

/**
 * Helper method to make sure that the iterator is a usable state.
 */
- (void) assertSaneIterator: (DBusMessageIter*)iter
{
  int childType = DBUS_TYPE_INVALID;
  // Make sure we are deserializing an array:
  NSAssert((DBUS_TYPE_ARRAY == dbus_message_iter_get_arg_type(iter)),
    @"Non array type when unmarshalling array from message.");
  childType = dbus_message_iter_get_element_type(iter);

  // Make sure we have the expected element type.
  NSAssert((childType == [[self elementTypeArgument] DBusType]),
    @"Type mismatch between D-Bus message and introspection data.");
}

-(id) unmarshalledObjectFromIterator: (DBusMessageIter*)iter
{
  DKArgument *theChild = [self elementTypeArgument];
  DBusMessageIter subIter;
  NSMutableArray *theArray = [NSMutableArray new];
  NSArray *returnArray = nil;
  NSNull *theNull = [NSNull null];

  [self assertSaneIterator: iter];

  dbus_message_iter_recurse(iter, &subIter);
  do
  {
    id obj = nil;
    if (0 == dbus_message_iter_get_arg_type(&subIter))
    {
      // If we opened an empty iterator, we just break from the loop
      break;
    }
    obj = [theChild unmarshalledObjectFromIterator: &subIter];
    if (nil == obj)
    {
      obj = theNull;
    }
    [theArray addObject: obj];
  } while (dbus_message_iter_next(&subIter));

  returnArray = [NSArray arrayWithArray: theArray];
  [theArray release];
  return returnArray;
}

- (void) marshallObject: (id)object
           intoIterator: (DBusMessageIter*)iter
{
  DBusMessageIter subIter;
  DKArgument *theChild = [self elementTypeArgument];
  NSEnumerator *elementEnum = nil;
  id element = nil;
  if (nil == object)
  {
    object = [NSArray array];
  }
  NSAssert1([object respondsToSelector: @selector(objectEnumerator)],
    @"Cannot enumerate contents of %@ when creating D-Bus array.",
    object);

  DK_ITER_OPEN_CONTAINER(iter, DBUS_TYPE_ARRAY, [[theChild DBusTypeSignature] UTF8String], &subIter);

  elementEnum = [object objectEnumerator];
  NS_DURING
  {
    while (nil != (element = [elementEnum nextObject]))
    {
      [theChild marshallObject: element
                  intoIterator: &subIter];

    }
  }
  NS_HANDLER
  {
    // We are already screwed and don't care whether
    // dbus_message_iter_close_container() returns OOM.
    dbus_message_iter_close_container(iter, &subIter);
    [localException raise];
  }
  NS_ENDHANDLER

  DK_ITER_CLOSE_CONTAINER(iter, &subIter);
}
@end

@implementation DKDictionaryTypeArgument
/*
 * NOTE: Most of the time, this initializer will not be used, because we only
 * know ex-post whether something is a dictionary (by virtue of having elements
 * of DBUS_TYPE_DICT_ENTRY).
 */
- (id)initWithIterator: (DBusSignatureIter*)iterator
                  name: (NSString*)_name
                parent: (id)_parent
{
  if (nil == (self = [super initWithIterator: iterator
                                        name: _name
                                      parent: _parent]))
  {
    return nil;
  }

  if (![[self elementTypeArgument] isKindOfClass: [DKDictEntryTypeArgument class]])
  {
    NSWarnMLog(@"Invalid dictionary type argument (does not contan a dict entry).");
    [self release];
    return nil;
  }
  return self;
}

- (BOOL) isDictionary
{
  return YES;
}

- (void) assertSaneIterator: (DBusMessageIter*)iter
{
  [super assertSaneIterator: iter];
  NSAssert((DBUS_TYPE_DICT_ENTRY == dbus_message_iter_get_element_type(iter)),
    @"Non dict-entry type in iterator when unmarshalling a dictionary.");
}

-(id) unmarshalledObjectFromIterator: (DBusMessageIter*)iter
{
  DKDictEntryTypeArgument *theChild = (DKDictEntryTypeArgument*)[self elementTypeArgument];
  DBusMessageIter subIter;
  NSMutableDictionary *theDictionary = [NSMutableDictionary new];
  NSDictionary *returnDictionary = nil;
  NSNull *theNull = [NSNull null];

  [self assertSaneIterator: iter];

  // We loop over the dict entries:
  dbus_message_iter_recurse(iter, &subIter);
  do
  {
    id value = nil;
    id key = nil;
    if (0 == dbus_message_iter_get_arg_type(&subIter))
    {
      // If we opened an empty iterator, break the loop.
      break;
    }
    [theChild unmarshallFromIterator: &subIter
                               value: &value
                                 key: &key];
    if (key == nil)
    {
      key = theNull;
    }
    if (value == nil)
    {
      value = theNull;
    }

    if (nil == [theDictionary objectForKey: key])
    {
      /*
       * From the D-Bus specification:
       * "A message is considered corrupt if the same key occurs twice in the
       * same array of DICT_ENTRY. However, for performance reasons
       * implementations are not required to reject dicts with duplicate keys."
       * We choose to just ignore duplicate keys:
       */
      [theDictionary setObject: value
                        forKey: key];
    }
    else
    {
      NSWarnMLog(@"Ignoring duplicate key (%@) in D-Bus dictionary.", key);
    }

  } while (dbus_message_iter_next(&subIter));

  returnDictionary = [NSDictionary dictionaryWithDictionary: theDictionary];
  [theDictionary release];
  return returnDictionary;
}

- (void) marshallObject: (id)object
           intoIterator: (DBusMessageIter*)iter
{
  NSArray *keys = nil;
  NSEnumerator *keyEnum = nil;
  DKDictEntryTypeArgument *pairArgument = (DKDictEntryTypeArgument*)[self elementTypeArgument];
  id element = nil;

  DBusMessageIter subIter;
  if (nil == object)
  {
    object = [NSDictionary dictionary];
  }

  NSAssert1(([object respondsToSelector: @selector(allKeys)]
    && [object respondsToSelector: @selector(objectForKey:)]),
    @"Cannot marshall non key/value dictionary '%@' to D-Bus iterator.",
    object);

  DK_ITER_OPEN_CONTAINER(iter, DBUS_TYPE_ARRAY, [[pairArgument DBusTypeSignature] UTF8String], &subIter);

  keys = [object allKeys];
  keyEnum = [keys objectEnumerator];

  NS_DURING
  {
    while (nil != (element = [keyEnum nextObject]))
    {
      [pairArgument marshallObject: [object objectForKey: element]
                            forKey: element
		      intoIterator: &subIter];
    }
  }
  NS_HANDLER
  {
    // Something already went wrong and we don't care for a potential OOM error
    // from dbus_message_iter_close_container();
    dbus_message_iter_close_container(iter, &subIter);
    [localException raise];
  }
  NS_ENDHANDLER

  DK_ITER_CLOSE_CONTAINER(iter, &subIter);
}
@end

@implementation DKStructTypeArgument
-(id) unmarshalledObjectFromIterator: (DBusMessageIter*)iter
{
  NSMutableArray *theArray = [NSMutableArray new];
  NSArray *returnArray = nil;
  NSNull *theNull = [NSNull null];
  NSUInteger index = 0;
  NSUInteger count = [children count];
  DBusMessageIter subIter;
  NSAssert((DBUS_TYPE_STRUCT == dbus_message_iter_get_arg_type(iter)),
    @"Type mismatch between introspection data and D-Bus message.");

  dbus_message_iter_recurse(iter,&subIter);
  do
  {
    id obj = [[children objectAtIndex: index] unmarshalledObjectFromIterator: &subIter];
    if (nil == obj)
    {
      obj = theNull;
    }
    [theArray addObject: obj];
  } while (dbus_message_iter_next(&subIter) && (++index < count));

  returnArray = [NSArray arrayWithArray: theArray];
  [theArray release];
  return returnArray;
}

- (void) marshallObject: (id)object
           intoIterator: (DBusMessageIter*)iter
{
  DBusMessageIter subIter;
  NSEnumerator *structEnum = nil;
  NSUInteger childCount = [children count];


  if (nil != object)
  {
    NSAssert1(([object respondsToSelector: @selector(count)]
      && [object respondsToSelector: @selector(objectEnumerator)]),
      @"Object '%@' cannot be marshalled as D-Bus struct.",
      object);
    NSAssert3(([object count] == childCount),
      @"Could not marshall object '%@' as D-Bus struct: Expected %lu members, got %lu.",
      object,
      [object count],
      childCount);
  }

  DK_ITER_OPEN_CONTAINER(iter, DBUS_TYPE_STRUCT, NULL, &subIter);

  if (nil != object)
  {
    structEnum = [object objectEnumerator];

    NS_DURING
    {
      NSUInteger index = 0;
      id member = nil;
      while ((nil != (member = [structEnum nextObject]))
        && (index < childCount))
      {
        [[children objectAtIndex: index] marshallObject: member
                                           intoIterator: &subIter];
      index++;
      }
    }
    NS_HANDLER
    {
      dbus_message_iter_close_container(iter, &subIter);
      [localException raise];
    }
    NS_ENDHANDLER
  }
  DK_ITER_CLOSE_CONTAINER(iter, &subIter);
}
@end


@implementation DKVariantTypeArgument

/**
 * Helper method to determine the sub-signature of array elements or dictionary
 * keys/values. This can only be a proper signature if all elements are of the
 * same type. Otherwise, the variant type will be returned.
 */
- (NSString*)validSubSignatureOrVariantForEnumerator: (NSEnumerator*)theEnum
{
  id element = [theEnum nextObject];
  NSString *thisSig = [[self DKArgumentWithObject: element] DBusTypeSignature];
  NSString *nextSig = thisSig;

  // For homogenous collection, we can get the proper signature, for non-homogenous
  // ones, we need to pass down the variant type.
  BOOL isHomogenous = YES;
  while ((nil != (element = [theEnum nextObject]))
    && (YES == isHomogenous))
  {
    thisSig = nextSig;
    nextSig = [[self DKArgumentWithObject: element] DBusTypeSignature];
    isHomogenous = [thisSig isEqualToString: nextSig];
  }

  if (isHomogenous)
  {
    return thisSig;
  }
  else
  {
    return @"v";
  }

}

- (DKArgument*) DKArgumentWithObject: (id)object
{
  if (([object respondsToSelector: @selector(keyEnumerator)])
    && ([object respondsToSelector: @selector(objectEnumerator)]))
  {
    NSEnumerator *keyEnum = [object keyEnumerator];
    NSEnumerator *objEnum = [object objectEnumerator];
    NSString *keySig = [self validSubSignatureOrVariantForEnumerator: keyEnum];
    NSString *objSig = [self validSubSignatureOrVariantForEnumerator: objEnum];
    NSString *theSig = [NSString stringWithFormat: @"a{%@%@}", keySig, objSig];
    DKArgument *subArg = [[[DKArgument alloc] initWithDBusSignature: [theSig UTF8String]
                                                               name: nil
                                                             parent: self] autorelease];
    if (nil == subArg)
    {
      // This might happen if the dictionary could not properly be represented as
      // a D-Bus dictionary (i.e. it has keys of complex type. In this case, we
      // fall back to representing it as an array of structs:
      theSig = [NSString stringWithFormat: @"a(%@%@)", keySig, objSig];
      subArg = [[[DKArgument alloc] initWithDBusSignature: [theSig UTF8String]
                                                     name: nil
                                                   parent: self] autorelease];
    }
    return subArg;
  }
  else if ([object respondsToSelector: @selector(objectEnumerator)])
  {
    NSEnumerator *theEnum = [object objectEnumerator];
    NSString *subSig = [self validSubSignatureOrVariantForEnumerator: theEnum];
    return [[[DKArgument alloc] initWithDBusSignature: [[@"a" stringByAppendingString: subSig] UTF8String]
                                                 name: nil
                                               parent: self] autorelease];
  }
  else if ([object isKindOfClass: [DKProxy class]])
  {
    DKProxy *rootProxy = [self proxyParent];
    if ([rootProxy hasSameScopeAs: object])
    {
      return [[[DKArgument alloc] initWithDBusSignature: DBUS_TYPE_OBJECT_PATH_AS_STRING
                                                   name: nil
                                                 parent: self] autorelease];
    }
  }
  else
  {
    // Simple types are quite straightforward, if we can find an appropriate
    // deserialization selector.
    int type = DKDBusTypeForUnboxingObject(object);
    if ((DBUS_TYPE_INVALID != type) && (DBUS_TYPE_OBJECT_PATH != type))
    {
      return [[[DKArgument alloc] initWithDBusSignature: (char*)&type
                                                   name: nil
                                                 parent: self] autorelease];
    }
    else if ([[self proxyParent] _isLocal])
    {
      // If this fails, and the proxy from which this argument derives is an
      // outgoing proxy, we can export it as an object path.
      return [[[DKArgument alloc] initWithDBusSignature: DBUS_TYPE_OBJECT_PATH_AS_STRING
                                                   name: nil
                                                 parent: self] autorelease];
    }
  }
  // Too bad, we have apparantely no chance to generate an argument tree for
  // this object.
  return nil;
}

- (id) unmarshalledObjectFromIterator: (DBusMessageIter*)iter
{
  char *theSig = NULL;
  DBusMessageIter subIter;
  DKArgument *theArgument = nil;
  id theValue = nil;
  NSAssert((DBUS_TYPE_VARIANT == dbus_message_iter_get_arg_type(iter)),
    @"Type mismatch between introspection data and D-Bus message.");

  dbus_message_iter_recurse(iter,&subIter);
  theSig = dbus_message_iter_get_signature(&subIter);
  theArgument = [[DKArgument alloc] initWithDBusSignature: theSig
                                                     name: nil
                                                   parent: self];
  NS_DURING
  {
    theValue = [theArgument unmarshalledObjectFromIterator: &subIter];
  }
  NS_HANDLER
  {
    [theArgument release];
    dbus_free(theSig);
    [localException raise];
  }
  NS_ENDHANDLER

  [theArgument release];
  dbus_free(theSig);

  return theValue;
}

- (void) marshallObject: (id)object
           intoIterator: (DBusMessageIter*)iter
{
  DKArgument *subArg = [self DKArgumentWithObject: object];
  DBusMessageIter subIter;

  if (nil != object)
  {
    NSAssert1(subArg,
      @"Could not marshall object %@ as D-Bus variant type",
      subArg);
  }

  DK_ITER_OPEN_CONTAINER(iter, DBUS_TYPE_VARIANT, [[subArg DBusTypeSignature] UTF8String], &subIter);


  if (nil != object)
  {
    NS_DURING
    {
      [subArg marshallObject: object
                intoIterator: &subIter];
    }
    NS_HANDLER
    {
      dbus_message_iter_close_container(iter, &subIter);
      [localException raise];
    }
    NS_ENDHANDLER
  }
  DK_ITER_CLOSE_CONTAINER(iter, &subIter);
}
@end

@implementation DKDictEntryTypeArgument
- (id)initWithIterator: (DBusSignatureIter*)iterator
                  name: (NSString*)_name
                parent: (id)_parent
{
  NSUInteger childCount = 0;
  if (nil == (self = [super initWithIterator: iterator
                                        name: _name
                                      parent: _parent]))
  {
    return nil;
  }

  childCount = [children count];

  // Dictionaries have exactly two types:
  if (childCount != 2)
  {
    NSWarnMLog(@"Invalid number of children (%lu) for D-Bus dict entry argument. Ignoring argument.",
      childCount);
    [self release];
    return nil;
  }
  else if ([[children objectAtIndex: 0] isContainerType])
  {
    NSWarnMLog(@"Invalid (complex) type '%@' as dict entry key. Ignoring argument.",
      [[children objectAtIndex: 0] DBusTypeSignature]);
    [self release];
    return nil;
  }

  return self;
}

- (DKArgument*)keyArgument
{
  return [children objectAtIndex: 0];
}

- (DKArgument*)valueArgument
{
  return [children objectAtIndex: 1];
}

- (void) unmarshallFromIterator: (DBusMessageIter*)iter
                          value: (id*)value
                            key: (id*)key
{
  DBusMessageIter subIter;
  NSAssert((DBUS_TYPE_DICT_ENTRY == dbus_message_iter_get_arg_type(iter)),
    @"Type mismatch between introspection data and D-Bus message.");

  dbus_message_iter_recurse(iter, &subIter);

  *key = [[self keyArgument]  unmarshalledObjectFromIterator: &subIter];

  if (dbus_message_iter_next(&subIter))
  {
    *value = [[self valueArgument] unmarshalledObjectFromIterator: &subIter];
  }
  else
  {
    *value = nil;
  }
  return;
}
- (void) marshallObject: (id)object
                 forKey: (id)key
           intoIterator: (DBusMessageIter*)iter
{
  DBusMessageIter subIter;
  DK_ITER_OPEN_CONTAINER(iter, DBUS_TYPE_DICT_ENTRY, NULL, &subIter);

  if ((nil != key) && (nil != object))
  {
    NS_DURING
    {
      [[self keyArgument] marshallObject: key
                            intoIterator: &subIter];
      [[self valueArgument] marshallObject: object
                              intoIterator: &subIter];
    }
    NS_HANDLER
    {
      // Again, we don't care for OOM here because we already failed.
      dbus_message_iter_close_container(iter, &subIter);
      [localException raise];
    }
    NS_ENDHANDLER
  }
  DK_ITER_CLOSE_CONTAINER(iter, &subIter);
}
@end