File: girepository.c

package info (click to toggle)
glib2.0 2.86.1-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid
  • size: 67,012 kB
  • sloc: ansic: 544,596; python: 9,702; sh: 1,612; xml: 1,482; perl: 1,222; cpp: 535; makefile: 321; javascript: 11
file content (2381 lines) | stat: -rw-r--r-- 78,054 bytes parent folder | download | duplicates (2)
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
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
 * GObject introspection: Repository implementation
 *
 * Copyright (C) 2005 Matthias Clasen
 * Copyright (C) 2008 Colin Walters <walters@verbum.org>
 * Copyright (C) 2008 Red Hat, Inc.
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 *
 * 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
 * Lesser 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., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include "config.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <glib.h>
#include <glib-private.h>
#include <glib/gprintf.h>
#include <gmodule.h>
#include "gibaseinfo-private.h"
#include "girepository.h"
#include "gitypelib-internal.h"
#include "girepository-private.h"

/**
 * GIRepository:
 *
 * `GIRepository` is used to manage repositories of namespaces. Namespaces
 * are represented on disk by type libraries (`.typelib` files).
 *
 * The individual pieces of API within a type library are represented by
 * subclasses of [class@GIRepository.BaseInfo]. These can be found using
 * methods like [method@GIRepository.Repository.find_by_name] or
 * [method@GIRepository.Repository.get_info].
 *
 * You are responsible for ensuring that the lifetime of the
 * [class@GIRepository.Repository] exceeds that of the lifetime of any of its
 * [class@GIRepository.BaseInfo]s. This cannot be guaranteed by using internal
 * references within libgirepository as that would affect performance.
 *
 * ### Discovery of type libraries
 *
 * `GIRepository` will typically look for a `girepository-1.0` directory
 * under the library directory used when compiling gobject-introspection. On a
 * standard Linux system this will end up being `/usr/lib/girepository-1.0`.
 *
 * It is possible to control the search paths programmatically, using
 * [method@GIRepository.Repository.prepend_search_path]. It is also possible to
 * modify the search paths by using the `GI_TYPELIB_PATH` environment variable.
 * The environment variable takes precedence over the default search path
 * and the [method@GIRepository.Repository.prepend_search_path] calls.
 *
 * ### Namespace ordering
 *
 * In situations where namespaces may be searched in order, or returned in a
 * list, the namespaces will be returned in alphabetical order, with all fully
 * loaded namespaces being returned before any lazily loaded ones (those loaded
 * with `GI_REPOSITORY_LOAD_FLAG_LAZY`). This allows for deterministic and
 * reproducible results.
 *
 * Similarly, if a symbol (such as a `GType` or error domain) is being searched
 * for in the set of loaded namespaces, the namespaces will be searched in that
 * order. In particular, this means that a symbol which exists in two namespaces
 * will always be returned from the alphabetically-higher namespace. This should
 * only happen in the case of `Gio` and `GioUnix`/`GioWin32`, which all refer to
 * the same `.so` file and expose overlapping sets of symbols. Symbols should
 * always end up being resolved to `GioUnix` or `GioWin32` if they are platform
 * dependent, rather than `Gio` itself.
 *
 * Since: 2.80
 */

/* The namespace and version corresponding to libgirepository itself, so
 * that we can refuse to load typelibs corresponding to the older,
 * incompatible version of this same library in gobject-introspection. */
#define GIREPOSITORY_TYPELIB_NAME "GIRepository"
#define GIREPOSITORY_TYPELIB_VERSION "3.0"
#define GIREPOSITORY_TYPELIB_FILENAME \
  GIREPOSITORY_TYPELIB_NAME "-" GIREPOSITORY_TYPELIB_VERSION ".typelib"

typedef struct {
  size_t n_interfaces;
  GIBaseInfo *interfaces[];
} GTypeInterfaceCache;

static void
gtype_interface_cache_free (gpointer data)
{
  GTypeInterfaceCache *cache = data;

  for (size_t i = 0; i < cache->n_interfaces; i++)
    gi_base_info_unref ((GIBaseInfo*) cache->interfaces[i]);
  g_free (cache);
}

struct _GIRepository
{
  GObject parent;

  GPtrArray *typelib_search_path;  /* (element-type filename) (owned) */
  GPtrArray *library_paths;  /* (element-type filename) (owned) */

  /* Certain operations require iterating over the typelibs and the iteration
   * order may affect the results. So keep an ordered list of the typelibs,
   * alongside the hash table which keep the canonical strong reference to them. */
  GHashTable *typelibs; /* (string) namespace -> GITypelib */
  GPtrArray *ordered_typelibs;  /* (element-type unowned GITypelib) (owned) (not nullable) */
  GHashTable *lazy_typelibs; /* (string) namespace-version -> GITypelib */
  GPtrArray *ordered_lazy_typelibs;  /* (element-type unowned GITypelib) (owned) (not nullable) */

  GHashTable *info_by_gtype; /* GType -> GIBaseInfo */
  GHashTable *info_by_error_domain; /* GQuark -> GIBaseInfo */
  GHashTable *interfaces_for_gtype; /* GType -> GTypeInterfaceCache */
  GHashTable *unknown_gtypes; /* hashset of GType */

  char **cached_shared_libraries;  /* (owned) (nullable) (array zero-terminated=1) */
  size_t cached_n_shared_libraries;  /* length of @cached_shared_libraries, not including NULL terminator */
};

G_DEFINE_TYPE (GIRepository, gi_repository, G_TYPE_OBJECT);

static GITypelib *
require_internal (GIRepository           *repository,
                  const char             *namespace,
                  const char             *version,
                  GIRepositoryLoadFlags   flags,
                  const char * const     *search_paths,
                  size_t                  n_search_paths,
                  GError                **error);

#ifdef G_PLATFORM_WIN32
#include <windows.h>

static HMODULE girepository_dll = NULL;

BOOL WINAPI DllMain (HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved);

BOOL WINAPI
DllMain (HINSTANCE hinstDLL,
         DWORD     fdwReason,
         LPVOID    lpvReserved)
{
  if (fdwReason == DLL_PROCESS_ATTACH)
      girepository_dll = hinstDLL;

  return TRUE;
}

#endif /* G_PLATFORM_WIN32 */

#ifdef __APPLE__
#include <mach-o/dyld.h>

/* This function returns the file path of the loaded libgirepository1.0.dylib.
 * It iterates over all the loaded images to find the one with the
 * gi_repository_init symbol and returns its file path.
  */
static const char *
gi_repository_get_library_path_macos (void)
{
  /*
   * Relevant documentation:
   * https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/MachOTopics/0-Introduction/introduction.html
   * https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/dyld.3.html
   * https://opensource.apple.com/source/xnu/xnu-2050.18.24/EXTERNAL_HEADERS/mach-o/loader.h
  */
  const void *ptr = gi_repository_init;
  const struct mach_header *header;
  intptr_t offset;
  uint32_t i, count;

  /* Iterate over all the loaded images */
  count = _dyld_image_count ();
  for (i = 0; i < count; i++)
    {
      header = _dyld_get_image_header (i);
      offset = _dyld_get_image_vmaddr_slide (i);

      /* Locate the first `load` command */
      struct load_command *cmd = (struct load_command *) ((char *) header + sizeof (struct mach_header));
      if (header->magic == MH_MAGIC_64)
        cmd = (struct load_command *) ((char *) header + sizeof (struct mach_header_64));

      /* Find the first `segment` command iterating over all the `load` commands.
       * Then, check if the gi_repository_init symbol is in this image by checking
       * if the pointer is in the segment's memory address range.
       */
      uint32_t j = 0;
      while (j < header->ncmds)
        {
          if (cmd->cmd == LC_SEGMENT)
            {
              struct segment_command *seg = (struct segment_command *) cmd;
              if (((intptr_t) ptr >= ((intptr_t) seg->vmaddr + offset)) && ((intptr_t) ptr < ((intptr_t) seg->vmaddr + offset + (intptr_t) seg->vmsize)))
                return _dyld_get_image_name (i);
           }
          if (cmd->cmd == LC_SEGMENT_64)
            {
              struct segment_command_64 *seg = (struct segment_command_64 *) cmd;
              if (((intptr_t) ptr >= ((intptr_t) seg->vmaddr + offset)) && ((intptr_t) ptr < ((intptr_t) seg->vmaddr + offset + (intptr_t) seg->vmsize)))
                return _dyld_get_image_name (i);
            }
          /* Jump to the next command */
          j++;
          cmd = (struct load_command *) ((char *) cmd + cmd->cmdsize);
        }
    }
  return NULL;
}
#endif /* __APPLE__ */

/*
 * gi_repository_get_libdir:
 *
 * Returns the directory where the typelib files are installed.
 *
 * In platforms without relocation support, this functions returns the
 * `GOBJECT_INTROSPECTION_LIBDIR` directory defined at build time .
 *
 * On Windows and macOS this function returns the directory
 * relative to the installation directory detected at runtime.
 *
 * On macOS, if the library is installed in
 * `/Applications/MyApp.app/Contents/Home/lib/libgirepository-1.0.dylib`, it returns
 * `/Applications/MyApp.app/Contents/Home/lib/girepository-1.0`
 *
 * On Windows, if the application is installed in
 * `C:/Program Files/MyApp/bin/MyApp.exe`, it returns
 * `C:/Program Files/MyApp/lib/girepository-1.0`
*/
static const gchar *
gi_repository_get_libdir (void)
{
  static gchar *static_libdir;

  if (g_once_init_enter_pointer (&static_libdir))
    {
      gchar *libdir;
#if defined(G_PLATFORM_WIN32)
      const char *toplevel = g_win32_get_package_installation_directory_of_module (girepository_dll);
      libdir = g_build_filename (toplevel, GOBJECT_INTROSPECTION_RELATIVE_LIBDIR, NULL);
      g_ignore_leak (libdir);
#elif defined(__APPLE__)
      const char *libpath = gi_repository_get_library_path_macos ();
      if (libpath != NULL)
        {
          libdir = g_path_get_dirname (libpath);
          g_ignore_leak (libdir);
        } else {
          libdir = GOBJECT_INTROSPECTION_LIBDIR;
        }
#else /* !G_PLATFORM_WIN32 && !__APPLE__ */
        libdir = GOBJECT_INTROSPECTION_LIBDIR;
#endif
      g_once_init_leave_pointer (&static_libdir, libdir);
    }
  return static_libdir;
}

static void
gi_repository_init (GIRepository *repository)
{
  /* typelib search path */
    {
      const char *libdir;
      char *typelib_dir;
      const char *type_lib_path_env;

      /* This variable is intended to take precedence over both:
       *   - the default search path;
       *   - all gi_repository_prepend_search_path() calls.
       */
      type_lib_path_env = g_getenv ("GI_TYPELIB_PATH");

      if (type_lib_path_env)
        {
          char **custom_dirs;

          custom_dirs = g_strsplit (type_lib_path_env, G_SEARCHPATH_SEPARATOR_S, 0);
          repository->typelib_search_path =
            g_ptr_array_new_take_null_terminated ((gpointer) g_steal_pointer (&custom_dirs), g_free);
        }
      else
        {
          repository->typelib_search_path = g_ptr_array_new_null_terminated (1, g_free, TRUE);
        }

      libdir = gi_repository_get_libdir ();

      typelib_dir = g_build_filename (libdir, "girepository-1.0", NULL);

      g_ptr_array_add (repository->typelib_search_path, g_steal_pointer (&typelib_dir));

      /* Debian-specific, should be removed after
       * `apt-file search /usr/lib/girepository-1.0` stops returning results */
      g_ptr_array_add (repository->typelib_search_path, g_strdup ("/usr/lib/girepository-1.0"));
    }

  repository->library_paths = g_ptr_array_new_null_terminated (1, g_free, TRUE);

  repository->typelibs
    = g_hash_table_new_full (g_str_hash, g_str_equal,
                             (GDestroyNotify) g_free,
                             (GDestroyNotify) gi_typelib_unref);
  repository->ordered_typelibs = g_ptr_array_new_with_free_func (NULL);
  repository->lazy_typelibs
    = g_hash_table_new_full (g_str_hash, g_str_equal,
                             (GDestroyNotify) g_free,
                             (GDestroyNotify) gi_typelib_unref);
  repository->ordered_lazy_typelibs = g_ptr_array_new_with_free_func (NULL);

  repository->info_by_gtype
    = g_hash_table_new_full (g_direct_hash, g_direct_equal,
                             (GDestroyNotify) NULL,
                             (GDestroyNotify) gi_base_info_unref);
  repository->info_by_error_domain
    = g_hash_table_new_full (g_direct_hash, g_direct_equal,
                             (GDestroyNotify) NULL,
                             (GDestroyNotify) gi_base_info_unref);
  repository->interfaces_for_gtype
    = g_hash_table_new_full (g_direct_hash, g_direct_equal,
                             (GDestroyNotify) NULL,
                             (GDestroyNotify) gtype_interface_cache_free);
  repository->unknown_gtypes = g_hash_table_new (NULL, NULL);
}

static void
gi_repository_finalize (GObject *object)
{
  GIRepository *repository = GI_REPOSITORY (object);

  g_hash_table_destroy (repository->typelibs);
  g_ptr_array_unref (repository->ordered_typelibs);
  g_hash_table_destroy (repository->lazy_typelibs);
  g_ptr_array_unref (repository->ordered_lazy_typelibs);

  g_hash_table_destroy (repository->info_by_gtype);
  g_hash_table_destroy (repository->info_by_error_domain);
  g_hash_table_destroy (repository->interfaces_for_gtype);
  g_hash_table_destroy (repository->unknown_gtypes);

  g_clear_pointer (&repository->cached_shared_libraries, g_strfreev);

  g_clear_pointer (&repository->library_paths, g_ptr_array_unref);
  g_clear_pointer (&repository->typelib_search_path, g_ptr_array_unref);

  (* G_OBJECT_CLASS (gi_repository_parent_class)->finalize) (G_OBJECT (repository));
}

static void
gi_repository_class_init (GIRepositoryClass *class)
{
  GObjectClass *gobject_class;

  gobject_class = G_OBJECT_CLASS (class);

  gobject_class->finalize = gi_repository_finalize;
}

/**
 * gi_repository_prepend_search_path:
 * @repository: A #GIRepository
 * @directory: (type filename): directory name to prepend to the typelib
 *   search path
 *
 * Prepends @directory to the typelib search path.
 *
 * See also: gi_repository_get_search_path().
 *
 * Since: 2.80
 */
void
gi_repository_prepend_search_path (GIRepository *repository,
                                   const char   *directory)
{
  g_return_if_fail (GI_IS_REPOSITORY (repository));

  g_ptr_array_insert (repository->typelib_search_path, 0, g_strdup (directory));
}

/**
 * gi_repository_get_search_path:
 * @repository: A #GIRepository
 * @n_paths_out: (optional) (out): The number of search paths returned.
 *
 * Returns the current search path [class@GIRepository.Repository] will use when
 * loading typelib files.
 *
 * The list is internal to [class@GIRepository.Repository] and should not be
 * freed, nor should its string elements.
 *
 * The list is guaranteed to be `NULL` terminated. The `NULL` terminator is not
 * counted in @n_paths_out.
 *
 * Returns: (element-type filename) (transfer none) (array length=n_paths_out): list of search paths, most
 *   important first
 * Since: 2.80
 */
const char * const *
gi_repository_get_search_path (GIRepository *repository,
                               size_t       *n_paths_out)
{
  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);

  if G_UNLIKELY (!repository->typelib_search_path ||
                 !repository->typelib_search_path->pdata)
    {
      static const char * const empty_search_path[] = {NULL};

      if (n_paths_out)
        *n_paths_out = 0;

      return empty_search_path;
    }

  if (n_paths_out)
    *n_paths_out = repository->typelib_search_path->len;

  return (const char * const *) repository->typelib_search_path->pdata;
}

/**
 * gi_repository_prepend_library_path:
 * @repository: A #GIRepository
 * @directory: (type filename): a single directory to scan for shared libraries
 *
 * Prepends @directory to the search path that is used to
 * search shared libraries referenced by imported namespaces.
 *
 * Multiple calls to this function all contribute to the final
 * list of paths.
 *
 * The list of paths is unique to @repository. When a typelib is loaded by the
 * repository, the list of paths from the @repository at that instant is used
 * by the typelib for loading its modules.
 *
 * If the library is not found in the directories configured
 * in this way, loading will fall back to the system library
 * path (i.e. `LD_LIBRARY_PATH` and `DT_RPATH` in ELF systems).
 * See the documentation of your dynamic linker for full details.
 *
 * Since: 2.80
 */
void
gi_repository_prepend_library_path (GIRepository *repository,
                                    const char   *directory)
{
  g_return_if_fail (GI_IS_REPOSITORY (repository));

  g_ptr_array_insert (repository->library_paths, 0, g_strdup (directory));
}

/**
 * gi_repository_get_library_path:
 * @repository: A #GIRepository
 * @n_paths_out: (optional) (out): The number of library paths returned.
 *
 * Returns the current search path [class@GIRepository.Repository] will use when
 * loading shared libraries referenced by imported namespaces.
 *
 * The list is internal to [class@GIRepository.Repository] and should not be
 * freed, nor should its string elements.
 *
 * The list is guaranteed to be `NULL` terminated. The `NULL` terminator is not
 * counted in @n_paths_out.
 *
 * Returns: (element-type filename) (transfer none) (array length=n_paths_out): list of search paths, most
 *   important first
 * Since: 2.80
 */
const char * const *
gi_repository_get_library_path (GIRepository *repository,
                                size_t       *n_paths_out)
{
  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);

  if G_UNLIKELY (!repository->library_paths || !repository->library_paths->pdata)
    {
      static const char * const empty_search_path[] = {NULL};

      if (n_paths_out)
        *n_paths_out = 0;

      return empty_search_path;
    }

  if (n_paths_out)
    *n_paths_out = repository->library_paths->len;

  return (const char * const *) repository->library_paths->pdata;
}

static char *
build_typelib_key (const char *name, const char *source)
{
  GString *str = g_string_new (name);
  g_string_append_c (str, '\0');
  g_string_append (str, source);
  return g_string_free (str, FALSE);
}

/* Note: Returns %NULL (not an empty %NULL-terminated array) if there are no
 * dependencies. */
static char **
get_typelib_dependencies (GITypelib *typelib)
{
  Header *header;
  const char *dependencies_glob;

  header = (Header *)typelib->data;

  if (header->dependencies == 0)
    return NULL;

  dependencies_glob = gi_typelib_get_string (typelib, header->dependencies);
  return g_strsplit (dependencies_glob, "|", 0);
}

static GITypelib *
check_version_conflict (GITypelib *typelib,
                        const char  *namespace,
                        const char  *expected_version,
                        char       **version_conflict)
{
  Header *header;
  const char *loaded_version;

  if (expected_version == NULL)
    {
      if (version_conflict)
        *version_conflict = NULL;
      return typelib;
    }

  header = (Header*)typelib->data;
  loaded_version = gi_typelib_get_string (typelib, header->nsversion);
  g_assert (loaded_version != NULL);

  if (strcmp (expected_version, loaded_version) != 0)
    {
      if (version_conflict)
        *version_conflict = (char*)loaded_version;
      return NULL;
    }
  if (version_conflict)
    *version_conflict = NULL;
  return typelib;
}

static GITypelib *
get_registered_status (GIRepository *repository,
                       const char   *namespace,
                       const char   *version,
                       gboolean      allow_lazy,
                       gboolean     *lazy_status,
                       char        **version_conflict)
{
  GITypelib *typelib;

  if (lazy_status)
    *lazy_status = FALSE;
  typelib = g_hash_table_lookup (repository->typelibs, namespace);
  if (typelib)
    return check_version_conflict (typelib, namespace, version, version_conflict);
  typelib = g_hash_table_lookup (repository->lazy_typelibs, namespace);
  if (!typelib)
    return NULL;
  if (lazy_status)
    *lazy_status = TRUE;
  if (!allow_lazy)
    return NULL;
  return check_version_conflict (typelib, namespace, version, version_conflict);
}

static GITypelib *
get_registered (GIRepository *repository,
                const char   *namespace,
                const char   *version)
{
  return get_registered_status (repository, namespace, version, TRUE, NULL, NULL);
}

static gboolean
load_dependencies_recurse (GIRepository *repository,
                           GITypelib     *typelib,
                           GError      **error)
{
  char **dependencies;

  dependencies = get_typelib_dependencies (typelib);

  if (dependencies != NULL)
    {
      int i;

      const char * const *search_path =
        (const char * const *) repository->typelib_search_path->pdata;
      gsize search_path_len = repository->typelib_search_path->len;

      for (i = 0; dependencies[i]; i++)
        {
          char *dependency = dependencies[i];
          const char *last_dash;
          char *dependency_namespace;
          const char *dependency_version;

          last_dash = strrchr (dependency, '-');
          g_assert (last_dash != NULL);  /* get_typelib_dependencies() guarantees this */
          dependency_namespace = g_strndup (dependency, (size_t) (last_dash - dependency));
          dependency_version = last_dash+1;

          if (!require_internal (repository, dependency_namespace, dependency_version,
                                 0, search_path, search_path_len,
                                 error))
            {
              g_free (dependency_namespace);
              g_strfreev (dependencies);
              return FALSE;
            }
          g_free (dependency_namespace);
        }
      g_strfreev (dependencies);
    }
  return TRUE;
}

/* Sort typelibs by namespace. The main requirement here is just to make iteration
 * deterministic, otherwise results can change as a lot of the code here would
 * just iterate over a `GHashTable`.
 *
 * A sub-requirement of this is that namespaces are sorted such that if a GType
 * or symbol is found in multiple namespaces where one is a prefix of the other,
 * the longest namespace wins. In practice, this only happens in
 * Gio/GioUnix/GioWin32, as all three of those namespaces refer to the same
 * `.so` file and overlapping sets of the same symbols, but we want the platform
 * specific namespace to be returned in preference to anything else (even though
 * either namespace is valid).
 * See https://gitlab.gnome.org/GNOME/glib/-/issues/3303 */
static int
sort_typelibs_cb (const void *a,
                  const void *b)
{
  GITypelib *typelib_a = *(GITypelib **) a;
  GITypelib *typelib_b = *(GITypelib **) b;

  return strcmp (gi_typelib_get_namespace (typelib_a),
                 gi_typelib_get_namespace (typelib_b));
}

static const char *
register_internal (GIRepository *repository,
                   const char   *source,
                   gboolean      lazy,
                   GITypelib    *typelib,
                   GError      **error)
{
  Header *header;
  const char *namespace;

  g_return_val_if_fail (typelib != NULL, NULL);

  header = (Header *)typelib->data;

  g_return_val_if_fail (header != NULL, NULL);

  namespace = gi_typelib_get_string (typelib, header->namespace);

  if (lazy)
    {
      g_assert (!g_hash_table_lookup (repository->lazy_typelibs,
                                      namespace));
      g_hash_table_insert (repository->lazy_typelibs,
                           build_typelib_key (namespace, source), gi_typelib_ref (typelib));
      g_ptr_array_add (repository->ordered_lazy_typelibs, typelib);
      g_ptr_array_sort (repository->ordered_lazy_typelibs, sort_typelibs_cb);
    }
  else
    {
      gpointer value;
      char *key;

      /* First, try loading all the dependencies */
      if (!load_dependencies_recurse (repository, typelib, error))
        return NULL;

      /* Check if we are transitioning from lazily loaded state */
      if (g_hash_table_lookup_extended (repository->lazy_typelibs,
                                        namespace,
                                        (gpointer)&key, &value))
        {
          g_hash_table_remove (repository->lazy_typelibs, key);
          g_ptr_array_remove (repository->ordered_lazy_typelibs, typelib);
        }
      else
        {
          key = build_typelib_key (namespace, source);
        }

      g_hash_table_insert (repository->typelibs,
                           g_steal_pointer (&key),
                           gi_typelib_ref (typelib));
      g_ptr_array_add (repository->ordered_typelibs, typelib);
      g_ptr_array_sort (repository->ordered_typelibs, sort_typelibs_cb);
    }

  /* These types might be resolved now, clear the cache */
  g_hash_table_remove_all (repository->unknown_gtypes);

  /* Success */
  g_assert (namespace != NULL);

  return namespace;
}

/**
 * gi_repository_get_immediate_dependencies:
 * @repository: A #GIRepository
 * @namespace_: Namespace of interest
 * @n_dependencies_out: (optional) (out): Return location for the number of
 *   dependencies
 *
 * Return an array of the immediate versioned dependencies for @namespace_.
 * Returned strings are of the form `namespace-version`.
 *
 * Note: @namespace_ must have already been loaded using a function
 * such as [method@GIRepository.Repository.require] before calling this
 * function.
 *
 * To get the transitive closure of dependencies for @namespace_, use
 * [method@GIRepository.Repository.get_dependencies].
 *
 * The list is guaranteed to be `NULL` terminated. The `NULL` terminator is not
 * counted in @n_dependencies_out.
 *
 * Returns: (transfer full) (array length=n_dependencies_out): String array of
 *   immediate versioned dependencies
 * Since: 2.80
 */
char **
gi_repository_get_immediate_dependencies (GIRepository *repository,
                                          const char   *namespace,
                                          size_t       *n_dependencies_out)
{
  GITypelib *typelib;
  char **deps;

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);
  g_return_val_if_fail (namespace != NULL, NULL);

  typelib = get_registered (repository, namespace, NULL);
  g_return_val_if_fail (typelib != NULL, NULL);

  /* Ensure we always return a non-%NULL vector. */
  deps = get_typelib_dependencies (typelib);
  if (deps == NULL)
      deps = g_strsplit ("", "|", 0);

  if (n_dependencies_out != NULL)
    *n_dependencies_out = g_strv_length (deps);

  return deps;
}

/* Load the transitive closure of dependency namespace-version strings for the
 * given @typelib. @repository must be non-%NULL. @transitive_dependencies must
 * be a pre-existing GHashTable<owned utf8, owned utf8> set for storing the
 * dependencies. */
static void
get_typelib_dependencies_transitive (GIRepository *repository,
                                     GITypelib    *typelib,
                                     GHashTable   *transitive_dependencies)
{
  char **immediate_dependencies;

  immediate_dependencies = get_typelib_dependencies (typelib);

  for (size_t i = 0; immediate_dependencies != NULL && immediate_dependencies[i]; i++)
    {
      char *dependency;
      const char *last_dash;
      char *dependency_namespace;

      dependency = immediate_dependencies[i];

      /* Steal from the strv. */
      g_hash_table_add (transitive_dependencies, dependency);
      immediate_dependencies[i] = NULL;

      /* Recurse for this namespace. */
      last_dash = strrchr (dependency, '-');
      g_assert (last_dash != NULL);  /* get_typelib_dependencies() guarantees this */
      dependency_namespace = g_strndup (dependency, (size_t) (last_dash - dependency));

      typelib = get_registered (repository, dependency_namespace, NULL);
      g_return_if_fail (typelib != NULL);
      get_typelib_dependencies_transitive (repository, typelib,
                                           transitive_dependencies);

      g_free (dependency_namespace);
    }

  g_free (immediate_dependencies);
}

/**
 * gi_repository_get_dependencies:
 * @repository: A #GIRepository
 * @namespace_: Namespace of interest
 * @n_dependencies_out: (optional) (out): Return location for the number of
 *   dependencies
 *
 * Retrieves all (transitive) versioned dependencies for
 * @namespace_.
 *
 * The returned strings are of the form `namespace-version`.
 *
 * Note: @namespace_ must have already been loaded using a function
 * such as [method@GIRepository.Repository.require] before calling this
 * function.
 *
 * To get only the immediate dependencies for @namespace_, use
 * [method@GIRepository.Repository.get_immediate_dependencies].
 *
 * The list is guaranteed to be `NULL` terminated. The `NULL` terminator is not
 * counted in @n_dependencies_out.
 *
 * Returns: (transfer full) (array length=n_dependencies_out): String array of
 *   all versioned dependencies
 * Since: 2.80
 */
char **
gi_repository_get_dependencies (GIRepository *repository,
                                const char   *namespace,
                                size_t       *n_dependencies_out)
{
  GITypelib *typelib;
  GHashTable *transitive_dependencies;  /* set of owned utf8 */
  GHashTableIter iter;
  char *dependency;
  GPtrArray *out;  /* owned utf8 elements */

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);
  g_return_val_if_fail (namespace != NULL, NULL);

  typelib = get_registered (repository, namespace, NULL);
  g_return_val_if_fail (typelib != NULL, NULL);

  /* Load the dependencies. */
  transitive_dependencies = g_hash_table_new_full (g_str_hash, g_str_equal,
                                                   g_free, NULL);
  get_typelib_dependencies_transitive (repository, typelib,
                                       transitive_dependencies);

  /* Convert to a string array. */
  out = g_ptr_array_new_null_terminated (g_hash_table_size (transitive_dependencies),
                                         g_free, TRUE);
  g_hash_table_iter_init (&iter, transitive_dependencies);

  while (g_hash_table_iter_next (&iter, (gpointer) &dependency, NULL))
    {
      g_ptr_array_add (out, dependency);
      g_hash_table_iter_steal (&iter);
    }

  g_hash_table_unref (transitive_dependencies);

  if (n_dependencies_out != NULL)
    *n_dependencies_out = out->len;

  return (char **) g_ptr_array_free (out, FALSE);
}

/**
 * gi_repository_load_typelib:
 * @repository: A #GIRepository
 * @typelib: (transfer none): the typelib to load
 * @flags: flags affecting the loading operation
 * @error: return location for a [type@GLib.Error], or `NULL`
 *
 * Load the given @typelib into the repository.
 *
 * Returns: namespace of the loaded typelib
 * Since: 2.80
 */
const char *
gi_repository_load_typelib (GIRepository           *repository,
                            GITypelib              *typelib,
                            GIRepositoryLoadFlags   flags,
                            GError                **error)
{
  Header *header;
  const char *namespace;
  const char *nsversion;
  gboolean allow_lazy = flags & GI_REPOSITORY_LOAD_FLAG_LAZY;
  gboolean is_lazy;
  char *version_conflict;

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);

  header = (Header *) typelib->data;
  namespace = gi_typelib_get_string (typelib, header->namespace);
  nsversion = gi_typelib_get_string (typelib, header->nsversion);

  if (get_registered_status (repository, namespace, nsversion, allow_lazy,
                             &is_lazy, &version_conflict))
    {
      if (version_conflict != NULL)
        {
          g_set_error (error, GI_REPOSITORY_ERROR,
                       GI_REPOSITORY_ERROR_NAMESPACE_VERSION_CONFLICT,
                       "Attempting to load namespace '%s', version '%s', but '%s' is already loaded",
                       namespace, nsversion, version_conflict);
          return NULL;
        }
      return namespace;
    }
  return register_internal (repository, "<builtin>",
                            allow_lazy, typelib, error);
}

/**
 * gi_repository_is_registered:
 * @repository: A #GIRepository
 * @namespace_: Namespace of interest
 * @version: (nullable): Required version, may be `NULL` for latest
 *
 * Check whether a particular namespace (and optionally, a specific
 * version thereof) is currently loaded.
 *
 * This function is likely to only be useful in unusual circumstances; in order
 * to act upon metadata in the namespace, you should call
 * [method@GIRepository.Repository.require] instead which will ensure the
 * namespace is loaded, and return as quickly as this function will if it has
 * already been loaded.
 *
 * Returns: `TRUE` if namespace-version is loaded, `FALSE` otherwise
 * Since: 2.80
 */
gboolean
gi_repository_is_registered (GIRepository *repository,
                             const char   *namespace,
                             const char   *version)
{
  g_return_val_if_fail (GI_IS_REPOSITORY (repository), FALSE);

  return get_registered (repository, namespace, version) != NULL;
}

/**
 * gi_repository_new:
 *
 * Create a new [class@GIRepository.Repository].
 *
 * Returns: (transfer full): a new [class@GIRepository.Repository]
 * Since: 2.80
 */
GIRepository *
gi_repository_new (void)
{
  return g_object_new (GI_TYPE_REPOSITORY, NULL);
}

/**
 * gi_repository_get_n_infos:
 * @repository: A #GIRepository
 * @namespace_: Namespace to inspect
 *
 * This function returns the number of metadata entries in
 * given namespace @namespace_.
 *
 * The namespace must have already been loaded before calling this function.
 *
 * Returns: number of metadata entries
 * Since: 2.80
 */
unsigned int
gi_repository_get_n_infos (GIRepository *repository,
                           const char   *namespace)
{
  GITypelib *typelib;
  unsigned int n_interfaces = 0;

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), 0);
  g_return_val_if_fail (namespace != NULL, 0);

  typelib = get_registered (repository, namespace, NULL);

  g_return_val_if_fail (typelib != NULL, 0);

  n_interfaces = ((Header *)typelib->data)->n_local_entries;

  return n_interfaces;
}

/**
 * gi_repository_get_info:
 * @repository: A #GIRepository
 * @namespace_: Namespace to inspect
 * @idx: 0-based offset into namespace metadata for entry
 *
 * This function returns a particular metadata entry in the
 * given namespace @namespace_.
 *
 * The namespace must have already been loaded before calling this function.
 * See [method@GIRepository.Repository.get_n_infos] to find the maximum number
 * of entries. It is an error to pass an invalid @idx to this function.
 *
 * Returns: (transfer full) (not nullable): [class@GIRepository.BaseInfo]
 *   containing metadata
 * Since: 2.80
 */
GIBaseInfo *
gi_repository_get_info (GIRepository *repository,
                        const char   *namespace,
                        unsigned int  idx)
{
  GITypelib *typelib;
  DirEntry *entry;

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);
  g_return_val_if_fail (namespace != NULL, NULL);
  g_return_val_if_fail (idx < G_MAXUINT16, NULL);

  typelib = get_registered (repository, namespace, NULL);

  g_return_val_if_fail (typelib != NULL, NULL);

  entry = gi_typelib_get_dir_entry (typelib, idx + 1);
  g_return_val_if_fail (entry != NULL, NULL);

  return gi_info_new_full (gi_typelib_blob_type_to_info_type (entry->blob_type),
                           repository,
                           NULL, typelib, entry->offset);
}

static DirEntry *
find_by_gtype (GPtrArray   *ordered_table,
               const char  *gtype_name,
               gboolean     check_prefix,
               GITypelib  **out_result_typelib)
{
  /* Search in reverse order as the longest namespaces will be listed last, and
   * those are the ones we want to search first. */
  for (guint i = ordered_table->len; i > 0; i--)
    {
      GITypelib *typelib = g_ptr_array_index (ordered_table, i - 1);
      DirEntry *ret;

      if (check_prefix)
        {
          if (!gi_typelib_matches_gtype_name_prefix (typelib, gtype_name))
            continue;
        }

      ret = gi_typelib_get_dir_entry_by_gtype_name (typelib, gtype_name);
      if (ret)
        {
          *out_result_typelib = typelib;
          return ret;
        }
    }

  return NULL;
}

/**
 * gi_repository_find_by_gtype:
 * @repository: A #GIRepository
 * @gtype: [type@GObject.Type] to search for
 *
 * Searches all loaded namespaces for a particular [type@GObject.Type].
 *
 * Note that in order to locate the metadata, the namespace corresponding to
 * the type must first have been loaded.  There is currently no
 * mechanism for determining the namespace which corresponds to an
 * arbitrary [type@GObject.Type] — thus, this function will operate most
 * reliably when you know the [type@GObject.Type] is from a loaded namespace.
 *
 * Returns: (transfer full) (nullable): [class@GIRepository.BaseInfo]
 *   representing metadata about @type, or `NULL` if none found
 * Since: 2.80
 */
GIBaseInfo *
gi_repository_find_by_gtype (GIRepository *repository,
                             GType         gtype)
{
  const char *gtype_name;
  GITypelib *result_typelib = NULL;
  GIBaseInfo *cached;
  DirEntry *entry;

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);
  g_return_val_if_fail (gtype != G_TYPE_INVALID, NULL);

  cached = g_hash_table_lookup (repository->info_by_gtype,
                                (gpointer)gtype);

  if (cached != NULL)
    return gi_base_info_ref (cached);

  if (g_hash_table_contains (repository->unknown_gtypes, (gpointer)gtype))
    return NULL;

  gtype_name = g_type_name (gtype);

  /* Inside each typelib, we include the "C prefix" which acts as
   * a namespace mechanism.  For GtkTreeView, the C prefix is Gtk.
   * Given the assumption that GTypes for a library also use the
   * C prefix, we know we can skip examining a typelib if our
   * target type does not have this typelib's C prefix. Use this
   * assumption as our first attempt at locating the DirEntry.
   */
  entry = find_by_gtype (repository->ordered_typelibs, gtype_name, TRUE, &result_typelib);
  if (entry == NULL)
    entry = find_by_gtype (repository->ordered_lazy_typelibs, gtype_name, TRUE, &result_typelib);

  /* Not every class library necessarily specifies a correct c_prefix,
   * so take a second pass. This time we will try a global lookup,
   * ignoring prefixes.
   * See http://bugzilla.gnome.org/show_bug.cgi?id=564016
   */
  if (entry == NULL)
    entry = find_by_gtype (repository->ordered_typelibs, gtype_name, FALSE, &result_typelib);
  if (entry == NULL)
    entry = find_by_gtype (repository->ordered_lazy_typelibs, gtype_name, FALSE, &result_typelib);

  if (entry != NULL)
    {
      cached = gi_info_new_full (gi_typelib_blob_type_to_info_type (entry->blob_type),
                                 repository,
                                 NULL, result_typelib, entry->offset);

      g_hash_table_insert (repository->info_by_gtype,
                           (gpointer) gtype,
                           gi_base_info_ref (cached));
      return cached;
    }
  else
    {
      g_hash_table_add (repository->unknown_gtypes, (gpointer) gtype);
      return NULL;
    }
}

/**
 * gi_repository_find_by_name:
 * @repository: A #GIRepository
 * @namespace_: Namespace which will be searched
 * @name: Entry name to find
 *
 * Searches for a particular entry in a namespace.
 *
 * Before calling this function for a particular namespace, you must call
 * [method@GIRepository.Repository.require] to load the namespace, or otherwise
 * ensure the namespace has already been loaded.
 *
 * Returns: (transfer full) (nullable): [class@GIRepository.BaseInfo]
 *   representing metadata about @name, or `NULL` if none found
 * Since: 2.80
 */
GIBaseInfo *
gi_repository_find_by_name (GIRepository *repository,
                            const char   *namespace,
                            const char   *name)
{
  GITypelib *typelib;
  DirEntry *entry;

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);
  g_return_val_if_fail (namespace != NULL, NULL);

  typelib = get_registered (repository, namespace, NULL);
  g_return_val_if_fail (typelib != NULL, NULL);

  entry = gi_typelib_get_dir_entry_by_name (typelib, name);
  if (entry == NULL)
    return NULL;
  return gi_info_new_full (gi_typelib_blob_type_to_info_type (entry->blob_type),
                           repository,
                           NULL, typelib, entry->offset);
}

static DirEntry *
find_by_error_domain (GPtrArray  *ordered_typelibs,
                      GQuark      target_domain,
                      GITypelib **out_typelib)
{
  /* Search in reverse order as the longest namespaces will be listed last, and
   * those are the ones we want to search first. */
  for (guint i = ordered_typelibs->len; i > 0; i--)
    {
      GITypelib *typelib = g_ptr_array_index (ordered_typelibs, i - 1);
      DirEntry *entry;

      entry = gi_typelib_get_dir_entry_by_error_domain (typelib, target_domain);
      if (entry != NULL)
        {
          *out_typelib = typelib;
          return entry;
        }
    }

  return NULL;
}

/**
 * gi_repository_find_by_error_domain:
 * @repository: A #GIRepository
 * @domain: a [type@GLib.Error] domain
 *
 * Searches for the enum type corresponding to the given [type@GLib.Error]
 * domain.
 *
 * Before calling this function for a particular namespace, you must call
 * [method@GIRepository.Repository.require] to load the namespace, or otherwise
 * ensure the namespace has already been loaded.
 *
 * Returns: (transfer full) (nullable): [class@GIRepository.EnumInfo]
 *   representing metadata about @domain’s enum type, or `NULL` if none found
 * Since: 2.80
 */
GIEnumInfo *
gi_repository_find_by_error_domain (GIRepository *repository,
                                    GQuark        domain)
{
  GIEnumInfo *cached;
  DirEntry *result = NULL;
  GITypelib *result_typelib = NULL;

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);

  cached = g_hash_table_lookup (repository->info_by_error_domain,
                                GUINT_TO_POINTER (domain));

  if (cached != NULL)
    return (GIEnumInfo *) gi_base_info_ref ((GIBaseInfo *)cached);

  result = find_by_error_domain (repository->ordered_typelibs, domain, &result_typelib);
  if (result == NULL)
    result = find_by_error_domain (repository->ordered_lazy_typelibs, domain, &result_typelib);

  if (result != NULL)
    {
      cached = (GIEnumInfo *) gi_info_new_full (gi_typelib_blob_type_to_info_type (result->blob_type),
                                                repository,
                                                NULL, result_typelib, result->offset);

      g_hash_table_insert (repository->info_by_error_domain,
                           GUINT_TO_POINTER (domain),
                           gi_base_info_ref ((GIBaseInfo *) cached));
      return cached;
    }
  return NULL;
}

/**
 * gi_repository_get_object_gtype_interfaces:
 * @repository: a #GIRepository
 * @gtype: a [type@GObject.Type] whose fundamental type is `G_TYPE_OBJECT`
 * @n_interfaces_out: (out): Number of interfaces
 * @interfaces_out: (out) (transfer none) (array length=n_interfaces_out): Interfaces for @gtype
 *
 * Look up the implemented interfaces for @gtype.
 *
 * This function cannot fail per se; but for a totally ‘unknown’
 * [type@GObject.Type], it may return 0 implemented interfaces.
 *
 * The semantics of this function are designed for a dynamic binding,
 * where in certain cases (such as a function which returns an
 * interface which may have ‘hidden’ implementation classes), not all
 * data may be statically known, and will have to be determined from
 * the [type@GObject.Type] of the object.  An example is
 * [func@Gio.File.new_for_path] returning a concrete class of
 * `GLocalFile`, which is a [type@GObject.Type] we see at runtime, but
 * not statically.
 *
 * Since: 2.80
 */
void
gi_repository_get_object_gtype_interfaces (GIRepository      *repository,
                                           GType              gtype,
                                           size_t            *n_interfaces_out,
                                           GIInterfaceInfo ***interfaces_out)
{
  GTypeInterfaceCache *cache;

  g_return_if_fail (GI_IS_REPOSITORY (repository));
  g_return_if_fail (g_type_fundamental (gtype) == G_TYPE_OBJECT);

  cache = g_hash_table_lookup (repository->interfaces_for_gtype,
                               (void *) gtype);
  if (cache == NULL)
    {
      GType *interfaces;
      unsigned int i;
      unsigned int n_interfaces;
      GList *interface_infos = NULL, *iter;

      interfaces = g_type_interfaces (gtype, &n_interfaces);
      for (i = 0; i < n_interfaces; i++)
        {
          GIBaseInfo *base_info;

          base_info = gi_repository_find_by_gtype (repository, interfaces[i]);
          if (base_info == NULL)
            continue;

          if (gi_base_info_get_info_type (base_info) != GI_INFO_TYPE_INTERFACE)
            {
              /* FIXME - could this really happen? */
              gi_base_info_unref (base_info);
              continue;
            }

          if (!g_list_find (interface_infos, base_info))
            interface_infos = g_list_prepend (interface_infos, base_info);
        }

      cache = g_malloc (sizeof (GTypeInterfaceCache)
                        + sizeof (GIBaseInfo*) * g_list_length (interface_infos));
      cache->n_interfaces = g_list_length (interface_infos);
      for (iter = interface_infos, i = 0; iter; iter = iter->next, i++)
        cache->interfaces[i] = iter->data;
      g_list_free (interface_infos);

      g_hash_table_insert (repository->interfaces_for_gtype, (gpointer) gtype,
                           cache);

      g_free (interfaces);
    }

  *n_interfaces_out = cache->n_interfaces;
  *interfaces_out = (GIInterfaceInfo**)&cache->interfaces[0];
}

static void
collect_namespaces (GPtrArray  *ordered_typelibs,
                    char      **names,
                    size_t     *inout_i)
{
  for (guint j = 0; j < ordered_typelibs->len; j++)
    {
      GITypelib *typelib = g_ptr_array_index (ordered_typelibs, j);
      const char *namespace = gi_typelib_get_namespace (typelib);
      names[(*inout_i)++] = g_strdup (namespace);
    }
}

/**
 * gi_repository_get_loaded_namespaces:
 * @repository: A #GIRepository
 * @n_namespaces_out: (optional) (out): Return location for the number of
 *   namespaces
 *
 * Return the list of currently loaded namespaces.
 *
 * The list is guaranteed to be `NULL` terminated. The `NULL` terminator is not
 * counted in @n_namespaces_out.
 *
 * Returns: (element-type utf8) (transfer full) (array length=n_namespaces_out):
 *   list of namespaces
 * Since: 2.80
 */
char **
gi_repository_get_loaded_namespaces (GIRepository *repository,
                                     size_t       *n_namespaces_out)
{
  char **names;
  size_t i;
  size_t n_typelibs;

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);

  n_typelibs = repository->ordered_typelibs->len + repository->ordered_lazy_typelibs->len;
  names = g_malloc0 (sizeof (char *) * (n_typelibs + 1));
  i = 0;

  collect_namespaces (repository->ordered_typelibs, names, &i);
  collect_namespaces (repository->ordered_lazy_typelibs, names, &i);

  if (n_namespaces_out != NULL)
    *n_namespaces_out = i;

  return names;
}

/**
 * gi_repository_get_version:
 * @repository: A #GIRepository
 * @namespace_: Namespace to inspect
 *
 * This function returns the loaded version associated with the given
 * namespace @namespace_.
 *
 * Note: The namespace must have already been loaded using a function
 * such as [method@GIRepository.Repository.require] before calling this
 * function.
 *
 * Returns: Loaded version
 * Since: 2.80
 */
const char *
gi_repository_get_version (GIRepository *repository,
                           const char   *namespace)
{
  GITypelib *typelib;
  Header *header;

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);
  g_return_val_if_fail (namespace != NULL, NULL);

  typelib = get_registered (repository, namespace, NULL);

  g_return_val_if_fail (typelib != NULL, NULL);

  header = (Header *) typelib->data;
  return gi_typelib_get_string (typelib, header->nsversion);
}

/**
 * gi_repository_get_shared_libraries:
 * @repository: A #GIRepository
 * @namespace_: Namespace to inspect
 * @out_n_elements: (out) (optional): Return location for the number of elements
 *   in the returned array
 *
 * This function returns an array of paths to the
 * shared C libraries associated with the given namespace @namespace_.
 *
 * There may be no shared library path associated, in which case this
 * function will return `NULL`.
 *
 * Note: The namespace must have already been loaded using a function
 * such as [method@GIRepository.Repository.require] before calling this
 * function.
 *
 * The list is internal to [class@GIRepository.Repository] and should not be
 * freed, nor should its string elements.
 *
 * The list is guaranteed to be `NULL` terminated. The `NULL` terminator is not
 * counted in @out_n_elements.
 *
 * Returns: (nullable) (array length=out_n_elements) (transfer none): Array of
 *   paths to shared libraries, or `NULL` if none are associated
 * Since: 2.80
 */
const char * const *
gi_repository_get_shared_libraries (GIRepository *repository,
                                    const char   *namespace,
                                    size_t       *out_n_elements)
{
  GITypelib *typelib;
  Header *header;

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);
  g_return_val_if_fail (namespace != NULL, NULL);

  typelib = get_registered (repository, namespace, NULL);

  g_return_val_if_fail (typelib != NULL, NULL);

  header = (Header *) typelib->data;
  if (!header->shared_library)
    {
      if (out_n_elements != NULL)
        *out_n_elements = 0;
      return NULL;
    }

  /* Populate the cache. */
  if (repository->cached_shared_libraries == NULL)
    {
      const char *comma_separated = gi_typelib_get_string (typelib, header->shared_library);

      if (comma_separated != NULL && *comma_separated != '\0')
        {
          repository->cached_shared_libraries = g_strsplit (comma_separated, ",", -1);
          repository->cached_n_shared_libraries = g_strv_length (repository->cached_shared_libraries);
        }
    }

  if (out_n_elements != NULL)
    *out_n_elements = repository->cached_n_shared_libraries;

  return (const char * const *) repository->cached_shared_libraries;
}

/**
 * gi_repository_get_c_prefix:
 * @repository: A #GIRepository
 * @namespace_: Namespace to inspect
 *
 * This function returns the ‘C prefix’, or the C level namespace
 * associated with the given introspection namespace.
 *
 * Each C symbol starts with this prefix, as well each [type@GObject.Type] in
 * the library.
 *
 * Note: The namespace must have already been loaded using a function
 * such as [method@GIRepository.Repository.require] before calling this
 * function.
 *
 * Returns: (nullable): C namespace prefix, or `NULL` if none associated
 * Since: 2.80
 */
const char *
gi_repository_get_c_prefix (GIRepository *repository,
                            const char   *namespace_)
{
  GITypelib *typelib;
  Header *header;

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);
  g_return_val_if_fail (namespace_ != NULL, NULL);

  typelib = get_registered (repository, namespace_, NULL);

  g_return_val_if_fail (typelib != NULL, NULL);

  header = (Header *) typelib->data;
  if (header->c_prefix)
    return gi_typelib_get_string (typelib, header->c_prefix);
  else
    return NULL;
}

/**
 * gi_repository_get_typelib_path:
 * @repository: A #GIRepository
 * @namespace_: GI namespace to use, e.g. `Gtk`
 *
 * If namespace @namespace_ is loaded, return the full path to the
 * .typelib file it was loaded from.
 *
 * If the typelib for namespace @namespace_ was included in a shared library,
 * return the special string `<builtin>`.
 *
 * Returns: (type filename) (nullable): Filesystem path (or `<builtin>`) if
 *   successful, `NULL` if namespace is not loaded
 * Since: 2.80
 */
const char *
gi_repository_get_typelib_path (GIRepository *repository,
                                const char   *namespace)
{
  gpointer orig_key, value;

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);

  if (!g_hash_table_lookup_extended (repository->typelibs, namespace,
                                     &orig_key, &value))
    {
      if (!g_hash_table_lookup_extended (repository->lazy_typelibs, namespace,
                                         &orig_key, &value))

        return NULL;
    }
  return ((char*)orig_key) + strlen ((char *) orig_key) + 1;
}

/* This simple search function looks for a specified namespace-version;
   it's faster than the full directory listing required for latest version. */
static GMappedFile *
find_namespace_version (const char          *namespace,
                        const char          *version,
                        const char * const  *search_paths,
                        size_t               n_search_paths,
                        char               **path_ret)
{
  GError *error = NULL;
  GMappedFile *mfile = NULL;
  char *fname;

  if (g_str_equal (namespace, GIREPOSITORY_TYPELIB_NAME) &&
      !g_str_equal (version, GIREPOSITORY_TYPELIB_VERSION))
    {
      g_debug ("Ignoring %s-%s.typelib because this libgirepository "
               "corresponds to %s-%s",
               namespace, version,
               namespace, GIREPOSITORY_TYPELIB_VERSION);
      return NULL;
    }

  fname = g_strdup_printf ("%s-%s.typelib", namespace, version);

  for (size_t i = 0; i < n_search_paths; ++i)
    {
      char *path = g_build_filename (search_paths[i], fname, NULL);

      mfile = g_mapped_file_new (path, FALSE, &error);
      if (error)
        {
          g_free (path);
          g_clear_error (&error);
          continue;
        }
      *path_ret = path;
      break;
    }
  g_free (fname);
  return mfile;
}

static gboolean
parse_version (const char *version,
               int *major,
               int *minor)
{
  const char *dot;
  char *end;

  *major = strtol (version, &end, 10);
  dot = strchr (version, '.');
  if (dot == NULL)
    {
      *minor = 0;
      return TRUE;
    }
  if (dot != end)
    return FALSE;
  *minor = strtol (dot+1, &end, 10);
  if (end != (version + strlen (version)))
    return FALSE;
  return TRUE;
}

static int
compare_version (const char *v1,
                 const char *v2)
{
  gboolean success;
  int v1_major, v1_minor;
  int v2_major, v2_minor;

  success = parse_version (v1, &v1_major, &v1_minor);
  g_assert (success);

  success = parse_version (v2, &v2_major, &v2_minor);
  g_assert (success);

  /* Avoid a compiler warning about `success` being unused with G_DISABLE_ASSERT */
  (void) success;

  if (v1_major > v2_major)
    return 1;
  else if (v2_major > v1_major)
    return -1;
  else if (v1_minor > v2_minor)
    return 1;
  else if (v2_minor > v1_minor)
    return -1;
  return 0;
}

struct NamespaceVersionCandidadate
{
  GMappedFile *mfile;
  int path_index;
  char *path;
  char *version;
};

static int
compare_candidate_reverse (struct NamespaceVersionCandidadate *c1,
                           struct NamespaceVersionCandidadate *c2)
{
  int result = compare_version (c1->version, c2->version);
  /* First, check the version */
  if (result > 0)
    return -1;
  else if (result < 0)
    return 1;
  else
    {
      /* Now check the path index, which says how early in the search path
       * we found it.  This ensures that of equal version targets, we
       * pick the earlier one.
       */
      if (c1->path_index == c2->path_index)
        return 0;
      else if (c1->path_index > c2->path_index)
        return 1;
      else
        return -1;
    }
}

static void
free_candidate (struct NamespaceVersionCandidadate *candidate)
{
  g_mapped_file_unref (candidate->mfile);
  g_free (candidate->path);
  g_free (candidate->version);
  g_slice_free (struct NamespaceVersionCandidadate, candidate);
}

static GSList *
enumerate_namespace_versions (const char         *namespace,
                              const char * const *search_paths,
                              size_t              n_search_paths)
{
  GSList *candidates = NULL;
  GHashTable *found_versions = g_hash_table_new (g_str_hash, g_str_equal);
  char *namespace_dash;
  char *namespace_typelib;
  GError *error = NULL;
  int index;

  namespace_dash = g_strdup_printf ("%s-", namespace);
  namespace_typelib = g_strdup_printf ("%s.typelib", namespace);

  index = 0;
  for (size_t i = 0; i < n_search_paths; ++i)
    {
      GDir *dir;
      const char *dirname;
      const char *entry;

      dirname = search_paths[i];
      dir = g_dir_open (dirname, 0, NULL);
      if (dir == NULL)
        continue;
      while ((entry = g_dir_read_name (dir)) != NULL)
        {
          GMappedFile *mfile;
          char *path, *version;
          struct NamespaceVersionCandidadate *candidate;

          if (!g_str_has_suffix (entry, ".typelib"))
            continue;

          if (g_str_has_prefix (entry, namespace_dash))
            {
              const char *last_dash;
              const char *name_end;
              int major, minor;

              if (g_str_equal (namespace, GIREPOSITORY_TYPELIB_NAME) &&
                  !g_str_equal (entry, GIREPOSITORY_TYPELIB_FILENAME))
                {
                  g_debug ("Ignoring %s because this libgirepository "
                           "corresponds to %s",
                           entry, GIREPOSITORY_TYPELIB_FILENAME);
                  continue;
                }

              name_end = strrchr (entry, '.');
              last_dash = strrchr (entry, '-');

              /* These are guaranteed by the suffix and prefix checks above: */
              g_assert (name_end != NULL);
              g_assert (last_dash != NULL);

              version = g_strndup (last_dash + 1, (size_t) (name_end - (last_dash + 1u)));
              if (!parse_version (version, &major, &minor))
                {
                  g_free (version);
                  continue;
                }
            }
          else
            continue;

          if (g_hash_table_lookup (found_versions, version) != NULL)
            {
              g_free (version);
              continue;
            }

          path = g_build_filename (dirname, entry, NULL);
          mfile = g_mapped_file_new (path, FALSE, &error);
          if (mfile == NULL)
            {
              g_free (path);
              g_free (version);
              g_clear_error (&error);
              continue;
            }
          candidate = g_slice_new0 (struct NamespaceVersionCandidadate);
          candidate->mfile = mfile;
          candidate->path_index = index;
          candidate->path = path;
          candidate->version = version;
          candidates = g_slist_prepend (candidates, candidate);
          g_hash_table_add (found_versions, version);
        }
      g_dir_close (dir);
      index++;
    }

  g_free (namespace_dash);
  g_free (namespace_typelib);
  g_hash_table_destroy (found_versions);

  return candidates;
}

static GMappedFile *
find_namespace_latest (const char          *namespace,
                       const char * const  *search_paths,
                       size_t               n_search_paths,
                       char               **version_ret,
                       char               **path_ret)
{
  GSList *candidates;
  GMappedFile *result = NULL;

  *version_ret = NULL;
  *path_ret = NULL;

  candidates = enumerate_namespace_versions (namespace, search_paths, n_search_paths);

  if (candidates != NULL)
    {
      struct NamespaceVersionCandidadate *elected;
      candidates = g_slist_sort (candidates, (GCompareFunc) compare_candidate_reverse);

      elected = (struct NamespaceVersionCandidadate *) candidates->data;
      /* Remove the elected one so we don't try to free its contents */
      candidates = g_slist_delete_link (candidates, candidates);

      result = elected->mfile;
      *path_ret = elected->path;
      *version_ret = elected->version;
      g_slice_free (struct NamespaceVersionCandidadate, elected); /* just free the container */
      g_slist_foreach (candidates, (GFunc) (void *) free_candidate, NULL);
      g_slist_free (candidates);
    }
  return result;
}

/**
 * gi_repository_enumerate_versions:
 * @repository: A #GIRepository
 * @namespace_: GI namespace, e.g. `Gtk`
 * @n_versions_out: (optional) (out): The number of versions returned.
 *
 * Obtain an unordered list of versions (either currently loaded or
 * available) for @namespace_ in this @repository.
 *
 * The list is guaranteed to be `NULL` terminated. The `NULL` terminator is not
 * counted in @n_versions_out.
 *
 * Returns: (element-type utf8) (transfer full) (array length=n_versions_out): the array of versions.
 * Since: 2.80
 */
char **
gi_repository_enumerate_versions (GIRepository *repository,
                                  const char   *namespace_,
                                  size_t       *n_versions_out)
{
  GPtrArray *versions;
  GSList *candidates, *link;
  const char *loaded_version;
  char **ret;

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);

  candidates = enumerate_namespace_versions (namespace_,
                                             (const char * const *) repository->typelib_search_path->pdata,
                                             repository->typelib_search_path->len);

  if (!candidates)
    {
      if (n_versions_out)
        *n_versions_out = 0;
      return g_strdupv ((char *[]) {NULL});
    }

  versions = g_ptr_array_new_null_terminated (1, g_free, TRUE);
  for (link = candidates; link; link = link->next)
    {
      struct NamespaceVersionCandidadate *candidate = link->data;
      g_ptr_array_add (versions, g_steal_pointer (&candidate->version));
      free_candidate (candidate);
    }
  g_slist_free (candidates);

  /* The currently loaded version of a namespace is also part of the
   * available versions, as it could have been loaded using
   * require_private().
   */
  if (gi_repository_is_registered (repository, namespace_, NULL))
    {
      loaded_version = gi_repository_get_version (repository, namespace_);
      if (loaded_version &&
          !g_ptr_array_find_with_equal_func (versions, loaded_version, g_str_equal, NULL))
        g_ptr_array_add (versions, g_strdup (loaded_version));
    }

  ret = (char **) g_ptr_array_steal (versions, n_versions_out);
  g_ptr_array_unref (g_steal_pointer (&versions));

  return ret;
}

static GITypelib *
require_internal (GIRepository           *repository,
                  const char             *namespace,
                  const char             *version,
                  GIRepositoryLoadFlags   flags,
                  const char * const     *search_paths,
                  size_t                  n_search_paths,
                  GError                **error)
{
  GMappedFile *mfile;
  GITypelib *ret = NULL;
  Header *header;
  GITypelib *typelib = NULL;
  GITypelib *typelib_owned = NULL;
  const char *typelib_namespace, *typelib_version;
  gboolean allow_lazy = (flags & GI_REPOSITORY_LOAD_FLAG_LAZY) > 0;
  gboolean is_lazy;
  char *version_conflict = NULL;
  char *path = NULL;
  char *tmp_version = NULL;

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);
  g_return_val_if_fail (namespace != NULL, NULL);

  typelib = get_registered_status (repository, namespace, version, allow_lazy,
                                   &is_lazy, &version_conflict);
  if (typelib)
    return typelib;

  if (version_conflict != NULL)
    {
      g_set_error (error, GI_REPOSITORY_ERROR,
                   GI_REPOSITORY_ERROR_NAMESPACE_VERSION_CONFLICT,
                   "Requiring namespace '%s' version '%s', but '%s' is already loaded",
                   namespace, version, version_conflict);
      return NULL;
    }

  if (version != NULL)
    {
      mfile = find_namespace_version (namespace, version, search_paths,
                                      n_search_paths, &path);
      tmp_version = g_strdup (version);
    }
  else
    {
      mfile = find_namespace_latest (namespace, search_paths, n_search_paths,
                                     &tmp_version, &path);
    }

  if (mfile == NULL)
    {
      if (version != NULL)
        g_set_error (error, GI_REPOSITORY_ERROR,
                     GI_REPOSITORY_ERROR_TYPELIB_NOT_FOUND,
                     "Typelib file for namespace '%s', version '%s' not found",
                     namespace, version);
      else
        g_set_error (error, GI_REPOSITORY_ERROR,
                     GI_REPOSITORY_ERROR_TYPELIB_NOT_FOUND,
                     "Typelib file for namespace '%s' (any version) not found",
                     namespace);
      goto out;
    }

  {
    GError *temp_error = NULL;
    GBytes *bytes = NULL;

    bytes = g_mapped_file_get_bytes (mfile);
    typelib_owned = typelib = gi_typelib_new_from_bytes (bytes, &temp_error);
    g_bytes_unref (bytes);
    g_clear_pointer (&mfile, g_mapped_file_unref);

    if (!typelib)
      {
        g_set_error (error, GI_REPOSITORY_ERROR,
                     GI_REPOSITORY_ERROR_TYPELIB_NOT_FOUND,
                     "Failed to load typelib file '%s' for namespace '%s': %s",
                     path, namespace, temp_error->message);
        g_clear_error (&temp_error);
        goto out;
      }

    typelib->library_paths = (repository->library_paths != NULL) ? g_ptr_array_ref (repository->library_paths) : NULL;
  }
  header = (Header *) typelib->data;
  typelib_namespace = gi_typelib_get_string (typelib, header->namespace);
  typelib_version = gi_typelib_get_string (typelib, header->nsversion);

  if (strcmp (typelib_namespace, namespace) != 0)
    {
      g_set_error (error, GI_REPOSITORY_ERROR,
                   GI_REPOSITORY_ERROR_NAMESPACE_MISMATCH,
                   "Typelib file %s for namespace '%s' contains "
                   "namespace '%s' which doesn't match the file name",
                   path, namespace, typelib_namespace);
      goto out;
    }
  if (version != NULL && strcmp (typelib_version, version) != 0)
    {
      g_set_error (error, GI_REPOSITORY_ERROR,
                   GI_REPOSITORY_ERROR_NAMESPACE_MISMATCH,
                   "Typelib file %s for namespace '%s' contains "
                   "version '%s' which doesn't match the expected version '%s'",
                   path, namespace, typelib_version, version);
      goto out;
    }

  if (!register_internal (repository, path, allow_lazy,
                          typelib, error))
    goto out;
  ret = typelib;
 out:
  g_clear_pointer (&typelib_owned, gi_typelib_unref);
  g_free (tmp_version);
  g_free (path);
  return ret;
}

static GITypelib *
require_internal_with_platform_data (GIRepository           *repository,
                                     const char             *namespace,
                                     const char             *version,
                                     GIRepositoryLoadFlags   flags,
                                     const char * const     *search_paths,
                                     size_t                  search_paths_len,
                                     GError                **error)
{
  GITypelib *typelib;

  typelib = require_internal (repository, namespace, version, flags,
                              search_paths, search_paths_len,
                              error);
  if (!typelib)
    return NULL;

#if defined (G_OS_UNIX) || defined (G_OS_WIN32)
  /* Backward compatibility hack: if we're loading Gio-2.0, we automatically
   * load the platform specific introspection data that used to exist inside
   * Gio-2.0
   */
  if (g_str_equal (namespace, "Gio") &&
      (!version || g_str_equal (version, "2.0")))
    {
      GError *local_error = NULL;
      const char *platform_namespace;

#  if defined (G_OS_UNIX)
      platform_namespace = "GioUnix";
#  elif defined (G_OS_WIN32)
      platform_namespace = "GioWin32";
#  endif /* defined (G_OS_LINUX) */

      if (!require_internal (repository, platform_namespace, version, flags,
                             search_paths, search_paths_len,
                             &local_error))
        {
          g_critical ("Unable to load platform-specific GIO introspection data: %s",
                      local_error->message);
          g_error_free (local_error);
        }
    }
#endif /* defined(G_OS_UNIX) || defined(G_OS_WIN32) */

  return typelib;
}

/**
 * gi_repository_require:
 * @repository: A #GIRepository
 * @namespace_: GI namespace to use, e.g. `Gtk`
 * @version: (nullable): Version of namespace, may be `NULL` for latest
 * @flags: Set of [flags@GIRepository.RepositoryLoadFlags], may be 0
 * @error: a [type@GLib.Error].
 *
 * Force the namespace @namespace_ to be loaded if it isn’t already.
 *
 * If @namespace_ is not loaded, this function will search for a
 * `.typelib` file using the repository search path.  In addition, a
 * version @version of namespace may be specified.  If @version is
 * not specified, the latest will be used.
 *
 * Returns: (transfer none): a pointer to the [type@GIRepository.Typelib] if
 *   successful, `NULL` otherwise
 * Since: 2.80
 */
GITypelib *
gi_repository_require (GIRepository           *repository,
                       const char             *namespace,
                       const char             *version,
                       GIRepositoryLoadFlags   flags,
                       GError                **error)
{
  const char * const *search_paths;
  size_t search_paths_len;

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);
  g_return_val_if_fail (namespace != NULL, NULL);

  search_paths = (const char * const *) repository->typelib_search_path->pdata;
  search_paths_len = repository->typelib_search_path->len;

  return require_internal_with_platform_data (repository, namespace, version, flags,
                                              search_paths, search_paths_len,
                                              error);
}

/**
 * gi_repository_require_private:
 * @repository: A #GIRepository
 * @typelib_dir: (type filename): Private directory where to find the requested
 *   typelib
 * @namespace_: GI namespace to use, e.g. `Gtk`
 * @version: (nullable): Version of namespace, may be `NULL` for latest
 * @flags: Set of [flags@GIRepository.RepositoryLoadFlags], may be 0
 * @error: a [type@GLib.Error].
 *
 * Force the namespace @namespace_ to be loaded if it isn’t already.
 *
 * If @namespace_ is not loaded, this function will search for a
 * `.typelib` file within the private directory only. In addition, a
 * version @version of namespace should be specified.  If @version is
 * not specified, the latest will be used.
 *
 * Returns: (transfer none): a pointer to the [type@GIRepository.Typelib] if
 *   successful, `NULL` otherwise
 * Since: 2.80
 */
GITypelib *
gi_repository_require_private (GIRepository           *repository,
                               const char             *typelib_dir,
                               const char             *namespace,
                               const char             *version,
                               GIRepositoryLoadFlags   flags,
                               GError                **error)
{
  const char * const search_path[] = { typelib_dir, NULL };

  g_return_val_if_fail (GI_IS_REPOSITORY (repository), NULL);
  g_return_val_if_fail (namespace != NULL, NULL);

  return require_internal_with_platform_data (repository, namespace, version, flags,
                                              search_path, 1,
                                              error);
}

static gboolean
gi_repository_introspect_cb (const char *option_name,
                             const char *value,
                             gpointer data,
                             GError **error)
{
  GError *tmp_error = NULL;
  char **args;

  args = g_strsplit (value, ",", 2);

  if (!gi_repository_dump (args[0], args[1], &tmp_error))
    {
      g_error ("Failed to extract GType data: %s",
               tmp_error->message);
      exit (1);
    }
  exit (0);
}

static const GOptionEntry introspection_args[] = {
  { "introspect-dump", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_CALLBACK,
    gi_repository_introspect_cb, "Dump introspection information",
    "infile.txt,outfile.xml" },
  G_OPTION_ENTRY_NULL
};

/**
 * gi_repository_get_option_group:
 *
 * Obtain the option group for girepository.
 *
 * It’s used by the dumper and for programs that want to provide introspection
 * information
 *
 * Returns: (transfer full): the option group
 * Since: 2.80
 */
GOptionGroup *
gi_repository_get_option_group (void)
{
  GOptionGroup *group;
  group = g_option_group_new ("girepository", "Introspection Options", "Show Introspection Options", NULL, NULL);

  g_option_group_add_entries (group, introspection_args);
  return group;
}

GQuark
gi_repository_error_quark (void)
{
  static GQuark quark = 0;
  if (quark == 0)
    quark = g_quark_from_static_string ("g-irepository-error-quark");
  return quark;
}

/**
 * gi_type_tag_to_string:
 * @type: the type_tag
 *
 * Obtain a string representation of @type
 *
 * Returns: the string
 * Since: 2.80
 */
const char *
gi_type_tag_to_string (GITypeTag type)
{
  switch (type)
    {
    case GI_TYPE_TAG_VOID:
      return "void";
    case GI_TYPE_TAG_BOOLEAN:
      return "gboolean";
    case GI_TYPE_TAG_INT8:
      return "gint8";
    case GI_TYPE_TAG_UINT8:
      return "guint8";
    case GI_TYPE_TAG_INT16:
      return "gint16";
    case GI_TYPE_TAG_UINT16:
      return "guint16";
    case GI_TYPE_TAG_INT32:
      return "gint32";
    case GI_TYPE_TAG_UINT32:
      return "guint32";
    case GI_TYPE_TAG_INT64:
      return "gint64";
    case GI_TYPE_TAG_UINT64:
      return "guint64";
    case GI_TYPE_TAG_FLOAT:
      return "gfloat";
    case GI_TYPE_TAG_DOUBLE:
      return "gdouble";
    case GI_TYPE_TAG_UNICHAR:
      return "gunichar";
    case GI_TYPE_TAG_GTYPE:
      return "GType";
    case GI_TYPE_TAG_UTF8:
      return "utf8";
    case GI_TYPE_TAG_FILENAME:
      return "filename";
    case GI_TYPE_TAG_ARRAY:
      return "array";
    case GI_TYPE_TAG_INTERFACE:
      return "interface";
    case GI_TYPE_TAG_GLIST:
      return "glist";
    case GI_TYPE_TAG_GSLIST:
      return "gslist";
    case GI_TYPE_TAG_GHASH:
      return "ghash";
    case GI_TYPE_TAG_ERROR:
      return "error";
    default:
      return "unknown";
    }
}

/**
 * gi_info_type_to_string:
 * @type: the info type
 *
 * Obtain a string representation of @type
 *
 * Returns: the string
 * Since: 2.80
 */
const char *
gi_info_type_to_string (GIInfoType type)
{
  switch (type)
    {
    case GI_INFO_TYPE_INVALID:
      return "invalid";
    case GI_INFO_TYPE_FUNCTION:
      return "function";
    case GI_INFO_TYPE_CALLBACK:
      return "callback";
    case GI_INFO_TYPE_STRUCT:
      return "struct";
    case GI_INFO_TYPE_ENUM:
      return "enum";
    case GI_INFO_TYPE_FLAGS:
      return "flags";
    case GI_INFO_TYPE_OBJECT:
      return "object";
    case GI_INFO_TYPE_INTERFACE:
      return "interface";
    case GI_INFO_TYPE_CONSTANT:
      return "constant";
    case GI_INFO_TYPE_UNION:
      return "union";
    case GI_INFO_TYPE_VALUE:
      return "value";
    case GI_INFO_TYPE_SIGNAL:
      return "signal";
    case GI_INFO_TYPE_VFUNC:
      return "vfunc";
    case GI_INFO_TYPE_PROPERTY:
      return "property";
    case GI_INFO_TYPE_FIELD:
      return "field";
    case GI_INFO_TYPE_ARG:
      return "arg";
    case GI_INFO_TYPE_TYPE:
      return "type";
    case GI_INFO_TYPE_UNRESOLVED:
      return "unresolved";
    default:
      return "unknown";
  }
}

GIInfoType
gi_typelib_blob_type_to_info_type (GITypelibBlobType blob_type)
{
  switch (blob_type)
    {
    case BLOB_TYPE_BOXED:
      /* `BLOB_TYPE_BOXED` now always refers to a `StructBlob`, and
       * `GIRegisteredTypeInfo` (the parent type of `GIStructInfo`) has a method
       * for distinguishing whether the struct is a boxed type. So presenting
       * `BLOB_TYPE_BOXED` as its own `GIBaseInfo` subclass is not helpful.
       * See commit e28078c70cbf4a57c7dbd39626f43f9bd2674145 and
       * https://gitlab.gnome.org/GNOME/glib/-/issues/3245. */
      return GI_INFO_TYPE_STRUCT;
    default:
      return (GIInfoType) blob_type;
    }
}

/**
 * gi_repository_dup_default:
 *
 * Gets the singleton process-global default `GIRepository`.
 *
 * The singleton is needed for situations where you must coordinate between
 * bindings and libraries which also need to interact with introspection which
 * could affect the bindings. For example, a Python application using a
 * GObject-based library through `GIRepository` to load plugins also written in
 * Python.
 *
 * Returns: (transfer full): the global singleton repository
 *
 * Since: 2.86
 */
GIRepository *
gi_repository_dup_default (void)
{
  static GIRepository *instance;

  if (g_once_init_enter (&instance))
    {
      GIRepository *repository = gi_repository_new ();
      g_object_add_weak_pointer (G_OBJECT (repository), (gpointer *)&instance);
      g_once_init_leave (&instance, repository);
    }

  return g_object_ref (instance);
}