rtl::Static -> static local
[LibreOffice.git] / sal / rtl / bootstrap.cxx
blob52ee7f38d24d5efdaa31ae525ca039ac368460ca
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
19 #include <config_features.h>
20 #include <config_folders.h>
22 #include <rtl/bootstrap.h>
23 #include <rtl/bootstrap.hxx>
24 #include <osl/diagnose.h>
25 #include <osl/module.h>
26 #include <osl/process.h>
27 #include <osl/file.hxx>
28 #include <osl/mutex.hxx>
29 #include <osl/profile.hxx>
30 #include <osl/security.hxx>
31 #include <rtl/alloc.h>
32 #include <rtl/string.hxx>
33 #include <rtl/ustrbuf.hxx>
34 #include <rtl/ustring.hxx>
35 #include <rtl/byteseq.hxx>
36 #include <rtl/instance.hxx>
37 #include <rtl/malformeduriexception.hxx>
38 #include <rtl/uri.hxx>
39 #include <sal/log.hxx>
40 #include <o3tl/lru_map.hxx>
42 #include <vector>
43 #include <algorithm>
44 #include <unordered_map>
46 #ifdef ANDROID
47 #include <osl/detail/android-bootstrap.h>
48 #endif
50 #ifdef IOS
51 #include <premac.h>
52 #import <Foundation/Foundation.h>
53 #include <postmac.h>
54 #endif
56 using osl::DirectoryItem;
57 using osl::FileStatus;
59 namespace
62 struct Bootstrap_Impl;
64 char const VND_SUN_STAR_PATHNAME[] = "vnd.sun.star.pathname:";
66 bool isPathnameUrl(OUString const & url)
68 return url.matchIgnoreAsciiCase(VND_SUN_STAR_PATHNAME);
71 bool resolvePathnameUrl(OUString * url)
73 OSL_ASSERT(url);
74 if (!isPathnameUrl(*url) ||
75 (osl::FileBase::getFileURLFromSystemPath(
76 url->copy(RTL_CONSTASCII_LENGTH(VND_SUN_STAR_PATHNAME)), *url) ==
77 osl::FileBase::E_None))
79 return true;
81 *url = OUString();
82 return false;
85 enum LookupMode {
86 LOOKUP_MODE_NORMAL, LOOKUP_MODE_URE_BOOTSTRAP,
87 LOOKUP_MODE_URE_BOOTSTRAP_EXPANSION };
89 struct ExpandRequestLink {
90 ExpandRequestLink const * next;
91 Bootstrap_Impl const * file;
92 OUString key;
95 OUString expandMacros(
96 Bootstrap_Impl const * file, OUString const & text, LookupMode mode,
97 ExpandRequestLink const * requestStack);
99 OUString recursivelyExpandMacros(
100 Bootstrap_Impl const * file, OUString const & text, LookupMode mode,
101 Bootstrap_Impl const * requestFile, OUString const & requestKey,
102 ExpandRequestLink const * requestStack)
104 for (; requestStack; requestStack = requestStack->next) {
105 if (requestStack->file == requestFile &&
106 requestStack->key == requestKey)
108 return "***RECURSION DETECTED***";
111 ExpandRequestLink link = { requestStack, requestFile, requestKey };
112 return expandMacros(file, text, mode, &link);
115 struct rtl_bootstrap_NameValue
117 OUString sName;
118 OUString sValue;
120 rtl_bootstrap_NameValue()
122 rtl_bootstrap_NameValue(OUString const & name, OUString const & value )
123 : sName( name ),
124 sValue( value )
128 } // end namespace
130 typedef std::vector<rtl_bootstrap_NameValue> NameValueVector;
132 static bool find(
133 NameValueVector const & vector, OUString const & key,
134 OUString * value)
136 OSL_ASSERT(value);
137 auto i = std::find_if(vector.begin(), vector.end(),
138 [&key](const rtl_bootstrap_NameValue& rNameValue) { return rNameValue.sName == key; });
139 if (i != vector.end())
141 *value = i->sValue;
142 return true;
144 return false;
147 namespace
149 NameValueVector rtl_bootstrap_set_vector;
152 static bool getFromCommandLineArgs(
153 OUString const & key, OUString * value )
155 OSL_ASSERT(value);
157 static NameValueVector nameValueVector = [&]()
159 NameValueVector tmp;
161 sal_Int32 nArgCount = osl_getCommandArgCount();
162 for(sal_Int32 i = 0; i < nArgCount; ++ i)
164 OUString pArg;
165 osl_getCommandArg( i, &pArg.pData );
166 if( (pArg.startsWith("-") || pArg.startsWith("/") ) &&
167 pArg.match("env:", 1) )
169 sal_Int32 nIndex = pArg.indexOf( '=' );
171 if( nIndex >= 0 )
173 rtl_bootstrap_NameValue nameValue;
174 nameValue.sName = pArg.copy( 5, nIndex - 5 );
175 nameValue.sValue = pArg.copy( nIndex+1 );
177 if( i == nArgCount-1 &&
178 nameValue.sValue.getLength() &&
179 nameValue.sValue[nameValue.sValue.getLength()-1] == 13 )
181 // avoid the 13 linefeed for the last argument,
182 // when the executable is started from a script,
183 // that was edited on windows
184 nameValue.sValue = nameValue.sValue.copy(0,nameValue.sValue.getLength()-1);
187 tmp.push_back( nameValue );
191 return tmp;
192 }();
194 return find(nameValueVector, key, value);
197 static void getExecutableDirectory_Impl(rtl_uString ** ppDirURL)
199 OUString fileName;
200 osl_getExecutableFile(&(fileName.pData));
202 sal_Int32 nDirEnd = fileName.lastIndexOf('/');
203 OSL_ENSURE(nDirEnd >= 0, "Cannot locate executable directory");
205 rtl_uString_newFromStr_WithLength(ppDirURL,fileName.getStr(),nDirEnd);
208 static OUString & getIniFileName_Impl()
210 static OUString aStaticName = []() {
211 OUString fileName;
213 #if defined IOS
214 // On iOS hardcode the inifile as "rc" in the .app
215 // directory. Apps are self-contained anyway, there is no
216 // possibility to have several "applications" in the same
217 // installation location with different inifiles.
218 const char *inifile = [[@"vnd.sun.star.pathname:" stringByAppendingString: [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent: @"rc"]] UTF8String];
219 fileName = OUString(inifile, strlen(inifile), RTL_TEXTENCODING_UTF8);
220 resolvePathnameUrl(&fileName);
221 #elif defined ANDROID
222 // Apps are self-contained on Android, too, can as well hardcode
223 // it as "rc" in the "/assets" directory, i.e. inside the app's
224 // .apk (zip) archive as the /assets/rc file.
225 fileName = OUString("vnd.sun.star.pathname:/assets/rc");
226 resolvePathnameUrl(&fileName);
227 #else
228 if (getFromCommandLineArgs("INIFILENAME", &fileName))
230 resolvePathnameUrl(&fileName);
232 else
234 osl_getExecutableFile(&(fileName.pData));
236 // get rid of a potential executable extension
237 OUString progExt = ".bin";
238 if (fileName.getLength() > progExt.getLength()
239 && fileName.copy(fileName.getLength() - progExt.getLength()).equalsIgnoreAsciiCase(progExt))
241 fileName = fileName.copy(0, fileName.getLength() - progExt.getLength());
244 progExt = ".exe";
245 if (fileName.getLength() > progExt.getLength()
246 && fileName.copy(fileName.getLength() - progExt.getLength()).equalsIgnoreAsciiCase(progExt))
248 fileName = fileName.copy(0, fileName.getLength() - progExt.getLength());
251 // append config file suffix
252 fileName += SAL_CONFIGFILE("");
254 #ifdef MACOSX
255 // We keep only executables in the MacOS folder, and all
256 // rc files in LIBO_ETC_FOLDER (typically "Resources").
257 sal_Int32 off = fileName.lastIndexOf( "/MacOS/" );
258 if (off != -1)
259 fileName = fileName.replaceAt(off + 1, strlen("MacOS"), LIBO_ETC_FOLDER);
260 #endif
262 #endif
264 return fileName;
265 }();
267 return aStaticName;
270 // ensure the given file url has no final slash
272 static void EnsureNoFinalSlash (OUString & url)
274 sal_Int32 i = url.getLength();
276 if (i > 0 && url[i - 1] == '/')
277 url = url.copy(0, i - 1);
280 namespace {
282 struct Bootstrap_Impl
284 sal_Int32 _nRefCount;
285 Bootstrap_Impl * _base_ini;
287 NameValueVector _nameValueVector;
288 OUString _iniName;
290 explicit Bootstrap_Impl (OUString const & rIniName);
291 ~Bootstrap_Impl();
293 static void * operator new (std::size_t n)
294 { return malloc (sal_uInt32(n)); }
295 static void operator delete (void * p , std::size_t)
296 { free (p); }
298 bool getValue(
299 OUString const & key, rtl_uString ** value,
300 rtl_uString * defaultValue, LookupMode mode, bool override,
301 ExpandRequestLink const * requestStack) const;
302 bool getDirectValue(
303 OUString const & key, rtl_uString ** value, LookupMode mode,
304 ExpandRequestLink const * requestStack) const;
305 bool getAmbienceValue(
306 OUString const & key, rtl_uString ** value, LookupMode mode,
307 ExpandRequestLink const * requestStack) const;
308 void expandValue(
309 rtl_uString ** value, OUString const & text, LookupMode mode,
310 Bootstrap_Impl const * requestFile, OUString const & requestKey,
311 ExpandRequestLink const * requestStack) const;
316 Bootstrap_Impl::Bootstrap_Impl( OUString const & rIniName )
317 : _nRefCount( 0 ),
318 _base_ini( nullptr ),
319 _iniName (rIniName)
321 OUString base_ini(getIniFileName_Impl());
322 // normalize path
323 FileStatus status( osl_FileStatus_Mask_FileURL );
324 DirectoryItem dirItem;
325 if (DirectoryItem::get(base_ini, dirItem) == DirectoryItem::E_None &&
326 dirItem.getFileStatus(status) == DirectoryItem::E_None)
328 base_ini = status.getFileURL();
329 if (rIniName != base_ini)
331 _base_ini = static_cast< Bootstrap_Impl * >(
332 rtl_bootstrap_args_open(base_ini.pData));
335 SAL_INFO("sal.bootstrap", "Bootstrap_Impl(): sFile=" << _iniName);
336 oslFileHandle handle;
337 if (!_iniName.isEmpty() &&
338 osl_openFile(_iniName.pData, &handle, osl_File_OpenFlag_Read) == osl_File_E_None)
340 rtl::ByteSequence seq;
342 while (osl_readLine(handle , reinterpret_cast<sal_Sequence **>(&seq)) == osl_File_E_None)
344 OString line(reinterpret_cast<const char *>(seq.getConstArray()), seq.getLength());
345 sal_Int32 nIndex = line.indexOf('=');
346 if (nIndex >= 1)
348 struct rtl_bootstrap_NameValue nameValue;
349 nameValue.sName = OStringToOUString(line.copy(0,nIndex).trim(), RTL_TEXTENCODING_ASCII_US);
350 nameValue.sValue = OStringToOUString(line.copy(nIndex+1).trim(), RTL_TEXTENCODING_UTF8);
352 SAL_INFO("sal.bootstrap", "pushing: name=" << nameValue.sName << " value=" << nameValue.sValue);
354 _nameValueVector.push_back(nameValue);
357 osl_closeFile(handle);
359 else
361 SAL_INFO( "sal.bootstrap", "couldn't open file: " << _iniName );
365 Bootstrap_Impl::~Bootstrap_Impl()
367 if (_base_ini)
368 rtl_bootstrap_args_close( _base_ini );
371 namespace {
373 Bootstrap_Impl * get_static_bootstrap_handle()
375 static Bootstrap_Impl* s_handle = []() {
376 OUString iniName(getIniFileName_Impl());
377 Bootstrap_Impl* that = static_cast<Bootstrap_Impl*>(rtl_bootstrap_args_open(iniName.pData));
378 if (!that)
380 that = new Bootstrap_Impl(iniName);
381 ++that->_nRefCount;
383 return that;
384 }();
386 return s_handle;
389 struct FundamentalIniData
391 rtlBootstrapHandle ini;
393 FundamentalIniData()
395 OUString uri;
396 ini =
397 (get_static_bootstrap_handle()->getValue(
398 "URE_BOOTSTRAP", &uri.pData, nullptr, LOOKUP_MODE_NORMAL, false,
399 nullptr)
400 && resolvePathnameUrl(&uri))
401 ? rtl_bootstrap_args_open(uri.pData) : nullptr;
404 ~FundamentalIniData() { rtl_bootstrap_args_close(ini); }
406 FundamentalIniData(const FundamentalIniData&) = delete;
407 FundamentalIniData& operator=(const FundamentalIniData&) = delete;
410 struct FundamentalIni: public rtl::Static< FundamentalIniData, FundamentalIni >
415 bool Bootstrap_Impl::getValue(
416 OUString const & key, rtl_uString ** value, rtl_uString * defaultValue,
417 LookupMode mode, bool override, ExpandRequestLink const * requestStack)
418 const
420 if (mode == LOOKUP_MODE_NORMAL && key == "URE_BOOTSTRAP")
421 mode = LOOKUP_MODE_URE_BOOTSTRAP;
423 if (override && getDirectValue(key, value, mode, requestStack))
424 return true;
426 if (key == "_OS")
428 rtl_uString_assign(
429 value, OUString(RTL_OS).pData);
430 return true;
433 if (key == "_ARCH")
435 rtl_uString_assign(
436 value, OUString(RTL_ARCH).pData);
437 return true;
440 if (key == "_CPPU_ENV")
442 rtl_uString_assign(
443 value,
444 (OUString(
445 SAL_STRINGIFY(CPPU_ENV)).
446 pData));
447 return true;
450 #ifdef ANDROID
451 if (key == "APP_DATA_DIR")
453 const char *app_data_dir = lo_get_app_data_dir();
454 rtl_uString_assign(
455 value, OUString(app_data_dir, strlen(app_data_dir), RTL_TEXTENCODING_UTF8).pData);
456 return true;
458 #endif
460 #ifdef IOS
461 if (key == "APP_DATA_DIR")
463 const char *app_data_dir = [[[[NSBundle mainBundle] bundlePath] stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLPathAllowedCharacterSet]] UTF8String];
464 rtl_uString_assign(
465 value, OUString(app_data_dir, strlen(app_data_dir), RTL_TEXTENCODING_UTF8).pData);
466 return true;
468 #endif
470 if (key == "ORIGIN")
472 rtl_uString_assign(
473 value,
474 _iniName.copy(
475 0, std::max<sal_Int32>(0, _iniName.lastIndexOf('/'))).pData);
476 return true;
479 if (getAmbienceValue(key, value, mode, requestStack))
480 return true;
482 if (key == "SYSUSERCONFIG")
484 OUString v;
485 bool b = osl::Security().getConfigDir(v);
486 EnsureNoFinalSlash(v);
487 rtl_uString_assign(value, v.pData);
488 return b;
491 if (key == "SYSUSERHOME")
493 OUString v;
494 bool b = osl::Security().getHomeDir(v);
495 EnsureNoFinalSlash(v);
496 rtl_uString_assign(value, v.pData);
497 return b;
500 if (key == "SYSBINDIR")
502 getExecutableDirectory_Impl(value);
503 return true;
506 if (_base_ini != nullptr && _base_ini->getDirectValue(key, value, mode, requestStack))
507 return true;
509 if (!override && getDirectValue(key, value, mode, requestStack))
510 return true;
512 if (mode == LOOKUP_MODE_NORMAL)
514 FundamentalIniData const & d = FundamentalIni::get();
515 Bootstrap_Impl const * b = static_cast<Bootstrap_Impl const *>(d.ini);
516 if (b != nullptr && b != this && b->getDirectValue(key, value, mode, requestStack))
517 return true;
520 if (defaultValue != nullptr)
522 rtl_uString_assign(value, defaultValue);
523 return true;
526 rtl_uString_new(value);
527 return false;
530 bool Bootstrap_Impl::getDirectValue(
531 OUString const & key, rtl_uString ** value, LookupMode mode,
532 ExpandRequestLink const * requestStack) const
534 OUString v;
535 if (find(_nameValueVector, key, &v))
537 expandValue(value, v, mode, this, key, requestStack);
538 return true;
541 return false;
544 bool Bootstrap_Impl::getAmbienceValue(
545 OUString const & key, rtl_uString ** value, LookupMode mode,
546 ExpandRequestLink const * requestStack) const
548 OUString v;
549 bool f;
552 osl::MutexGuard g(osl::Mutex::getGlobalMutex());
553 f = find(rtl_bootstrap_set_vector, key, &v);
556 if (f || getFromCommandLineArgs(key, &v) ||
557 osl_getEnvironment(key.pData, &v.pData) == osl_Process_E_None)
559 expandValue(value, v, mode, nullptr, key, requestStack);
560 return true;
563 return false;
566 void Bootstrap_Impl::expandValue(
567 rtl_uString ** value, OUString const & text, LookupMode mode,
568 Bootstrap_Impl const * requestFile, OUString const & requestKey,
569 ExpandRequestLink const * requestStack) const
571 rtl_uString_assign(
572 value,
573 (mode == LOOKUP_MODE_URE_BOOTSTRAP && isPathnameUrl(text) ?
574 text :
575 recursivelyExpandMacros(
576 this, text,
577 (mode == LOOKUP_MODE_URE_BOOTSTRAP ?
578 LOOKUP_MODE_URE_BOOTSTRAP_EXPANSION : mode),
579 requestFile, requestKey, requestStack)).pData);
582 namespace {
584 typedef std::unordered_map< OUString, Bootstrap_Impl * > bootstrap_map_t;
585 bootstrap_map_t bootstrap_map;
589 rtlBootstrapHandle SAL_CALL rtl_bootstrap_args_open(rtl_uString * pIniName)
591 static o3tl::lru_map<OUString,OUString> fileUrlLookupCache(16);
593 OUString originalIniName( pIniName );
594 OUString iniName;
596 osl::ResettableMutexGuard guard(osl::Mutex::getGlobalMutex());
597 auto cacheIt = fileUrlLookupCache.find(originalIniName);
598 bool foundInCache = cacheIt != fileUrlLookupCache.end();
599 if (foundInCache)
600 iniName = cacheIt->second;
601 guard.clear();
603 // normalize path
604 if (!foundInCache)
606 FileStatus status(osl_FileStatus_Mask_FileURL);
607 DirectoryItem dirItem;
608 if (DirectoryItem::get(originalIniName, dirItem) != DirectoryItem::E_None ||
609 dirItem.getFileStatus(status) != DirectoryItem::E_None)
611 return nullptr;
613 iniName = status.getFileURL();
616 guard.reset();
617 if (!foundInCache)
618 fileUrlLookupCache.insert({originalIniName, iniName});
619 Bootstrap_Impl * that;
620 auto iFind(bootstrap_map.find(iniName));
621 if (iFind == bootstrap_map.end())
623 guard.clear();
624 that = new Bootstrap_Impl(iniName);
625 guard.reset();
626 iFind = bootstrap_map.find(iniName);
627 if (iFind == bootstrap_map.end())
629 ++that->_nRefCount;
630 ::std::pair< bootstrap_map_t::iterator, bool > insertion(
631 bootstrap_map.emplace(iniName, that));
632 OSL_ASSERT(insertion.second);
634 else
636 Bootstrap_Impl * obsolete = that;
637 that = iFind->second;
638 ++that->_nRefCount;
639 guard.clear();
640 delete obsolete;
643 else
645 that = iFind->second;
646 ++that->_nRefCount;
648 return static_cast< rtlBootstrapHandle >( that );
651 void SAL_CALL rtl_bootstrap_args_close(rtlBootstrapHandle handle) SAL_THROW_EXTERN_C()
653 if (!handle)
654 return;
656 Bootstrap_Impl * that = static_cast< Bootstrap_Impl * >( handle );
658 osl::MutexGuard guard(osl::Mutex::getGlobalMutex());
659 OSL_ASSERT(bootstrap_map.find(that->_iniName)->second == that);
660 --that->_nRefCount;
662 if (that->_nRefCount != 0)
663 return;
665 std::size_t const nLeaking = 8; // only hold up to 8 files statically
666 if (bootstrap_map.size() > nLeaking)
668 ::std::size_t erased = bootstrap_map.erase( that->_iniName );
669 if (erased != 1) {
670 OSL_ASSERT( false );
672 delete that;
676 sal_Bool SAL_CALL rtl_bootstrap_get_from_handle(
677 rtlBootstrapHandle handle,
678 rtl_uString * pName,
679 rtl_uString ** ppValue,
680 rtl_uString * pDefault
683 osl::MutexGuard guard(osl::Mutex::getGlobalMutex());
685 bool found = false;
686 if(ppValue && pName)
688 if (!handle)
689 handle = get_static_bootstrap_handle();
691 found = static_cast< Bootstrap_Impl * >(handle)->getValue(
692 pName, ppValue, pDefault, LOOKUP_MODE_NORMAL, false, nullptr );
695 return found;
698 void SAL_CALL rtl_bootstrap_get_iniName_from_handle (
699 rtlBootstrapHandle handle,
700 rtl_uString ** ppIniName
703 if(!ppIniName)
704 return;
706 if(handle)
708 Bootstrap_Impl * pImpl = static_cast<Bootstrap_Impl*>(handle);
709 rtl_uString_assign(ppIniName, pImpl->_iniName.pData);
711 else
713 const OUString & iniName = getIniFileName_Impl();
714 rtl_uString_assign(ppIniName, iniName.pData);
718 void SAL_CALL rtl_bootstrap_setIniFileName (
719 rtl_uString * pName
722 osl::MutexGuard guard(osl::Mutex::getGlobalMutex());
723 OUString & file = getIniFileName_Impl();
724 file = pName;
727 sal_Bool SAL_CALL rtl_bootstrap_get (
728 rtl_uString * pName,
729 rtl_uString ** ppValue,
730 rtl_uString * pDefault
733 return rtl_bootstrap_get_from_handle(nullptr, pName, ppValue, pDefault);
736 void SAL_CALL rtl_bootstrap_set (
737 rtl_uString * pName,
738 rtl_uString * pValue
741 const OUString name(pName);
742 const OUString value(pValue);
744 osl::MutexGuard guard(osl::Mutex::getGlobalMutex());
746 for (auto & item : rtl_bootstrap_set_vector)
748 if (item.sName == name)
750 item.sValue = value;
751 return;
755 SAL_INFO("sal.bootstrap", "explicitly getting: name=" << name << " value=" <<value);
757 rtl_bootstrap_set_vector.emplace_back(name, value);
760 void SAL_CALL rtl_bootstrap_expandMacros_from_handle(
761 rtlBootstrapHandle handle,
762 rtl_uString ** macro)
764 if (!handle)
765 handle = get_static_bootstrap_handle();
767 OUString expanded(expandMacros(static_cast< Bootstrap_Impl * >(handle),
768 OUString::unacquired(macro),
769 LOOKUP_MODE_NORMAL, nullptr));
770 rtl_uString_assign(macro, expanded.pData);
773 void SAL_CALL rtl_bootstrap_expandMacros(rtl_uString ** macro)
775 rtl_bootstrap_expandMacros_from_handle(nullptr, macro);
778 void rtl_bootstrap_encode(rtl_uString const * value, rtl_uString ** encoded)
780 OSL_ASSERT(value);
781 OUStringBuffer b(value->length+5);
782 for (sal_Int32 i = 0; i < value->length; ++i)
784 sal_Unicode c = value->buffer[i];
785 if (c == '$' || c == '\\')
786 b.append('\\');
788 b.append(c);
791 rtl_uString_assign(encoded, b.makeStringAndClear().pData);
794 namespace {
796 int hex(sal_Unicode c)
798 return
799 c >= '0' && c <= '9' ? c - '0' :
800 c >= 'A' && c <= 'F' ? c - 'A' + 10 :
801 c >= 'a' && c <= 'f' ? c - 'a' + 10 : -1;
804 sal_Unicode read(OUString const & text, sal_Int32 * pos, bool * escaped)
806 OSL_ASSERT(pos && *pos >= 0 && *pos < text.getLength() && escaped);
807 sal_Unicode c = text[(*pos)++];
808 if (c == '\\')
810 int n1, n2, n3, n4;
811 if (*pos < text.getLength() - 4 && text[*pos] == 'u' &&
812 ((n1 = hex(text[*pos + 1])) >= 0) &&
813 ((n2 = hex(text[*pos + 2])) >= 0) &&
814 ((n3 = hex(text[*pos + 3])) >= 0) &&
815 ((n4 = hex(text[*pos + 4])) >= 0))
817 *pos += 5;
818 *escaped = true;
819 return static_cast< sal_Unicode >(
820 (n1 << 12) | (n2 << 8) | (n3 << 4) | n4);
823 if (*pos < text.getLength())
825 *escaped = true;
826 return text[(*pos)++];
830 *escaped = false;
831 return c;
834 OUString lookup(
835 Bootstrap_Impl const * file, LookupMode mode, bool override,
836 OUString const & key, ExpandRequestLink const * requestStack)
838 OUString v;
839 (file == nullptr ? get_static_bootstrap_handle() : file)->getValue(
840 key, &v.pData, nullptr, mode, override, requestStack);
841 return v;
844 OUString expandMacros(
845 Bootstrap_Impl const * file, OUString const & text, LookupMode mode,
846 ExpandRequestLink const * requestStack)
848 SAL_INFO("sal.bootstrap", "expandMacros called with: " << text);
849 OUStringBuffer buf(2048);
851 for (sal_Int32 i = 0; i < text.getLength();)
853 bool escaped;
854 sal_Unicode c = read(text, &i, &escaped);
855 if (escaped || c != '$')
857 buf.append(c);
859 else
861 if (i < text.getLength() && text[i] == '{')
863 ++i;
864 sal_Int32 p = i;
865 sal_Int32 nesting = 0;
866 OUString seg[3];
867 int n = 0;
869 while (i < text.getLength())
871 sal_Int32 j = i;
872 c = read(text, &i, &escaped);
874 if (!escaped)
876 switch (c)
878 case '{':
879 ++nesting;
880 break;
881 case '}':
882 if (nesting == 0)
884 seg[n++] = text.copy(p, j - p);
885 goto done;
887 else
889 --nesting;
891 break;
892 case ':':
893 if (nesting == 0 && n < 2)
895 seg[n++] = text.copy(p, j - p);
896 p = i;
898 break;
902 done:
903 for (int j = 0; j < n; ++j)
905 seg[j] = expandMacros(file, seg[j], mode, requestStack);
908 if (n == 1)
910 buf.append(lookup(file, mode, false, seg[0], requestStack));
912 else if (n == 3 && seg[0] == ".override")
914 rtl::Bootstrap b(seg[1]);
915 Bootstrap_Impl * f = static_cast< Bootstrap_Impl * >(b.getHandle());
916 buf.append(lookup(f, mode, f != nullptr, seg[2], requestStack));
918 else
920 if (n == 3 && seg[1].isEmpty())
922 // For backward compatibility, treat ${file::key} the
923 // same as just ${file:key}:
924 seg[1] = seg[2];
925 n = 2;
928 if (n == 2)
930 buf.append(
931 lookup(
932 static_cast< Bootstrap_Impl * >(
933 rtl::Bootstrap(seg[0]).getHandle()),
934 mode, false, seg[1], requestStack));
936 else
938 // Going through osl::Profile, this code erroneously
939 // does not recursively expand macros in the resulting
940 // replacement text (and if it did, it would fail to
941 // detect cycles that pass through here):
942 buf.append(
943 OStringToOUString(
944 osl::Profile(seg[0]).readString(
945 OUStringToOString(
946 seg[1], RTL_TEXTENCODING_UTF8),
947 OUStringToOString(
948 seg[2], RTL_TEXTENCODING_UTF8),
949 OString()),
950 RTL_TEXTENCODING_UTF8));
954 else
956 OUStringBuffer kbuf(text.getLength());
957 for (; i < text.getLength();)
959 sal_Int32 j = i;
960 c = read(text, &j, &escaped);
961 if (!escaped &&
962 (c == ' ' || c == '$' || c == '-' || c == '/' ||
963 c == ';' || c == '\\'))
965 break;
968 kbuf.append(c);
969 i = j;
972 buf.append(
973 lookup(
974 file, mode, false, kbuf.makeStringAndClear(),
975 requestStack));
980 OUString result(buf.makeStringAndClear());
981 SAL_INFO("sal.bootstrap", "expandMacros result: " << result);
983 return result;
988 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */