nss: upgrade to release 3.73
[LibreOffice.git] / bridges / source / cpp_uno / shared / vtablefactory.cxx
blob90c414290c1ab3bba15e05fd0e6214f09f75c403
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 .
21 #include <vtablefactory.hxx>
23 #include <vtables.hxx>
25 #include <osl/thread.h>
26 #include <osl/security.hxx>
27 #include <osl/file.hxx>
28 #include <osl/mutex.hxx>
29 #include <rtl/alloc.h>
30 #include <rtl/ustring.hxx>
31 #include <sal/log.hxx>
32 #include <sal/types.h>
33 #include <typelib/typedescription.hxx>
35 #include <memory>
36 #include <new>
37 #include <unordered_map>
38 #include <vector>
40 #if defined SAL_UNX
41 #include <unistd.h>
42 #include <string.h>
43 #include <errno.h>
44 #include <sys/mman.h>
45 #elif defined _WIN32
46 #define WIN32_LEAN_AND_MEAN
47 #include <windows.h>
48 #else
49 #error Unsupported platform
50 #endif
52 #if defined USE_DOUBLE_MMAP
53 #include <fcntl.h>
54 #endif
56 #if defined MACOSX && defined __aarch64__
57 #include <pthread.h>
58 #endif
60 using bridges::cpp_uno::shared::VtableFactory;
62 namespace {
64 extern "C" void * allocExec(
65 SAL_UNUSED_PARAMETER rtl_arena_type *, sal_Size * size)
67 std::size_t pagesize;
68 #if defined SAL_UNX
69 #if defined FREEBSD || defined NETBSD || defined OPENBSD || defined DRAGONFLY || defined HAIKU
70 pagesize = getpagesize();
71 #else
72 pagesize = sysconf(_SC_PAGESIZE);
73 #endif
74 #elif defined _WIN32
75 SYSTEM_INFO info;
76 GetSystemInfo(&info);
77 pagesize = info.dwPageSize;
78 #else
79 #error Unsupported platform
80 #endif
81 std::size_t n = (*size + (pagesize - 1)) & ~(pagesize - 1);
82 void * p;
83 #if defined SAL_UNX
84 #if defined MACOSX
85 p = mmap(
86 nullptr, n, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON | MAP_JIT, -1,
87 0);
88 if (p != MAP_FAILED) {
89 goto done;
92 auto const e = errno;
93 SAL_INFO("bridges.osx", "mmap failed with " << e);
94 if (e != EINVAL) {
95 p = nullptr;
96 goto done;
99 // At least some macOS 10.13 machines are reported to fail the above mmap with EINVAL (see
100 // tdf#134754 "Crash on macOS 10.13 opening local HSQLDB-based odb file in Base on LibreOffice 7
101 // rc1", so in that case retry with the "traditional" approach:
102 #endif
103 p = mmap(
104 nullptr, n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1,
106 if (p == MAP_FAILED) {
107 p = nullptr;
109 else if (mprotect (p, n, PROT_READ | PROT_WRITE | PROT_EXEC) == -1)
111 munmap (p, n);
112 p = nullptr;
114 #if defined MACOSX
115 done:
116 #endif
117 #elif defined _WIN32
118 p = VirtualAlloc(nullptr, n, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
119 #endif
120 if (p != nullptr) {
121 *size = n;
123 return p;
126 extern "C" void freeExec(
127 SAL_UNUSED_PARAMETER rtl_arena_type *, void * address, sal_Size size)
129 #if defined SAL_UNX
130 munmap(address, size);
131 #elif defined _WIN32
132 (void) size; // unused
133 VirtualFree(address, 0, MEM_RELEASE);
134 #endif
139 class VtableFactory::GuardedBlocks:
140 public std::vector<Block>
142 public:
143 GuardedBlocks(const GuardedBlocks&) = delete;
144 const GuardedBlocks& operator=(const GuardedBlocks&) = delete;
146 explicit GuardedBlocks(VtableFactory const & factory):
147 m_factory(factory), m_guarded(true) {}
149 ~GuardedBlocks();
151 void unguard() { m_guarded = false; }
153 private:
154 VtableFactory const & m_factory;
155 bool m_guarded;
158 VtableFactory::GuardedBlocks::~GuardedBlocks() {
159 if (m_guarded) {
160 for (iterator i(begin()); i != end(); ++i) {
161 m_factory.freeBlock(*i);
166 class VtableFactory::BaseOffset {
167 public:
168 explicit BaseOffset(typelib_InterfaceTypeDescription * type) { calculate(type, 0); }
170 sal_Int32 getFunctionOffset(OUString const & name) const
171 { return m_map.find(name)->second; }
173 private:
174 sal_Int32 calculate(
175 typelib_InterfaceTypeDescription * type, sal_Int32 offset);
177 std::unordered_map< OUString, sal_Int32 > m_map;
180 sal_Int32 VtableFactory::BaseOffset::calculate(
181 typelib_InterfaceTypeDescription * type, sal_Int32 offset)
183 OUString name(type->aBase.pTypeName);
184 auto it = m_map.find(name);
185 if (it == m_map.end()) {
186 for (sal_Int32 i = 0; i < type->nBaseTypes; ++i) {
187 offset = calculate(type->ppBaseTypes[i], offset);
189 m_map.insert(it, {name, offset});
190 typelib_typedescription_complete(
191 reinterpret_cast< typelib_TypeDescription ** >(&type));
192 offset += bridges::cpp_uno::shared::getLocalFunctions(type);
194 return offset;
197 VtableFactory::VtableFactory(): m_arena(
198 rtl_arena_create(
199 "bridges::cpp_uno::shared::VtableFactory",
200 sizeof (void *), // to satisfy alignment requirements
201 0, nullptr, allocExec, freeExec, 0))
203 if (m_arena == nullptr) {
204 throw std::bad_alloc();
208 VtableFactory::~VtableFactory() {
210 osl::MutexGuard guard(m_mutex);
211 for (const auto& rEntry : m_map) {
212 for (sal_Int32 j = 0; j < rEntry.second.count; ++j) {
213 freeBlock(rEntry.second.blocks[j]);
217 rtl_arena_destroy(m_arena);
220 const VtableFactory::Vtables& VtableFactory::getVtables(
221 typelib_InterfaceTypeDescription * type)
223 OUString name(type->aBase.pTypeName);
224 osl::MutexGuard guard(m_mutex);
225 Map::iterator i(m_map.find(name));
226 if (i == m_map.end()) {
227 GuardedBlocks blocks(*this);
228 createVtables(blocks, BaseOffset(type), type, 0, type, true);
229 Vtables vtables;
230 assert(blocks.size() <= SAL_MAX_INT32);
231 vtables.count = static_cast< sal_Int32 >(blocks.size());
232 vtables.blocks.reset(new Block[vtables.count]);
233 for (sal_Int32 j = 0; j < vtables.count; ++j) {
234 vtables.blocks[j] = blocks[j];
236 i = m_map.emplace(name, std::move(vtables)).first;
237 blocks.unguard();
239 return i->second;
242 #ifdef USE_DOUBLE_MMAP
243 bool VtableFactory::createBlock(Block &block, sal_Int32 slotCount) const
245 std::size_t size = getBlockSize(slotCount);
246 std::size_t pagesize = sysconf(_SC_PAGESIZE);
247 block.size = (size + (pagesize - 1)) & ~(pagesize - 1);
248 block.fd = -1;
250 // Try non-doublemmaped allocation first:
251 block.start = block.exec = rtl_arena_alloc(m_arena, &block.size);
252 if (block.start != nullptr) {
253 return true;
256 osl::Security aSecurity;
257 OUString strDirectory;
258 OUString strURLDirectory;
259 if (aSecurity.getHomeDir(strURLDirectory))
260 osl::File::getSystemPathFromFileURL(strURLDirectory, strDirectory);
262 for (int i = strDirectory.isEmpty() ? 1 : 0; i < 2; ++i)
264 if (strDirectory.isEmpty())
265 strDirectory = "/tmp";
267 strDirectory += "/.execoooXXXXXX";
268 OString aTmpName = OUStringToOString(strDirectory, osl_getThreadTextEncoding());
269 std::unique_ptr<char[]> tmpfname(new char[aTmpName.getLength()+1]);
270 strncpy(tmpfname.get(), aTmpName.getStr(), aTmpName.getLength()+1);
271 // coverity[secure_temp] - https://communities.coverity.com/thread/3179
272 if ((block.fd = mkstemp(tmpfname.get())) == -1)
273 fprintf(stderr, "mkstemp(\"%s\") failed: %s\n", tmpfname.get(), strerror(errno));
274 if (block.fd == -1)
276 break;
278 unlink(tmpfname.get());
279 tmpfname.reset();
280 #if defined(HAVE_POSIX_FALLOCATE)
281 int err = posix_fallocate(block.fd, 0, block.size);
282 #else
283 int err = ftruncate(block.fd, block.size);
284 #endif
285 if (err != 0)
287 #if defined(HAVE_POSIX_FALLOCATE)
288 SAL_WARN("bridges", "posix_fallocate failed with code " << err);
289 #else
290 SAL_WARN("bridges", "truncation of executable memory area failed with code " << err);
291 #endif
292 close(block.fd);
293 block.fd = -1;
294 break;
296 block.start = mmap(nullptr, block.size, PROT_READ | PROT_WRITE, MAP_SHARED, block.fd, 0);
297 if (block.start== MAP_FAILED) {
298 block.start = nullptr;
300 block.exec = mmap(nullptr, block.size, PROT_READ | PROT_EXEC, MAP_SHARED, block.fd, 0);
301 if (block.exec == MAP_FAILED) {
302 block.exec = nullptr;
305 //All good
306 if (block.start && block.exec && block.fd != -1)
307 break;
309 freeBlock(block);
311 strDirectory.clear();
313 return (block.start != nullptr && block.exec != nullptr);
316 void VtableFactory::freeBlock(Block const & block) const {
317 //if the double-map failed we were allocated on the arena
318 if (block.fd == -1 && block.start == block.exec && block.start != nullptr)
319 rtl_arena_free(m_arena, block.start, block.size);
320 else
322 if (block.start) munmap(block.start, block.size);
323 if (block.exec) munmap(block.exec, block.size);
324 if (block.fd != -1) close(block.fd);
327 #else
328 bool VtableFactory::createBlock(Block &block, sal_Int32 slotCount) const
330 block.size = getBlockSize(slotCount);
331 block.start = rtl_arena_alloc(m_arena, &block.size);
332 return block.start != nullptr;
335 void VtableFactory::freeBlock(Block const & block) const {
336 rtl_arena_free(m_arena, block.start, block.size);
338 #endif
340 sal_Int32 VtableFactory::createVtables(
341 GuardedBlocks & blocks, BaseOffset const & baseOffset,
342 typelib_InterfaceTypeDescription * type, sal_Int32 vtableNumber,
343 typelib_InterfaceTypeDescription * mostDerived, bool includePrimary) const
345 #if defined MACOSX && defined __aarch64__
346 // TODO: Should we handle resetting this in a exception-throwing-safe way?
347 pthread_jit_write_protect_np(0);
348 #endif
349 if (includePrimary) {
350 sal_Int32 slotCount
351 = bridges::cpp_uno::shared::getPrimaryFunctions(type);
352 Block block;
353 if (!createBlock(block, slotCount)) {
354 throw std::bad_alloc();
356 try {
357 Slot * slots = initializeBlock(
358 block.start, slotCount, vtableNumber, mostDerived);
359 unsigned char * codeBegin =
360 reinterpret_cast< unsigned char * >(slots);
361 unsigned char * code = codeBegin;
362 sal_Int32 vtableOffset = blocks.size() * sizeof (Slot *);
363 for (typelib_InterfaceTypeDescription const * type2 = type;
364 type2 != nullptr; type2 = type2->pBaseTypeDescription)
366 code = addLocalFunctions(
367 &slots, code,
368 #ifdef USE_DOUBLE_MMAP
369 reinterpret_cast<sal_uIntPtr>(block.exec) - reinterpret_cast<sal_uIntPtr>(block.start),
370 #endif
371 type2,
372 baseOffset.getFunctionOffset(type2->aBase.pTypeName),
373 bridges::cpp_uno::shared::getLocalFunctions(type2),
374 vtableOffset);
376 flushCode(codeBegin, code);
377 #ifdef USE_DOUBLE_MMAP
378 //Finished generating block, swap writable pointer with executable
379 //pointer
380 std::swap(block.start, block.exec);
381 #endif
382 blocks.push_back(block);
383 } catch (...) {
384 freeBlock(block);
385 throw;
388 #if defined MACOSX && defined __aarch64__
389 pthread_jit_write_protect_np(1);
390 #endif
391 for (sal_Int32 i = 0; i < type->nBaseTypes; ++i) {
392 vtableNumber = createVtables(
393 blocks, baseOffset, type->ppBaseTypes[i],
394 vtableNumber + (i == 0 ? 0 : 1), mostDerived, i != 0);
396 return vtableNumber;
399 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */