Avoid potential negative array index access to cached text.
[LibreOffice.git] / include / o3tl / safeCoInitUninit.hxx
blob0ceb4a9746a2923fd29492e062442d3ea237b72d
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
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/.
8 */
10 #pragma once
12 #if defined _WIN32
13 #include <prewin.h>
15 // for CoInitializeEx / CoUninitialize
16 #include <combaseapi.h>
18 #include <postwin.h>
20 // for std::abort
21 #include <cstdlib>
23 namespace o3tl
25 // Helpers for safe calls to CoInitializeEx and CoUninitialize in MSVC
26 // Indeed if a thread has been already initialized with a concurrency model
27 // (in LO case COINIT_APARTMENTTHREADED or COINIT_MULTITHREADED)
28 // CoInitializeEx can't succeed without calling first CoUninitialize
29 // also, CoUninitialize must be called the number of times CoInitializeEx has been called
30 inline HRESULT safeCoInitializeEx(DWORD dwCoInit, int& nbReinit)
32 HRESULT hr;
33 while ((hr = CoInitializeEx(nullptr, dwCoInit)) == RPC_E_CHANGED_MODE)
35 // so we're in RPC_E_CHANGED_MODE case
36 // the pb was it was already initialized with a different concurrency model
37 // close this init
38 CoUninitialize();
39 // and increment counter for dtr part
40 ++nbReinit;
42 // and keep on the loop if there were multi initializations
44 if (FAILED(hr))
45 std::abort();
46 return hr;
49 inline void safeCoUninitializeReinit(DWORD dwCoInit, int nbReinit)
51 CoUninitialize();
52 // Put back all the inits, if there were, before the use of the caller to safeCoInitializeEx
53 for (int i = 0; i < nbReinit; ++i)
54 CoInitializeEx(nullptr, dwCoInit);
57 #endif
58 /* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */