summaryrefslogtreecommitdiffstats
path: root/configmgr/source/components.cxx
blob: 3c35a258c12c2d4f4bbc5de5dd6702aba0a60973 (plain)
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
/* -*- 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 <sal/config.h>

#include <cassert>
#include <chrono>
#include <utility>
#include <vector>
#include <set>

#include <com/sun/star/beans/Optional.hpp>
#include <com/sun/star/beans/UnknownPropertyException.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/NoSuchElementException.hpp>
#include <com/sun/star/lang/WrappedTargetException.hpp>
#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/uno/XInterface.hpp>
#include <cppuhelper/exc_hlp.hxx>
#include <config_dconf.h>
#include <config_folders.h>
#include <osl/conditn.hxx>
#include <osl/file.hxx>
#include <osl/mutex.hxx>
#include <rtl/bootstrap.hxx>
#include <rtl/ref.hxx>
#include <rtl/ustrbuf.hxx>
#include <rtl/ustring.hxx>
#include <sal/log.hxx>
#include <sal/types.h>
#include <salhelper/thread.hxx>
#include <comphelper/diagnose_ex.hxx>
#include <comphelper/backupfilehelper.hxx>
#include <o3tl/string_view.hxx>

#include "additions.hxx"
#include "components.hxx"
#include "data.hxx"
#include "lock.hxx"
#include "modifications.hxx"
#include "node.hxx"
#include "nodemap.hxx"
#include "parsemanager.hxx"
#include "partial.hxx"
#include "rootaccess.hxx"
#include "writemodfile.hxx"
#include "xcdparser.hxx"
#include "xcuparser.hxx"
#include "xcsparser.hxx"

#if ENABLE_DCONF
#include "dconf.hxx"
#endif

#if defined(_WIN32)
#include "winreg.hxx"
#endif

namespace configmgr {

namespace {

struct UnresolvedVectorItem {
    OUString name;
    rtl::Reference< ParseManager > manager;

    UnresolvedVectorItem(
        OUString  theName,
        rtl::Reference< ParseManager > theManager):
        name(std::move(theName)), manager(std::move(theManager)) {}
};

typedef std::vector< UnresolvedVectorItem > UnresolvedVector;

void parseXcsFile(
    OUString const & url, int layer, Data & data, Partial const * partial,
    Modifications * modifications, Additions * additions)
{
    assert(partial == nullptr && modifications == nullptr && additions == nullptr);
    (void) partial; (void) modifications; (void) additions;
    bool ok = rtl::Reference< ParseManager >(
        new ParseManager(url, new XcsParser(layer, data)))->parse(nullptr);
    assert(ok);
    (void) ok; // avoid warnings
}

void parseXcuFile(
    OUString const & url, int layer, Data & data, Partial const * partial,
    Modifications * modifications, Additions * additions)
{
    bool ok = rtl::Reference< ParseManager >(
        new ParseManager(
            url,
            new XcuParser(layer, data, partial, modifications, additions)))->
        parse(nullptr);
    assert(ok);
    (void) ok; // avoid warnings
}

OUString expand(OUString const & str) {
    OUString s(str);
    rtl::Bootstrap::expandMacros(s); //TODO: detect failure
    return s;
}

bool canRemoveFromLayer(int layer, rtl::Reference< Node > const & node) {
    assert(node.is());
    if (node->getLayer() > layer && node->getLayer() < Data::NO_LAYER) {
        return false;
    }
    switch (node->kind()) {
    case Node::KIND_LOCALIZED_PROPERTY:
    case Node::KIND_GROUP:
        for (auto const& member : node->getMembers())
        {
            if (!canRemoveFromLayer(layer, member.second)) {
                return false;
            }
        }
        return true;
    case Node::KIND_SET:
        return node->getMembers().empty();
    default: // Node::KIND_PROPERTY, Node::KIND_LOCALIZED_VALUE
        return true;
    }
}

}

class Components::WriteThread: public salhelper::Thread {
public:
    WriteThread(
        rtl::Reference< WriteThread > * reference, Components & components,
        OUString url, Data const & data);

    void flush() { delay_.set(); }

private:
    virtual ~WriteThread() override {}

    virtual void execute() override;

    rtl::Reference< WriteThread > * reference_;
    Components & components_;
    OUString url_;
    Data const & data_;
    osl::Condition delay_;
    std::shared_ptr<osl::Mutex> lock_;
};

Components::WriteThread::WriteThread(
    rtl::Reference< WriteThread > * reference, Components & components,
    OUString url, Data const & data):
    Thread("configmgrWriter"), reference_(reference), components_(components),
    url_(std::move(url)), data_(data),
    lock_( lock() )
{
    assert(reference != nullptr);
}

void Components::WriteThread::execute() {
    delay_.wait(std::chrono::seconds(1)); // must not throw; result_error is harmless and ignored
    osl::MutexGuard g(*lock_); // must not throw
    try {
        try {
            writeModFile(components_, url_, data_);
        } catch (css::uno::RuntimeException &) {
            // Ignore write errors, instead of aborting:
            TOOLS_WARN_EXCEPTION("configmgr", "error writing modifications");
        }
    } catch (...) {
        reference_->clear();
        throw;
    }
    reference_->clear();
}

Components & Components::getSingleton(
    css::uno::Reference< css::uno::XComponentContext > const & context)
{
    assert(context.is());
    static Components singleton(context);
    return singleton;
}

bool Components::allLocales(std::u16string_view locale) {
    return locale == u"*";
}

rtl::Reference< Node > Components::resolvePathRepresentation(
    OUString const & pathRepresentation,
    OUString * canonicRepresentation, std::vector<OUString> * path, int * finalizedLayer)
    const
{
    return data_.resolvePathRepresentation(
        pathRepresentation, canonicRepresentation, path, finalizedLayer);
}

rtl::Reference< Node > Components::getTemplate(OUString const & fullName) const
{
    return data_.getTemplate(Data::NO_LAYER, fullName);
}

void Components::addRootAccess(rtl::Reference< RootAccess > const & access) {
    roots_.insert(access.get());
}

void Components::removeRootAccess(RootAccess * access) {
    roots_.erase(access);
}

void Components::initGlobalBroadcaster(
    Modifications const & modifications,
    rtl::Reference< RootAccess > const & exclude, Broadcaster * broadcaster)
{
    //TODO: Iterate only over roots w/ listeners:
    for (auto const& elemRoot : roots_)
    {
        rtl::Reference< RootAccess > root;
        if (elemRoot->acquireCounting() > 1) {
            root.set(elemRoot); // must not throw
        }
        elemRoot->releaseNondeleting();
        if (root.is()) {
            if (root != exclude) {
                std::vector<OUString> path(root->getAbsolutePath());
                Modifications::Node const * mods = &modifications.getRoot();
                for (auto const& pathElem : path)
                {
                    Modifications::Node::Children::const_iterator k(
                        mods->children.find(pathElem));
                    if (k == mods->children.end()) {
                        mods = nullptr;
                        break;
                    }
                    mods = &k->second;
                }
                //TODO: If the complete tree of which root is a part is deleted,
                // or replaced, mods will be null, but some of the listeners
                // from within root should probably fire nonetheless:
                if (mods != nullptr) {
                    root->initBroadcaster(*mods, broadcaster);
                }
            }
        }
    }
}

void Components::addModification(std::vector<OUString> const & path) {
    data_.modifications.add(path);
}

void Components::writeModifications() {

    if (data_.modifications.empty())
        return;

    switch (modificationTarget_) {
    case ModificationTarget::None:
        break;
    case ModificationTarget::File:
        if (!writeThread_.is()) {
            writeThread_ = new WriteThread(
                &writeThread_, *this, modificationFileUrl_, data_);
            writeThread_->launch();
        }
        break;
    case ModificationTarget::Dconf:
#if ENABLE_DCONF
        dconf::writeModifications(*this, data_);
#endif
        break;
    }
}

void Components::flushModifications() {
    rtl::Reference< WriteThread > thread;
    {
        osl::MutexGuard g(*lock_);
        thread = writeThread_;
    }
    if (thread.is()) {
        thread->flush();
        thread->join();
    }
}

void Components::insertExtensionXcsFile(
    bool shared, OUString const & fileUri)
{
    int layer = getExtensionLayer(shared);
    try {
        parseXcsFile(fileUri, layer, data_, nullptr, nullptr, nullptr);
    } catch (css::container::NoSuchElementException & e) {
        throw css::uno::RuntimeException(
            "insertExtensionXcsFile does not exist: " + e.Message);
    }
}

void Components::insertExtensionXcuFile(
    bool shared, OUString const & fileUri, Modifications * modifications)
{
    assert(modifications != nullptr);
    int layer = getExtensionLayer(shared) + 1;
    Additions * adds = data_.addExtensionXcuAdditions(fileUri, layer);
    try {
        parseXcuFile(fileUri, layer, data_, nullptr, modifications, adds);
    } catch (css::container::NoSuchElementException & e) {
        data_.removeExtensionXcuAdditions(fileUri);
        throw css::uno::RuntimeException(
            "insertExtensionXcuFile does not exist: " + e.Message);
    }
}

void Components::removeExtensionXcuFile(
    OUString const & fileUri, Modifications * modifications)
{
    //TODO: Ideally, exactly the data coming from the specified xcu file would
    // be removed.  However, not enough information is recorded in the in-memory
    // data structures to do so.  So, as a workaround, all those set elements
    // that were freshly added by the xcu and have afterwards been left
    // unchanged or have only had their properties changed in the user layer are
    // removed (and nothing else).  The heuristic to determine
    // whether a node has been left unchanged is to check the layer ID (as
    // usual) and additionally to check that the node does not recursively
    // contain any non-empty sets (multiple extension xcu files are merged into
    // one layer, so checking layer ID alone is not enough).  Since
    // item->additions records all additions of set members in textual order,
    // the latter check works well when iterating through item->additions in
    // reverse order.
    assert(modifications != nullptr);
    rtl::Reference< Data::ExtensionXcu > item(
        data_.removeExtensionXcuAdditions(fileUri));
    if (!item.is())
        return;

    for (Additions::reverse_iterator i(item->additions.rbegin());
         i != item->additions.rend(); ++i)
    {
        rtl::Reference< Node > parent;
        NodeMap const * map = &data_.getComponents();
        rtl::Reference< Node > node;
        for (auto const& j : *i)
        {
            parent = node;
            node = map->findNode(Data::NO_LAYER, j);
            if (!node.is()) {
                break;
            }
            map = &node->getMembers();
        }
        if (node.is()) {
            assert(parent.is());
            if (parent->kind() == Node::KIND_SET) {
                assert(
                    node->kind() == Node::KIND_GROUP ||
                    node->kind() == Node::KIND_SET);
                if (canRemoveFromLayer(item->layer, node)) {
                    parent->getMembers().erase(i->back());
                    data_.modifications.remove(*i);
                    modifications->add(*i);
                }
            }
        }
    }
    writeModifications();
}

void Components::insertModificationXcuFile(
    OUString const & fileUri,
    std::set< OUString > const & includedPaths,
    std::set< OUString > const & excludedPaths,
    Modifications * modifications)
{
    assert(modifications != nullptr);
    Partial part(includedPaths, excludedPaths);
    try {
        parseFileLeniently(
            &parseXcuFile, fileUri, Data::NO_LAYER, &part, modifications, nullptr);
    } catch (const css::container::NoSuchElementException &) {
        TOOLS_WARN_EXCEPTION(
            "configmgr",
            "error inserting non-existing \"" << fileUri << "\"");
    }
}

css::beans::Optional< css::uno::Any > Components::getExternalValue(
    std::u16string_view descriptor)
{
    size_t i = descriptor.find(' ');
    if (i == 0 || i == std::u16string_view::npos) {
        throw css::uno::RuntimeException(
            OUString::Concat("bad external value descriptor ") + descriptor);
    }
    //TODO: Do not make calls with mutex locked:
    OUString name(descriptor.substr(0, i));
    ExternalServices::iterator j(externalServices_.find(name));
    if (j == externalServices_.end()) {
        css::uno::Reference< css::uno::XInterface > service;
        try {
            service = context_->getServiceManager()->createInstanceWithContext(
                name, context_);
        } catch (const css::uno::RuntimeException &) {
            // Assuming these exceptions are real errors:
            throw;
        } catch (const css::uno::Exception &)  {
            // Assuming these exceptions indicate that the service is not
            // installed:
            TOOLS_WARN_EXCEPTION(
                "configmgr",
                "createInstance(" << name << ") failed");
        }
        css::uno::Reference< css::beans::XPropertySet > propset;
        if (service.is()) {
            propset.set( service, css::uno::UNO_QUERY_THROW);
        }
        j = externalServices_.emplace(name, propset).first;
    }
    css::beans::Optional< css::uno::Any > value;
    if (j->second.is()) {
        try {
            if (!(j->second->getPropertyValue(OUString(descriptor.substr(i + 1))) >>=
                  value))
            {
                throw css::uno::RuntimeException(
                    OUString::Concat("cannot obtain external value through ") + descriptor);
            }
        } catch (css::beans::UnknownPropertyException & e) {
            throw css::uno::RuntimeException(
                "unknown external value descriptor ID: " + e.Message);
        } catch (css::lang::WrappedTargetException & e) {
            css::uno::Any anyEx = cppu::getCaughtException();
            throw css::lang::WrappedTargetRuntimeException(
                "cannot obtain external value: " + e.Message,
                nullptr, anyEx );
        }
    }
    return value;
}

Components::Components(
    css::uno::Reference< css::uno::XComponentContext > const & context):
    context_(context), sharedExtensionLayer_(-1), userExtensionLayer_(-1),
    modificationTarget_(ModificationTarget::None)
{
    assert(context.is());
    lock_ = lock();
    OUString conf(expand("${CONFIGURATION_LAYERS}"));
    int layer = 0;
    for (sal_Int32 i = 0;;) {
        while (i != conf.getLength() && conf[i] == ' ') {
            ++i;
        }
        if (i == conf.getLength()) {
            break;
        }
        if (modificationTarget_ != ModificationTarget::None) {
            throw css::uno::RuntimeException(
                "CONFIGURATION_LAYERS: modification target layer followed by"
                " further layers");
        }
        sal_Int32 c = i;
        for (;; ++c) {
            if (c == conf.getLength() || conf[c] == ' ') {
                throw css::uno::RuntimeException(
                    "CONFIGURATION_LAYERS: missing ':' in \"" + conf + "\"");
            }
            if (conf[c] == ':') {
                break;
            }
        }
        sal_Int32 n = conf.indexOf(' ', c + 1);
        if (n == -1) {
            n = conf.getLength();
        }
        OUString type(conf.copy(i, c - i));
        OUString url(conf.copy(c + 1, n - c - 1));
        if (type == "xcsxcu") {
            sal_uInt32 nStartTime = osl_getGlobalTimer();
            parseXcsXcuLayer(layer, url);
            SAL_INFO("configmgr", "parseXcsXcuLayer() took " << (osl_getGlobalTimer() - nStartTime) << " ms");
            layer += 2; //TODO: overflow
        } else if (type == "bundledext") {
            parseXcsXcuIniLayer(layer, url, false);
            layer += 2; //TODO: overflow
        } else if (type == "sharedext") {
            if (sharedExtensionLayer_ != -1) {
                throw css::uno::RuntimeException(
                    "CONFIGURATION_LAYERS: multiple \"sharedext\" layers");
            }
            sharedExtensionLayer_ = layer;
            parseXcsXcuIniLayer(layer, url, true);
            layer += 2; //TODO: overflow
        } else if (type == "userext") {
            if (userExtensionLayer_ != -1) {
                throw css::uno::RuntimeException(
                    "CONFIGURATION_LAYERS: multiple \"userext\" layers");
            }
            userExtensionLayer_ = layer;
            parseXcsXcuIniLayer(layer, url, true);
            layer += 2; //TODO: overflow
        } else if (type == "res") {
            sal_uInt32 nStartTime = osl_getGlobalTimer();
            parseResLayer(layer, url);
            SAL_INFO("configmgr", "parseResLayer() took " << (osl_getGlobalTimer() - nStartTime) << " ms");
            ++layer; //TODO: overflow
#if ENABLE_DCONF
        } else if (type == "dconf") {
            if (url == "!") {
                modificationTarget_ = ModificationTarget::Dconf;
                dconf::readLayer(data_, Data::NO_LAYER);
            } else if (url == "*") {
                dconf::readLayer(data_, layer);
            } else {
                throw css::uno::RuntimeException(
                    "CONFIGURATION_LAYERS: unknown \"dconf\" kind \"" + url
                    + "\"");
            }
            ++layer; //TODO: overflow
#endif
#if defined(_WIN32)
        } else if (type == "winreg") {
            WinRegType eType;
            if (url == "LOCAL_MACHINE" || url.isEmpty()/*backwards comp.*/) {
                eType = WinRegType::LOCAL_MACHINE;
            } else if (url == "CURRENT_USER") {
                eType = WinRegType::CURRENT_USER;
            } else {
                throw css::uno::RuntimeException(
                    "CONFIGURATION_LAYERS: unknown \"winreg\" kind \"" + url
                    + "\"");
            }
            OUString aTempFileURL;
            if (dumpWindowsRegistry(&aTempFileURL, eType)) {
                parseFileLeniently(&parseXcuFile, aTempFileURL, layer, nullptr, nullptr, nullptr);
                if (!getenv("SAL_CONFIG_WINREG_RETAIN_TMP"))
                    osl::File::remove(aTempFileURL);
            }
            ++layer; //TODO: overflow
#endif
        } else if (type == "user") {
            bool write;
            if (url.startsWith("!", &url)) {
                write = true;
            } else if (url.startsWith("*", &url)) {
                write = false;
            } else {
                write = true; // for backwards compatibility
            }
            if (url.isEmpty()) {
                throw css::uno::RuntimeException(
                    "CONFIGURATION_LAYERS: empty \"user\" URL");
            }
            bool ignore = false;
#if ENABLE_DCONF
            if (write) {
                OUString token(
                    expand("${SYSUSERCONFIG}/libreoffice/dconfwrite"));
                osl::DirectoryItem it;
                osl::FileBase::RC e = osl::DirectoryItem::get(token, it);
                ignore = e == osl::FileBase::E_None;
                SAL_INFO(
                    "configmgr",
                    "dconf write (<" << token << "> " << +e << "): "
                        << int(ignore));
                if (ignore) {
                    modificationTarget_ = ModificationTarget::Dconf;
                }
            }
#endif
            if (!ignore) {
                if (write) {
                    modificationTarget_ = ModificationTarget::File;
                    modificationFileUrl_ = url;
                }
                parseModificationLayer(write ? Data::NO_LAYER : layer, url);
            }
            ++layer; //TODO: overflow
        } else {
            throw css::uno::RuntimeException(
                "CONFIGURATION_LAYERS: unknown layer type \"" + type + "\"");
        }
        i = n;
    }
}

Components::~Components()
{
    // get flag if _exit was already called which is a sign to not secure user config.
    // this is used for win only currently where calling _exit() unfortunately still
    // calls destructors (what is not wanted). May be needed for other systems, too
    // (unknown yet) but can do no harm
    const bool bExitWasCalled(comphelper::BackupFileHelper::getExitWasCalled());

#ifndef _WIN32
    // we can add a SAL_WARN here for other systems where the destructor gets called after
    // an _exit() call. Still safe - the getExitWasCalled() is used, but a hint that _exit
    // behaves different on a system
    SAL_WARN_IF(bExitWasCalled, "configmgr", "Components::~Components() called after _exit() call");
#endif

    if (bExitWasCalled)
    {
        // do not write, re-join threads
        osl::MutexGuard g(*lock_);

        if (writeThread_.is())
        {
            writeThread_->join();
        }
    }
    else
    {
        // write changes
        flushModifications();
    }

    for (auto const& rootElem : roots_)
    {
        rootElem->setAlive(false);
    }
}

void Components::parseFileLeniently(
    FileParser * parseFile, OUString const & url, int layer,
    Partial const * partial, Modifications * modifications,
    Additions * additions)
{
    assert(parseFile != nullptr);
    try {
        (*parseFile)(url, layer, data_, partial, modifications, additions);
    } catch (const css::container::NoSuchElementException &) {
        throw;
    } catch (const css::uno::Exception &) { //TODO: more specific exception catching
        // Ignore invalid XML files, instead of completely preventing OOo from
        // starting:
        TOOLS_WARN_EXCEPTION(
            "configmgr",
            "error reading \"" << url << "\"");
    }
}

void Components::parseFiles(
    int layer, OUString const & extension, FileParser * parseFile,
    OUString const & url, bool recursive)
{
    osl::Directory dir(url);
    switch (dir.open()) {
    case osl::FileBase::E_None:
        break;
    case osl::FileBase::E_NOENT:
        if (!recursive) {
            return;
        }
        [[fallthrough]];
    default:
        throw css::uno::RuntimeException(
            "cannot open directory " + url);
    }
    for (;;) {
        osl::DirectoryItem i;
        osl::FileBase::RC rc = dir.getNextItem(i, SAL_MAX_UINT32);
        if (rc == osl::FileBase::E_NOENT) {
            break;
        }
        if (rc != osl::FileBase::E_None) {
            throw css::uno::RuntimeException(
                "cannot iterate directory " + url);
        }
        osl::FileStatus stat(
            osl_FileStatus_Mask_Type | osl_FileStatus_Mask_FileName |
            osl_FileStatus_Mask_FileURL);
        if (i.getFileStatus(stat) != osl::FileBase::E_None) {
            throw css::uno::RuntimeException(
                "cannot stat in directory " + url);
        }
        if (stat.getFileType() == osl::FileStatus::Directory) { //TODO: symlinks
            parseFiles(layer, extension, parseFile, stat.getFileURL(), true);
        } else {
            OUString file(stat.getFileName());
            if (file.endsWith(extension)) {
                try {
                    parseFileLeniently(
                        parseFile, stat.getFileURL(), layer, nullptr, nullptr, nullptr);
                } catch (css::container::NoSuchElementException & e) {
                    if (stat.getFileType() == osl::FileStatus::Link) {
                        SAL_WARN("configmgr", "dangling link <" << stat.getFileURL() << ">");
                        continue;
                    }
                    throw css::uno::RuntimeException(
                        "stat'ed file does not exist: " + e.Message);
                }
            }
        }
    }
}

void Components::parseFileList(
    int layer, FileParser * parseFile, std::u16string_view urls,
    bool recordAdditions)
{
    for (sal_Int32 i = 0;;) {
        OUString url(o3tl::getToken(urls, 0, ' ', i));
        if (!url.isEmpty()) {
            Additions * adds = nullptr;
            if (recordAdditions) {
                adds = data_.addExtensionXcuAdditions(url, layer);
            }
            try {
                parseFileLeniently(parseFile, url, layer, nullptr, nullptr, adds);
            } catch (const css::container::NoSuchElementException &) {
                TOOLS_WARN_EXCEPTION("configmgr", "file does not exist");
                if (adds != nullptr) {
                    data_.removeExtensionXcuAdditions(url);
                }
            }
        }
        if (i == -1) {
            break;
        }
    }
}

void Components::parseXcdFiles(int layer, OUString const & url) {
    osl::Directory dir(url);
    switch (dir.open()) {
    case osl::FileBase::E_None:
        break;
    case osl::FileBase::E_NOENT:
        return;
    default:
        throw css::uno::RuntimeException(
            "cannot open directory " + url);
    }
    UnresolvedVector unres;
    std::set< OUString > existingDeps;
    std::set< OUString > processedDeps;
    for (;;) {
        osl::DirectoryItem i;
        osl::FileBase::RC rc = dir.getNextItem(i, SAL_MAX_UINT32);
        if (rc == osl::FileBase::E_NOENT) {
            break;
        }
        if (rc != osl::FileBase::E_None) {
            throw css::uno::RuntimeException(
                "cannot iterate directory " + url);
        }
        osl::FileStatus stat(
            osl_FileStatus_Mask_Type | osl_FileStatus_Mask_FileName |
            osl_FileStatus_Mask_FileURL);
        if (i.getFileStatus(stat) != osl::FileBase::E_None) {
            throw css::uno::RuntimeException(
                "cannot stat in directory " + url);
        }
        if (stat.getFileType() != osl::FileStatus::Directory) { //TODO: symlinks
            OUString file(stat.getFileName());
            OUString name;
            if (file.endsWith(".xcd", &name)) {
                existingDeps.insert(name);
                rtl::Reference< ParseManager > manager;
                try {
                    manager = new ParseManager(
                        stat.getFileURL(),
                        new XcdParser(layer, processedDeps, data_));
                } catch (css::container::NoSuchElementException & e) {
                    if (stat.getFileType() == osl::FileStatus::Link) {
                        SAL_WARN("configmgr", "dangling link <" << stat.getFileURL() << ">");
                        continue;
                    }
                    throw css::uno::RuntimeException(
                        "stat'ed file does not exist: " + e.Message);
                }
                if (manager->parse(nullptr)) {
                    processedDeps.insert(name);
                } else {
                    unres.emplace_back(name, manager);
                }
            }
        }
    }
    while (!unres.empty()) {
        bool resolved = false;
        for (UnresolvedVector::iterator i(unres.begin()); i != unres.end();) {
            if (i->manager->parse(&existingDeps)) {
                processedDeps.insert(i->name);
                i = unres.erase(i);
                resolved = true;
            } else {
                ++i;
            }
        }
        if (!resolved) {
            throw css::uno::RuntimeException(
                "xcd: unresolved dependencies in " + url);
        }
    }
}

void Components::parseXcsXcuLayer(int layer, OUString const & url) {
    parseXcdFiles(layer, url);
    parseFiles(layer, ".xcs", &parseXcsFile, url + "/schema", false);
    parseFiles(layer + 1, ".xcu", &parseXcuFile, url + "/data", false);
}

void Components::parseXcsXcuIniLayer(
    int layer, OUString const & url, bool recordAdditions)
{
    // Check if ini file exists (otherwise .override would still read global
    // SCHEMA/DATA variables, which could interfere with unrelated environment
    // variables):
    if (rtl::Bootstrap(url).getHandle() == nullptr)        return;

    OUStringBuffer prefix("${.override:");
    for (sal_Int32 i = 0; i != url.getLength(); ++i) {
        sal_Unicode c = url[i];
        switch (c) {
        case '$':
        case ':':
        case '\\':
            prefix.append('\\');
            [[fallthrough]];
        default:
            prefix.append(c);
        }
    }
    prefix.append(':');
    OUString urls(prefix + "SCHEMA}");
    rtl::Bootstrap::expandMacros(urls);
    if (!urls.isEmpty()) {
        parseFileList(layer, &parseXcsFile, urls, false);
    }
    urls = prefix + "DATA}";
    rtl::Bootstrap::expandMacros(urls);
    if (!urls.isEmpty()) {
        parseFileList(layer + 1, &parseXcuFile, urls, recordAdditions);
    }
}

void Components::parseResLayer(int layer, std::u16string_view url) {
    OUString resUrl(OUString::Concat(url) + "/res");
    parseXcdFiles(layer, resUrl);
    parseFiles(layer, ".xcu", &parseXcuFile, resUrl, false);
}

void Components::parseModificationLayer(int layer, OUString const & url) {
    try {
        parseFileLeniently(&parseXcuFile, url, layer, nullptr, nullptr, nullptr);
    } catch (css::container::NoSuchElementException &) {
        SAL_INFO(
            "configmgr", "user registrymodifications.xcu does not (yet) exist");
        // Migrate old user layer data (can be removed once migration is no
        // longer relevant, probably OOo 4; also see hack for xsi namespace in
        // xmlreader::XmlReader::registerNamespaceIri):
        parseFiles(
            layer, ".xcu", &parseXcuFile,
            expand(
                "${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("bootstrap")
                ":UserInstallation}/user/registry/data"),
            false);
    }
}

int Components::getExtensionLayer(bool shared) const {
    int layer = shared ? sharedExtensionLayer_ : userExtensionLayer_;
    if (layer == -1) {
        throw css::uno::RuntimeException(
            "insert extension xcs/xcu file into undefined layer");
    }
    return layer;
}

}

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