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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <string.h>
#include <vector>

#include <cppuhelper/exc_hlp.hxx>
#include <cppuhelper/weak.hxx>
#include <cppuhelper/implbase.hxx>
#include <cppuhelper/supportsservice.hxx>
#include <comphelper/sequence.hxx>
#include <rtl/ustring.hxx>

#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/loader/XImplementationLoader.hpp>
#include <com/sun/star/registry/XImplementationRegistration2.hpp>
#include <com/sun/star/container/XHierarchicalNameAccess.hpp>
#include <com/sun/star/reflection/XServiceTypeDescription.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>

#include "mergekeys.hxx"

#if defined(_WIN32)
#include <io.h>
#endif


using namespace com::sun::star;
using namespace css::uno;
using namespace css::loader;
using namespace css::beans;
using namespace css::lang;
using namespace css::registry;
using namespace cppu;
using namespace osl;

namespace {

static constexpr OUStringLiteral slash_UNO_slash_REGISTRY_LINKS
        = "/UNO/REGISTRY_LINKS";
static constexpr OUStringLiteral slash_IMPLEMENTATIONS
        =  "/IMPLEMENTATIONS";
static constexpr OUStringLiteral slash_UNO
        = "/UNO";
static constexpr OUStringLiteral slash_UNO_slash_SERVICES
        = "/UNO/SERVICES";
static constexpr OUStringLiteral slash_UNO_slash_SINGLETONS
        = "/UNO/SINGLETONS";
static constexpr OUStringLiteral slash_SERVICES
        = "/SERVICES/";
static constexpr OUStringLiteral slash_UNO_slash_LOCATION
        = "/UNO/LOCATION";
static constexpr OUStringLiteral slash_UNO_slash_ACTIVATOR
        = "/UNO/ACTIVATOR";
static constexpr OUStringLiteral colon_old
        = ":old";
static constexpr OUStringLiteral com_sun_star_registry_SimpleRegistry
        = "com.sun.star.registry.SimpleRegistry";
static constexpr OUStringLiteral Registry
        = "Registry";

//  static deleteAllLinkReferences()

void deleteAllLinkReferences(const Reference < XSimpleRegistry >& xReg,
                                    const Reference < XRegistryKey >& xSource)
    // throw ( InvalidRegistryException, RuntimeException )
{
    Reference < XRegistryKey > xKey = xSource->openKey(
        slash_UNO_slash_REGISTRY_LINKS );

    if (!(xKey.is() && (xKey->getValueType() == RegistryValueType_ASCIILIST)))
        return;

    const Sequence<OUString> linkNames = xKey->getAsciiListValue();

    if (!linkNames.hasElements())
        return;

    OUString            aLinkName;
    OUString            aLinkParent;
    Reference < XRegistryKey >  xLinkParent;
    const sal_Unicode*  pTmpName = nullptr;
    const sal_Unicode*  pShortName = nullptr;
    sal_Int32           sEnd = 0;

    for (const OUString& rLinkName : linkNames)
    {
        aLinkName = rLinkName;

        pTmpName = aLinkName.getStr();

        if (pTmpName[0] != L'/')
            continue;

        sal_Int32 nIndex = rtl_ustr_indexOfChar( pTmpName, '%' );
        if ( nIndex == -1 )
            pShortName = nullptr;
        else
            pShortName = pTmpName+nIndex;

        while (pShortName && pShortName[1] == L'%')
        {
            nIndex = rtl_ustr_indexOfChar( pShortName+2, '%' );
            if ( nIndex == -1 )
                pShortName = nullptr;
            else
                pShortName += nIndex+2;
        }

        if (pShortName)
        {
            aLinkName = aLinkName.copy(0, pShortName - pTmpName);
        }

        xReg->getRootKey()->deleteLink(aLinkName);

        sEnd = aLinkName.lastIndexOf( '/' );

        aLinkParent = aLinkName.copy(0, sEnd);

        while(!aLinkParent.isEmpty())
        {
            xLinkParent = xReg->getRootKey()->openKey(aLinkParent);

            if (xLinkParent.is() && !xLinkParent->getKeyNames().hasElements())
            {
                aLinkName = aLinkParent;

                xReg->getRootKey()->deleteKey(aLinkParent);

                sEnd = aLinkName.lastIndexOf( '/' );

                aLinkParent = aLinkName.copy(0, sEnd);
            }
            else
            {
                break;
            }
        }
    }
}


//  static prepareLink

void prepareLink( const Reference < XSimpleRegistry > & xDest,
                         const Reference < XRegistryKey > & xSource,
                         const OUString& link)
    // throw ( InvalidRegistryException, RuntimeException )
{
    OUString linkRefName = xSource->getKeyName();
    OUString linkName(link);
    bool    isRelativ = false;

    const sal_Unicode*  pTmpName = link.getStr();
    const sal_Unicode*  pShortName;
    sal_Int32           nIndex = rtl_ustr_indexOfChar( pTmpName, '%' );
    if ( nIndex == -1 )
        pShortName = nullptr;
    else
        pShortName = pTmpName+nIndex;

    if (pTmpName[0] != L'/')
        isRelativ = true;

    while (pShortName && pShortName[1] == L'%')
    {
        nIndex = rtl_ustr_indexOfChar( pShortName+2, '%' );
        if ( nIndex == -1 )
            pShortName = nullptr;
        else
            pShortName += nIndex+2;
    }

    if (pShortName)
    {
        linkRefName += link.copy(pShortName - pTmpName + 1);
        linkName = link.copy(0, pShortName - pTmpName);
    }

    if (isRelativ)
        xSource->createLink(linkName, linkRefName);
    else
        xDest->getRootKey()->createLink(linkName, linkRefName);
}


//  static searchImplForLink

OUString searchImplForLink(
    const Reference < XRegistryKey > & xRootKey,
    const OUString& linkName,
    const OUString& implName )
    // throw ( InvalidRegistryException, RuntimeException )
{
    Reference < XRegistryKey > xKey = xRootKey->openKey( slash_IMPLEMENTATIONS );
    if (xKey.is())
    {
        const Sequence< Reference < XRegistryKey > > subKeys( xKey->openKeys() );
        OUString key_name( slash_UNO + linkName );

        for (const Reference < XRegistryKey >& xImplKey : subKeys)
        {
            try
            {
                if (xImplKey->getKeyType( key_name ) == RegistryKeyType_LINK)
                {
                    OUString oldImplName = xImplKey->getKeyName().copy(strlen("/IMPLEMENTATIONS/"));
                    if (implName != oldImplName)
                    {
                        return oldImplName;
                    }
                }
            }
            catch(InvalidRegistryException&)
            {
            }
        }
    }

    return OUString();
}


//  static searchLinkTargetForImpl

OUString searchLinkTargetForImpl(const Reference < XRegistryKey >& xRootKey,
                                        const OUString& linkName,
                                        const OUString& implName)
{
    Reference < XRegistryKey > xKey = xRootKey->openKey( slash_IMPLEMENTATIONS );

    if (xKey.is())
    {
        Sequence< Reference < XRegistryKey > > subKeys = xKey->openKeys();

        OUString qualifiedLinkName( slash_UNO + linkName );

        auto pSubKey = std::find_if(subKeys.begin(), subKeys.end(),
            [&implName, &qualifiedLinkName](const Reference<XRegistryKey>& rSubKey) {
                OUString tmpImplName = rSubKey->getKeyName().copy(strlen("/IMPLEMENTATIONS/"));
                return tmpImplName == implName
                    && rSubKey->getKeyType( qualifiedLinkName ) == RegistryKeyType_LINK;
            });
        if (pSubKey != subKeys.end())
            return (*pSubKey)->getLinkTarget( qualifiedLinkName );
    }

    return OUString();
}


//  static createUniqueSubEntry

void createUniqueSubEntry(const Reference < XRegistryKey > & xSuperKey,
                                 const OUString& value)
    // throw ( InvalidRegistryException, RuntimeException )
{
    if (!xSuperKey.is())
        return;

    if (xSuperKey->getValueType() == RegistryValueType_ASCIILIST)
    {
        Sequence<OUString> implEntries = xSuperKey->getAsciiListValue();
        sal_Int32 length = implEntries.getLength();

        bool bReady = comphelper::findValue(implEntries, value) != -1;

        if (bReady)
        {
            Sequence<OUString> implEntriesNew(length);
            implEntriesNew.getArray()[0] = value;

            std::copy_if(implEntries.begin(), implEntries.end(), std::next(implEntriesNew.begin()),
                [&value](const OUString& rEntry) { return rEntry != value; });
            xSuperKey->setAsciiListValue(implEntriesNew);
        } else
        {
            Sequence<OUString> implEntriesNew(length+1);
            implEntriesNew.getArray()[0] = value;

            std::copy(implEntries.begin(), implEntries.end(), std::next(implEntriesNew.begin()));
            xSuperKey->setAsciiListValue(implEntriesNew);
        }
    } else
    {
        Sequence<OUString> implEntriesNew { value };

        xSuperKey->setAsciiListValue(implEntriesNew);
    }
}


//  static deleteSubEntry

bool deleteSubEntry(const Reference < XRegistryKey >& xSuperKey, const OUString& value)
    // throw ( InvalidRegistryException, RuntimeException )
{
    if (xSuperKey->getValueType() == RegistryValueType_ASCIILIST)
    {
        Sequence<OUString> implEntries = xSuperKey->getAsciiListValue();
        sal_Int32 length = implEntries.getLength();
        sal_Int32 equals = static_cast<sal_Int32>(std::count(implEntries.begin(), implEntries.end(), value));
        bool hasNoImplementations = false;

        if (equals == length)
        {
            hasNoImplementations = true;
        } else
        {
            Sequence<OUString> implEntriesNew(length - equals);

            std::copy_if(implEntries.begin(), implEntries.end(), implEntriesNew.begin(),
                [&value](const OUString& rEntry) { return rEntry != value; });
            xSuperKey->setAsciiListValue(implEntriesNew);
        }

        if (hasNoImplementations)
        {
            return true;
        }
    }
    return false;
}


//  static prepareUserLink

void prepareUserLink(const Reference < XSimpleRegistry >& xDest,
                                const OUString& linkName,
                                const OUString& linkTarget,
                                const OUString& implName)
{
    Reference < XRegistryKey > xRootKey = xDest->getRootKey();

    if (xRootKey->getKeyType(linkName) == RegistryKeyType_LINK)
    {
        OUString oldImplName(searchImplForLink(xRootKey, linkName, implName));

        if (!oldImplName.isEmpty())
        {
            createUniqueSubEntry(xDest->getRootKey()->createKey(
                linkName + colon_old ), oldImplName);
        }
    }

    if (xRootKey->isValid())
        xRootKey->createLink(linkName, linkTarget);
}


//  static deleteUserLink

void deletePathIfPossible(const Reference < XRegistryKey >& xRootKey,
                                 const OUString& path)
{
    try
    {
        Sequence<OUString> keyNames(xRootKey->openKey(path)->getKeyNames());

        if (!keyNames.hasElements() &&
            xRootKey->openKey(path)->getValueType() == RegistryValueType_NOT_DEFINED)
        {
            xRootKey->deleteKey(path);

            OUString newPath = path.copy(0, path.lastIndexOf('/'));

            if (newPath.getLength() > 1)
                deletePathIfPossible(xRootKey, newPath);
        }
    }
    catch(InvalidRegistryException&)
    {
    }
}


//  static deleteUserLink

void deleteUserLink(const Reference < XRegistryKey >& xRootKey,
                               const OUString& linkName,
                               const OUString& linkTarget,
                               const OUString& implName)
    // throw ( InvalidRegistryException, RuntimeException )
{
    bool bClean = false;

    if (xRootKey->getKeyType(linkName) == RegistryKeyType_LINK)
    {
        OUString tmpTarget = xRootKey->getLinkTarget(linkName);

        if (tmpTarget == linkTarget)
        {
            xRootKey->deleteLink(linkName);
        }
    }

    Reference < XRegistryKey > xOldKey = xRootKey->openKey(
        linkName + colon_old );
    if (xOldKey.is())
    {
        if (xOldKey->getValueType() == RegistryValueType_ASCIILIST)
        {
            Sequence<OUString> implEntries = xOldKey->getAsciiListValue();
            sal_Int32 length = implEntries.getLength();
            sal_Int32 equals = static_cast<sal_Int32>(std::count(implEntries.begin(), implEntries.end(), implName));
            bool hasNoImplementations = false;

            if (equals == length)
            {
                hasNoImplementations = true;
            } else
            {
                OUString oldImpl;

                if (length > equals + 1)
                {
                    Sequence<OUString> implEntriesNew(length - equals - 1);

                    sal_Int32 j = 0;
                    bool first = true;
                    for (sal_Int32 i = 0; i < length; i++)
                    {
                        if (implEntries.getConstArray()[i] != implName)
                        {
                            if (first)
                            {
                                oldImpl = implEntries.getConstArray()[i];
                                first = false;
                            } else
                            {
                                implEntriesNew.getArray()[j++] = implEntries.getConstArray()[i];
                            }
                        }
                    }

                    xOldKey->setAsciiListValue(implEntriesNew);
                } else
                {
                    oldImpl = implEntries.getConstArray()[0];
                    OUString path(xOldKey->getKeyName());
                    xOldKey->closeKey();
                    xRootKey->deleteKey(path);
                }

                OUString oldTarget = searchLinkTargetForImpl(xRootKey, linkName, oldImpl);
                if (!oldTarget.isEmpty())
                {
                    xRootKey->createLink(linkName, oldTarget);
                }
            }

            if (hasNoImplementations)
            {
                bClean = true;
                OUString path(xOldKey->getKeyName());
                xOldKey->closeKey();
                xRootKey->deleteKey(path);
            }
        }
    } else
    {
        bClean = true;
    }

    if (bClean)
    {
        OUString path = linkName.copy(0, linkName.lastIndexOf('/'));
        deletePathIfPossible(xRootKey, path);
    }
}


//  static prepareUserKeys

void prepareUserKeys(const Reference < XSimpleRegistry >& xDest,
                                const Reference < XRegistryKey >& xUnoKey,
                                const Reference < XRegistryKey >& xKey,
                                const OUString& implName,
                                bool bRegister)
{
    bool hasSubKeys = false;

    Sequence<OUString> keyNames = xKey->getKeyNames();

    OUString relativKey;
    if (keyNames.hasElements())
        relativKey = keyNames.getConstArray()[0].copy(xKey->getKeyName().getLength()+1);

    if (keyNames.getLength() == 1 &&
        xKey->getKeyType(relativKey) == RegistryKeyType_LINK)
    {
        hasSubKeys = true;

        OUString linkTarget = xKey->getLinkTarget(relativKey);
        OUString linkName(xKey->getKeyName().copy(xUnoKey->getKeyName().getLength()));

        linkName += "/" + relativKey;

        if (bRegister)
        {
            prepareUserLink(xDest, linkName, linkTarget, implName);
        } else
        {
            deleteUserLink(xDest->getRootKey(), linkName, linkTarget, implName);
        }
    } else
    {
        const Sequence< Reference < XRegistryKey> > subKeys = xKey->openKeys();

        if (subKeys.hasElements())
        {
            hasSubKeys = true;

            for (const Reference < XRegistryKey > & rSubKey : subKeys)
            {
                prepareUserKeys(xDest, xUnoKey, rSubKey, implName, bRegister);
            }
        }
    }

    if (hasSubKeys)
        return;

    OUString keyName(xKey->getKeyName().copy(xUnoKey->getKeyName().getLength()));

    Reference < XRegistryKey > xRootKey = xDest->getRootKey();
    if (bRegister)
    {
        createUniqueSubEntry(xRootKey->createKey(keyName), implName);
    }
    else
    {
        Reference< XRegistryKey > rKey = xRootKey->openKey(keyName);
        if( rKey.is() )
        {
            deleteSubEntry(rKey, implName);
            xRootKey->deleteKey(keyName);
        }

        OUString path = keyName.copy(0, keyName.lastIndexOf('/'));
        if( !path.isEmpty() )
        {
            deletePathIfPossible(xRootKey, path);
        }
    }
}


//  static deleteAllImplementations

void deleteAllImplementations(   const Reference < XSimpleRegistry >& xReg,
                                        const Reference < XRegistryKey >& xSource,
                                        const OUString& locationUrl,
                                        std::vector<OUString> & implNames)
    // throw (InvalidRegistryException, RuntimeException)
{
    Sequence < Reference < XRegistryKey > > subKeys = xSource->openKeys();

    if (subKeys.hasElements())
    {
        bool hasLocationUrl = false;

        for (const Reference < XRegistryKey> & xImplKey : std::as_const(subKeys))
        {
            Reference < XRegistryKey > xKey = xImplKey->openKey(
                slash_UNO_slash_LOCATION );

            if (xKey.is() && (xKey->getValueType() == RegistryValueType_ASCII))
            {
                if (xKey->getAsciiValue() == locationUrl)
                {
                    hasLocationUrl = true;

                    OUString implName(xImplKey->getKeyName().copy(1));
                    sal_Int32 firstDot = implName.indexOf('/');

                    if (firstDot >= 0)
                        implName = implName.copy(firstDot + 1);

                    implNames.push_back(implName);

                    deleteAllLinkReferences(xReg, xImplKey);

                    xKey = xImplKey->openKey( slash_UNO );
                    if (xKey.is())
                    {
                        const Sequence< Reference < XRegistryKey > > subKeys2 = xKey->openKeys();

                        for (const Reference < XRegistryKey > & rSubKey2 : subKeys2)
                        {
                            if (rSubKey2->getKeyName() != (xImplKey->getKeyName() + slash_UNO_slash_SERVICES ) &&
                                rSubKey2->getKeyName() != (xImplKey->getKeyName() + slash_UNO_slash_REGISTRY_LINKS ) &&
                                rSubKey2->getKeyName() != (xImplKey->getKeyName() + slash_UNO_slash_ACTIVATOR ) &&
                                rSubKey2->getKeyName() != (xImplKey->getKeyName() + slash_UNO_slash_SINGLETONS ) &&
                                rSubKey2->getKeyName() != (xImplKey->getKeyName() + slash_UNO_slash_LOCATION) )
                            {
                                prepareUserKeys(xReg, xKey, rSubKey2, implName, false);
                            }
                        }
                    }
                }
            }

            if (hasLocationUrl)
            {
                hasLocationUrl = false;
                OUString path(xImplKey->getKeyName());
                xImplKey->closeKey();
                xReg->getRootKey()->deleteKey(path);
            }
        }

        subKeys = xSource->openKeys();
        if (!subKeys.hasElements())
        {
            OUString path(xSource->getKeyName());
            xSource->closeKey();
            xReg->getRootKey()->deleteKey(path);
        }
    } else
    {
        OUString path(xSource->getKeyName());
        xSource->closeKey();
        xReg->getRootKey()->deleteKey(path);
    }
}


void delete_all_singleton_entries(
    Reference < registry::XRegistryKey > const & xSingletons_section,
    ::std::vector< OUString > const & impl_names )
    // throw (InvalidRegistryException, RuntimeException)
{
    Sequence< Reference< registry::XRegistryKey > > singletons( xSingletons_section->openKeys() );
    Reference< registry::XRegistryKey > const * subkeys = singletons.getConstArray();
    for ( sal_Int32 nPos = singletons.getLength(); nPos--; )
    {
        Reference< registry::XRegistryKey > const & xSingleton = subkeys[ nPos ];
        Reference< registry::XRegistryKey > xRegisteredImplNames(
            xSingleton->openKey( "REGISTERED_BY" ) );
        if (xRegisteredImplNames.is() && xRegisteredImplNames->isValid())
        {
            Sequence< OUString > registered_implnames;
            try
            {
                registered_implnames = xRegisteredImplNames->getAsciiListValue();
            }
            catch (registry::InvalidValueException &)
            {
            }
            OUString const * p = registered_implnames.getConstArray();
            sal_Int32 nOrigRegLength = registered_implnames.getLength();
            sal_Int32 nNewLength = nOrigRegLength;
            for ( sal_Int32 n = nOrigRegLength; n--; )
            {
                OUString const & registered_implname = p[ n ];

                for (auto const& impl_name : impl_names)
                {
                    if (impl_name == registered_implname)
                    {
                        registered_implnames[ n ] = p[ nNewLength -1 ];
                        --nNewLength;
                    }
                }
            }

            if (nNewLength != nOrigRegLength)
            {
                if (0 == nNewLength)
                {
                    // remove whole entry
                    xRegisteredImplNames->closeKey();
                    xSingleton->deleteKey( "REGISTERED_BY" );
                    // registry key cannot provide its relative name, only absolute :(
                    OUString abs( xSingleton->getKeyName() );
                    xSingletons_section->deleteKey( abs.copy( abs.lastIndexOf( '/' ) +1 ) );
                }
                else
                {
                    registered_implnames.realloc( nNewLength );
                    xRegisteredImplNames->setAsciiListValue( registered_implnames );
                }
            }
        }
    }
}


//  static deleteAllServiceEntries

void deleteAllServiceEntries(    const Reference < XSimpleRegistry >& xReg,
                                        const Reference < XRegistryKey >& xSource,
                                        const OUString& implName)
    // throw ( InvalidRegistryException, RuntimeException )
{
    Sequence< Reference < XRegistryKey > > subKeys = xSource->openKeys();

    if (subKeys.hasElements())
    {
        bool hasNoImplementations = false;

        for (const Reference < XRegistryKey > & xServiceKey : std::as_const(subKeys))
        {
            if (xServiceKey->getValueType() == RegistryValueType_ASCIILIST)
            {
                Sequence<OUString> implEntries = xServiceKey->getAsciiListValue();
                sal_Int32 length = implEntries.getLength();
                sal_Int32 equals = static_cast<sal_Int32>(std::count(implEntries.begin(), implEntries.end(), implName));

                if (equals == length)
                {
                    hasNoImplementations = true;
                } else
                {
                    if (equals > 0)
                    {
                        Sequence<OUString> implEntriesNew(length-equals);

                        std::copy_if(implEntries.begin(), implEntries.end(), implEntriesNew.begin(),
                            [&implName](const OUString& rEntry) { return rEntry != implName; });

                        xServiceKey->setAsciiListValue(implEntriesNew);
                    }
                }
            }

            if (hasNoImplementations)
            {
                hasNoImplementations = false;
                OUString path(xServiceKey->getKeyName());
                xServiceKey->closeKey();
                xReg->getRootKey()->deleteKey(path);
            }
        }

        subKeys = xSource->openKeys();
        if (!subKeys.hasElements())
        {
            OUString path(xSource->getKeyName());
            xSource->closeKey();
            xReg->getRootKey()->deleteKey(path);
        }
    } else
    {
        OUString path(xSource->getKeyName());
        xSource->closeKey();
        xReg->getRootKey()->deleteKey(path);
    }
}


bool is_supported_service(
    OUString const & service_name,
    Reference< reflection::XServiceTypeDescription > const & xService_td )
{
    if (xService_td->getName() == service_name)
        return true;
    Sequence< Reference< reflection::XServiceTypeDescription > > seq(
        xService_td->getMandatoryServices() );
    return std::any_of(seq.begin(), seq.end(), [&service_name](const auto& rService) {
        return is_supported_service( service_name, rService ); });
}


void insert_singletons(
    Reference< registry::XSimpleRegistry > const & xDest,
    Reference< registry::XRegistryKey > const & xImplKey,
    Reference< XComponentContext > const & xContext )
    // throw( registry::InvalidRegistryException, registry::CannotRegisterImplementationException, RuntimeException )
{
    // singletons
    Reference< registry::XRegistryKey > xKey( xImplKey->openKey( "UNO/SINGLETONS" ) );
    if (!(xKey.is() && xKey->isValid()))
        return;

    OUString implname( xImplKey->getKeyName().copy( sizeof ("/IMPLEMENTATIONS/") -1 ) );
    // singleton entries
    Sequence< Reference< registry::XRegistryKey > > xSingletons_section( xKey->openKeys() );
    Reference< registry::XRegistryKey > const * p = xSingletons_section.getConstArray();
    for ( sal_Int32 nPos = xSingletons_section.getLength(); nPos--; )
    {
        Reference< registry::XRegistryKey > const & xSingleton = p[ nPos ];
        OUString singleton_name(
            xSingleton->getKeyName().copy(
                implname.getLength() + sizeof ("/IMPLEMENTATIONS//UNO/SINGLETONS/") -1 ) );
        OUString service_name( xSingleton->getStringValue() );

        OUString keyname( "/SINGLETONS/" + singleton_name );
        Reference< registry::XRegistryKey > xKey2( xDest->getRootKey()->openKey( keyname ) );
        if (xKey2.is() && xKey2->isValid())
        {
            try
            {
                OUString existing_name( xKey2->getStringValue() );
                if ( existing_name != service_name )
                {
                    Reference< container::XHierarchicalNameAccess > xTDMgr;
                    OUString the_tdmgr =
                        "/singletons/com.sun.star.reflection.theTypeDescriptionManager";
                    xContext->getValueByName( the_tdmgr ) >>= xTDMgr;
                    if (! xTDMgr.is())
                    {
                        throw RuntimeException( "cannot get singleton " + the_tdmgr );
                    }
                    try
                    {
                        Reference< reflection::XServiceTypeDescription > xExistingService_td;
                        xTDMgr->getByHierarchicalName( existing_name ) >>= xExistingService_td;
                        if (! xExistingService_td.is())
                        {
                            throw RuntimeException( "cannot get service type description: " + existing_name );
                        }

                        // everything's fine if existing service entry supports the one
                        // to be registered
                        if (! is_supported_service( service_name, xExistingService_td ))
                        {
                            throw registry::CannotRegisterImplementationException(
                                "existing singleton service (" + singleton_name + "=" + existing_name + ") "
                                " does not support given one: " + service_name);
                        }
                    }
                    catch (const container::NoSuchElementException & exc)
                    {
                        css::uno::Any anyEx = cppu::getCaughtException();
                        throw css::lang::WrappedTargetRuntimeException(
                                "cannot get service type description: " + exc.Message,
                                nullptr, anyEx );
                    }
                }
            }
            catch (registry::InvalidValueException &)
            {
                // repair
                xKey2->setStringValue( service_name );
            }
        }
        else
        {
            // insert singleton entry
            xKey2 = xDest->getRootKey()->createKey( keyname );
            xKey2->setStringValue( service_name );
        }

        Reference< registry::XRegistryKey > xRegisteredImplNames(
            xKey2->openKey( "REGISTERED_BY" ) );
        if (!xRegisteredImplNames.is() || !xRegisteredImplNames->isValid())
        {
            // create
            xRegisteredImplNames = xKey2->createKey( "REGISTERED_BY" );
        }

        Sequence< OUString > implnames;
        try
        {
            implnames = xRegisteredImplNames->getAsciiListValue();
        }
        catch (registry::InvalidValueException &)
        {
        }
        // check implname is already in
        if (comphelper::findValue(implnames, implname) == -1)
        {
            // append and write back
            implnames.realloc( implnames.getLength() +1 );
            implnames[ implnames.getLength() -1 ] = implname;
            xRegisteredImplNames->setAsciiListValue( implnames );
        }
    }
}


//  static prepareRegistry

void prepareRegistry(
    const Reference < XSimpleRegistry >& xDest,
    const Reference < XRegistryKey >& xSource,
    const OUString& implementationLoaderUrl,
    const OUString& locationUrl,
    Reference< XComponentContext > const & xContext )
    // throw ( InvalidRegistryException, CannotRegisterImplementationException, RuntimeException )
{
    const Sequence< Reference < XRegistryKey > > subKeys = xSource->openKeys();

    if (!subKeys.hasElements())
    {
        throw InvalidRegistryException(
            "prepareRegistry(): source registry is empty" );
    }

    for (const Reference < XRegistryKey >& xImplKey : subKeys)
    {
        Reference < XRegistryKey >  xKey = xImplKey->openKey(
            slash_UNO_slash_SERVICES );

        if (xKey.is())
        {
            // update entries in SERVICES section
            const Sequence< Reference < XRegistryKey > > serviceKeys = xKey->openKeys();

            OUString implName = xImplKey->getKeyName().copy(1);
            sal_Int32 firstDot = implName.indexOf('/');

            if (firstDot >= 0)
                implName = implName.copy(firstDot + 1);

            sal_Int32 offset = xKey->getKeyName().getLength() + 1;

            for (const Reference < XRegistryKey >& rServiceKey : serviceKeys)
            {
                OUString serviceName = rServiceKey->getKeyName().copy(offset);

                createUniqueSubEntry(
                    xDest->getRootKey()->createKey(
                        slash_SERVICES + serviceName ),
                    implName);
            }

            xKey = xImplKey->openKey( slash_UNO );
            if (xKey.is())
            {
                const Sequence< Reference < XRegistryKey > > subKeys2 = xKey->openKeys();

                for (const Reference < XRegistryKey >& rSubKey2 : subKeys2)
                {
                    if (rSubKey2->getKeyName() != (xImplKey->getKeyName() + slash_UNO_slash_SERVICES) &&
                        rSubKey2->getKeyName() != (xImplKey->getKeyName() + slash_UNO_slash_REGISTRY_LINKS ) &&
                        rSubKey2->getKeyName() != (xImplKey->getKeyName() + slash_UNO_slash_SINGLETONS ))
                    {
                        prepareUserKeys(xDest, xKey, rSubKey2, implName, true);
                    }
                }
            }
        }

        // update LOCATION entry
        xKey = xImplKey->createKey( slash_UNO_slash_LOCATION );

        if (xKey.is())
        {
            xKey->setAsciiValue(locationUrl);
        }

        // update ACTIVATOR entry
        xKey = xImplKey->createKey( slash_UNO_slash_ACTIVATOR );

        if (xKey.is())
        {
            xKey->setAsciiValue(implementationLoaderUrl);
        }

        xKey = xImplKey->openKey( slash_UNO_slash_SERVICES );

        if (xKey.is() && (xKey->getValueType() == RegistryValueType_ASCIILIST))
        {
            // update link entries in REGISTRY_LINKS section
            const Sequence<OUString> linkNames = xKey->getAsciiListValue();

            for (const OUString& rLinkName : linkNames)
            {
                prepareLink(xDest, xImplKey, rLinkName);
            }
        }

        insert_singletons( xDest, xImplKey, xContext );
    }
}


void findImplementations(    const Reference < XRegistryKey > & xSource,
                                    std::vector<OUString>& implNames)
{
    bool isImplKey = false;

    try
    {
        Reference < XRegistryKey > xKey = xSource->openKey(
            slash_UNO_slash_SERVICES );

        if (xKey.is() && xKey->getKeyNames().hasElements())
        {
            isImplKey = true;

            OUString implName = xSource->getKeyName().copy(1).replace('/', '.');
            sal_Int32 firstDot = implName.indexOf('.');

            if (firstDot >= 0)
                implName = implName.copy(firstDot + 1);

            implNames.push_back(implName);
        }
    }
    catch(InvalidRegistryException&)
    {
    }

    if (isImplKey) return;

    try
    {
        const Sequence< Reference < XRegistryKey > > subKeys = xSource->openKeys();

        for (const Reference < XRegistryKey >& rSubKey : subKeys)
        {
            findImplementations(rSubKey, implNames);
        }
    }
    catch(InvalidRegistryException&)
    {
    }
}


class ImplementationRegistration
    : public WeakImplHelper< XImplementationRegistration2, XServiceInfo, XInitialization >
{
public:
    explicit ImplementationRegistration( const Reference < XComponentContext > & rSMgr );

    // XServiceInfo
    OUString                        SAL_CALL getImplementationName() override;
    sal_Bool                        SAL_CALL supportsService(const OUString& ServiceName) override;
    Sequence< OUString >            SAL_CALL getSupportedServiceNames() override;

    // XImplementationRegistration
    virtual void SAL_CALL registerImplementation(
        const OUString& implementationLoader,
        const OUString& location,
        const Reference < XSimpleRegistry > & xReg) override;

    virtual sal_Bool SAL_CALL revokeImplementation(
        const OUString& location,
        const Reference < XSimpleRegistry >& xReg) override;

    virtual Sequence< OUString > SAL_CALL getImplementations(
        const OUString& implementationLoader,
        const OUString& location) override;
    virtual Sequence< OUString > SAL_CALL checkInstantiation(
        const OUString& implementationName) override;

    // XImplementationRegistration2
    virtual void SAL_CALL registerImplementationWithLocation(
        const OUString& implementationLoader,
        const OUString& location,
        const OUString& registeredLocation,
        const Reference < XSimpleRegistry > & xReg) override;

    // XInitialization
    virtual void SAL_CALL initialize(
        const css::uno::Sequence< css::uno::Any >& aArguments ) override;

private: // helper methods
    void prepareRegister(
        const OUString& implementationLoader,
        const OUString& location,
        const OUString& registeredLocation,
        const Reference < XSimpleRegistry > & xReg);
    // throw( CannotRegisterImplementationException, RuntimeException )

    static void doRegister( const Reference < XMultiComponentFactory >& xSMgr,
                            const Reference < XComponentContext > &xCtx,
                            const Reference < XImplementationLoader >& xAct,
                            const Reference < XSimpleRegistry >& xDest,
                            const OUString& implementationLoaderUrl,
                            const OUString& locationUrl,
                            const OUString& registeredLocationUrl);
        /* throw ( InvalidRegistryException,
                   MergeConflictException,
                   CannotRegisterImplementationException, RuntimeException ) */

    static void doRevoke( const Reference < XSimpleRegistry >& xDest,
                          const OUString& locationUrl );
        // throw( InvalidRegistryException, RuntimeException )
    Reference< XSimpleRegistry > getRegistryFromServiceManager() const;

    static Reference< XSimpleRegistry > createTemporarySimpleRegistry(
        const Reference< XMultiComponentFactory > &rSMgr,
        const Reference < XComponentContext > & rCtx );

private: // members
    Reference < XMultiComponentFactory >    m_xSMgr;
    Reference < XComponentContext >         m_xCtx;
};


// ImplementationRegistration()

ImplementationRegistration::ImplementationRegistration( const Reference < XComponentContext > & xCtx )
    : m_xSMgr( xCtx->getServiceManager() )
    , m_xCtx( xCtx )
{}

// XServiceInfo
OUString ImplementationRegistration::getImplementationName()
{
    return "com.sun.star.comp.stoc.ImplementationRegistration";
}

// XServiceInfo
sal_Bool ImplementationRegistration::supportsService(const OUString& ServiceName)
{
    return cppu::supportsService(this, ServiceName);
}

// XServiceInfo
Sequence< OUString > ImplementationRegistration::getSupportedServiceNames()
{
    return { "com.sun.star.registry.ImplementationRegistration" };
}

Reference< XSimpleRegistry > ImplementationRegistration::getRegistryFromServiceManager() const
{
    Reference < XPropertySet > xPropSet( m_xSMgr, UNO_QUERY );
    Reference < XSimpleRegistry > xRegistry;

    if( xPropSet.is() ) {

        try {  // the implementation does not support XIntrospectionAccess !

            Any aAny = xPropSet->getPropertyValue( Registry );

            if( aAny.getValueType().getTypeClass() == TypeClass_INTERFACE ) {
                aAny >>= xRegistry;
            }
         }
         catch( UnknownPropertyException & ) {
             // empty reference is error signal !
        }
    }

    return xRegistry;
}


// XInitialization

void ImplementationRegistration::initialize(
    const css::uno::Sequence< css::uno::Any >& aArgs )
{

    if( aArgs.getLength() != 4 ) {
        throw IllegalArgumentException(
            "ImplementationRegistration::initialize() expects 4 parameters, got "  + OUString::number( aArgs.getLength() ),
            Reference<XInterface > (), 0 );
    }

    Reference< XImplementationLoader > rLoader;
    OUString loaderServiceName;
    OUString locationUrl;
    Reference< XSimpleRegistry > rReg;

    // 1st argument : An instance of an implementation loader
    if( aArgs.getConstArray()[0].getValueType().getTypeClass() == TypeClass_INTERFACE ) {
        aArgs.getConstArray()[0] >>= rLoader;
    }
    if( !rLoader.is()) {
        throw IllegalArgumentException(
            "ImplementationRegistration::initialize() invalid first parameter,"
            "expected " + cppu::UnoType<decltype(rLoader)>::get().getTypeName() +
            ", got " + aArgs.getConstArray()[0].getValueTypeName(),
            Reference< XInterface > (), 0 );
    }

    // 2nd argument : The service name of the loader. This name is written into the registry
    if( aArgs.getConstArray()[1].getValueType().getTypeClass() == TypeClass_STRING ) {
        aArgs.getConstArray()[1] >>= loaderServiceName;
    }
    if( loaderServiceName.isEmpty() ) {
        throw IllegalArgumentException(
            "ImplementationRegistration::initialize() invalid second parameter,"
            "expected string, got " + aArgs.getConstArray()[1].getValueTypeName(),
            Reference< XInterface > (), 0 );
    }

    // 3rd argument : The file name of the dll, that contains the loader
    if( aArgs.getConstArray()[2].getValueType().getTypeClass() == TypeClass_STRING ) {
        aArgs.getConstArray()[2] >>= locationUrl;
    }
    if( locationUrl.isEmpty() ) {
        throw IllegalArgumentException(
            "ImplementationRegistration::initialize() invalid third parameter,"
            "expected string, got " + aArgs.getConstArray()[2].getValueTypeName(),
            Reference< XInterface > (), 0 );
    }

    // 4th argument : The registry, the service should be written to
    if( aArgs.getConstArray()[3].getValueType().getTypeClass() == TypeClass_INTERFACE ) {
        aArgs.getConstArray()[3] >>= rReg;
    }

    if( !rReg.is() ) {
        rReg = getRegistryFromServiceManager();
        if( !rReg.is() ) {
            throw IllegalArgumentException(
                "ImplementationRegistration::initialize() invalid fourth parameter,"
                "expected " + cppu::UnoType<decltype(rReg)>::get().getTypeName() +
                ", got " + aArgs.getConstArray()[3].getValueTypeName(),
                Reference< XInterface > (), 0 );
        }
    }

    doRegister(m_xSMgr, m_xCtx, rLoader , rReg, loaderServiceName , locationUrl, locationUrl);
}


// virtual function registerImplementationWithLocation of XImplementationRegistration2

void ImplementationRegistration::registerImplementationWithLocation(<--- The function 'registerImplementationWithLocation' is never used.
    const OUString& implementationLoaderUrl,
    const OUString& locationUrl,
    const OUString& registeredLocationUrl,
    const Reference < XSimpleRegistry > & xReg)
{
    prepareRegister(
        implementationLoaderUrl, locationUrl, registeredLocationUrl, xReg);
}

// helper function
void ImplementationRegistration::prepareRegister(
    const OUString& implementationLoaderUrl,
    const OUString& locationUrl,
    const OUString& registeredLocationUrl,
    const Reference < XSimpleRegistry > & xReg)
    // throw( CannotRegisterImplementationException, RuntimeException )
{
    OUString activatorName;

    if (!implementationLoaderUrl.isEmpty())
    {
        activatorName = implementationLoaderUrl.getToken(0, ':');
    } else
    {
        // check locationUrl to find out what kind of loader is needed
        // set implLoaderUrl
    }

    if( !m_xSMgr.is() )    {
        throw CannotRegisterImplementationException(
                "ImplementationRegistration::registerImplementation() "
                "no componentcontext available to instantiate loader" );
    }

    try
    {
        Reference < XImplementationLoader > xAct(
            m_xSMgr->createInstanceWithContext(activatorName, m_xCtx) , UNO_QUERY );
        if (!xAct.is())
        {
            throw CannotRegisterImplementationException(
                "ImplementationRegistration::registerImplementation() - The service "
                + activatorName + " cannot be instantiated" );
        }

        Reference < XSimpleRegistry > xRegistry;

        if (xReg.is())
        {
            // registry supplied by user
            xRegistry = xReg;
        }
        else
        {
            xRegistry = getRegistryFromServiceManager();
        }

        if ( xRegistry.is())
        {
            doRegister(m_xSMgr, m_xCtx, xAct, xRegistry, implementationLoaderUrl,
                       locationUrl, registeredLocationUrl);
        }

    }
    catch( CannotRegisterImplementationException & )
    {
        throw;
    }
    catch( const InvalidRegistryException & e )
    {
        throw CannotRegisterImplementationException(
            "ImplementationRegistration::registerImplementation() "
            "InvalidRegistryException during registration (" + e.Message + ")" );
    }
    catch( const MergeConflictException & e )
    {
        throw CannotRegisterImplementationException(
            "ImplementationRegistration::registerImplementation() "
            "MergeConflictException during registration (" + e.Message + ")" );
    }

}


// virtual function registerImplementation of XImplementationRegistration

void ImplementationRegistration::registerImplementation(
    const OUString& implementationLoaderUrl,
    const OUString& locationUrl,
    const Reference < XSimpleRegistry > & xReg)
{
    prepareRegister(implementationLoaderUrl, locationUrl, locationUrl, xReg);
}


// virtual function revokeImplementation of XImplementationRegistration

sal_Bool ImplementationRegistration::revokeImplementation(const OUString& location,
                                                      const Reference < XSimpleRegistry >& xReg)
{
    bool ret = false;

    Reference < XSimpleRegistry > xRegistry;

    if (xReg.is()) {
        xRegistry = xReg;
    }
    else {
        Reference < XPropertySet > xPropSet( m_xSMgr, UNO_QUERY );
        if( xPropSet.is() ) {
            try {
                Any aAny = xPropSet->getPropertyValue( Registry );

                if( aAny.getValueType().getTypeClass() == TypeClass_INTERFACE )
                {
                    aAny >>= xRegistry;
                }
            }
            catch ( UnknownPropertyException & ) {
            }
        }
    }

    if (xRegistry.is())
    {
        try
        {
            doRevoke(xRegistry, location);
            ret = true;
        }
        catch( InvalidRegistryException & )
        {
            // no way to transport the error, as no exception is specified and a runtime
            // exception is not appropriate.
            OSL_FAIL( "InvalidRegistryException during revokeImplementation" );
        }
    }

    return ret;
}


// virtual function getImplementations of XImplementationRegistration

Sequence< OUString > ImplementationRegistration::getImplementations(
    const OUString & implementationLoaderUrl,
    const OUString & locationUrl)
{
    OUString activatorName;

    if (!implementationLoaderUrl.isEmpty())
    {
        activatorName = implementationLoaderUrl.getToken(0, ':');
    } else
    {
        // check locationUrl to find out what kind of loader is needed
        // set implementationLoaderUrl
    }

    if( m_xSMgr.is() ) {

        Reference < XImplementationLoader > xAct(
            m_xSMgr->createInstanceWithContext( activatorName, m_xCtx ), UNO_QUERY );

        if (xAct.is())
        {

            Reference < XSimpleRegistry > xReg =
                createTemporarySimpleRegistry( m_xSMgr, m_xCtx);

            if (xReg.is())
            {
                try
                {
                    xReg->open(OUString() /* in mem */, false, true);
                    Reference < XRegistryKey > xImpl;

                    { // only necessary for deleting the temporary variable of rootkey
                        xImpl = xReg->getRootKey()->createKey( slash_IMPLEMENTATIONS );
                    }
                    if (xAct->writeRegistryInfo(xImpl, implementationLoaderUrl, locationUrl))
                    {
                        std::vector<OUString> implNames;

                        findImplementations(xImpl, implNames);

                        if (!implNames.empty())
                        {
                            Sequence<OUString> seqImpl(comphelper::containerToSequence(implNames));
                            xImpl->closeKey();
                            return seqImpl;
                        }
                    }

                    xImpl->closeKey();
                }
                catch(MergeConflictException&)
                {
                }
                catch(InvalidRegistryException&)
                {
                }
            }
        }
    }

    return Sequence<OUString>();
}


// virtual function checkInstantiation of XImplementationRegistration

Sequence< OUString > ImplementationRegistration::checkInstantiation(const OUString&)<--- The function 'checkInstantiation' is never used.
{
    OSL_FAIL( "ImplementationRegistration::checkInstantiation not implemented" );
    return Sequence<OUString>();
}


// helper function doRegistration


void ImplementationRegistration::doRevoke(
    const Reference < XSimpleRegistry >& xDest,
    const OUString& locationUrl)
    // throw ( InvalidRegistryException, RuntimeException )
{
    if( !xDest.is() )
        return;

    std::vector<OUString> aNames;

    Reference < XRegistryKey > xRootKey( xDest->getRootKey() );

    Reference < XRegistryKey > xKey =
        xRootKey->openKey( slash_IMPLEMENTATIONS );
    if (xKey.is() && xKey->isValid())
    {
        deleteAllImplementations(xDest, xKey, locationUrl, aNames);
    }

    xKey = xRootKey->openKey( slash_SERVICES );
    if (xKey.is())
    {
        for (auto const& name : aNames)
        {
            deleteAllServiceEntries(xDest, xKey, name);
        }
    }

    xKey = xRootKey->openKey( "/SINGLETONS" );
    if (xKey.is() && xKey->isValid())
    {
        delete_all_singleton_entries( xKey, aNames );
    }

    if (xRootKey.is())
        xRootKey->closeKey();
    if (xKey.is() && xKey->isValid() )
        xKey->closeKey();
}

void ImplementationRegistration::doRegister(
    const Reference< XMultiComponentFactory > & xSMgr,
    const Reference< XComponentContext > &xCtx,
    const Reference < XImplementationLoader > & xAct,
    const Reference < XSimpleRegistry >& xDest,
    const OUString& implementationLoaderUrl,
    const OUString& locationUrl,
    const OUString& registeredLocationUrl)
    /* throw ( InvalidRegistryException,
               MergeConflictException,
               CannotRegisterImplementationException, RuntimeException ) */
{
    Reference < XSimpleRegistry >   xReg =
        createTemporarySimpleRegistry( xSMgr, xCtx );
    Reference < XRegistryKey >      xSourceKey;

    if (!(xAct.is() && xReg.is() && xDest.is()))
        return;

    try
    {
        xReg->open(OUString() /* in mem */, false, true);

        { // only necessary for deleting the temporary variable of rootkey
            xSourceKey = xReg->getRootKey()->createKey( slash_IMPLEMENTATIONS );
        }

        bool bSuccess =
            xAct->writeRegistryInfo(xSourceKey, implementationLoaderUrl, locationUrl);
        if ( !bSuccess )
        {
            throw CannotRegisterImplementationException(
                "ImplementationRegistration::doRegistration() component registration signaled failure" );
        }

        prepareRegistry(xDest, xSourceKey, implementationLoaderUrl, registeredLocationUrl, xCtx);

        xSourceKey->closeKey();

        xSourceKey = xReg->getRootKey();
        Reference < XRegistryKey > xDestKey = xDest->getRootKey();
        stoc_impreg::mergeKeys( xDestKey, xSourceKey );
        xDestKey->closeKey();
        xSourceKey->closeKey();


        // Cleanup Source registry.
        if ( xSourceKey->isValid() )
            xSourceKey->closeKey();
    }
    catch(CannotRegisterImplementationException&)
    {
        if ( xSourceKey->isValid() )
            xSourceKey->closeKey();
        // and throw again
        throw;
    }
}


Reference< XSimpleRegistry > ImplementationRegistration::createTemporarySimpleRegistry(
    const Reference< XMultiComponentFactory > &rSMgr,
    const Reference < XComponentContext > & xCtx)
{

    Reference < XSimpleRegistry > xReg(
        rSMgr->createInstanceWithContext(
            com_sun_star_registry_SimpleRegistry,   xCtx ),
        UNO_QUERY);
    OSL_ASSERT( xReg.is() );
    return xReg;
}

}

extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface *
com_sun_star_comp_stoc_ImplementationRegistration_get_implementation(<--- The function 'com_sun_star_comp_stoc_ImplementationRegistration_get_implementation' is never used.
    css::uno::XComponentContext *context,
    css::uno::Sequence<css::uno::Any> const &)
{
    return cppu::acquire(new ImplementationRegistration(context));
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */