LibreOffice Module bridges (master) 1
vtablefactory.cxx
Go to the documentation of this file.
1/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2/*
3 * This file is part of the LibreOffice project.
4 *
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 *
9 * This file incorporates work covered by the following license notice:
10 *
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 .
18 */
19
20
21#include <vtablefactory.hxx>
22
23#include <vtables.hxx>
24
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>
34
35#include <memory>
36#include <new>
37#include <unordered_map>
38#include <vector>
39
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
51
52#if defined USE_DOUBLE_MMAP
53#include <fcntl.h>
54#endif
55
56#if defined MACOSX && defined __aarch64__
57#include <pthread.h>
58#endif
59
61
62namespace {
63
64extern "C" void * allocExec(
65 SAL_UNUSED_PARAMETER rtl_arena_type *, sal_Size * size)
66{
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;
90 }
91 {
92 auto const e = errno;
93 SAL_INFO("bridges.osx", "mmap failed with " << e);
94 if (e != EINVAL) {
95 p = nullptr;
96 goto done;
97 }
98 }
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,
105 0);
106 if (p == MAP_FAILED) {
107 p = nullptr;
108 }
109 else if (mprotect (p, n, PROT_READ | PROT_WRITE | PROT_EXEC) == -1)
110 {
111 munmap (p, n);
112 p = nullptr;
113 }
114#if defined MACOSX
115done:
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;
122 }
123 return p;
124}
125
126extern "C" void freeExec(
127 SAL_UNUSED_PARAMETER rtl_arena_type *, void * address, sal_Size size)
128{
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
135}
136
137#if defined MACOSX && defined __aarch64__
138struct JitMemoryProtectionGuard {
139 JitMemoryProtectionGuard() { pthread_jit_write_protect_np(0); }
140 ~JitMemoryProtectionGuard() { pthread_jit_write_protect_np(1); }
141};
142#endif
143
144}
145
147 public std::vector<Block>
148{
149public:
150 GuardedBlocks(const GuardedBlocks&) = delete;
151 const GuardedBlocks& operator=(const GuardedBlocks&) = delete;
152
153 explicit GuardedBlocks(VtableFactory const & factory):
154 m_factory(factory), m_guarded(true) {}
155
157
158 void unguard() { m_guarded = false; }
159
160private:
163};
164
166 if (m_guarded) {
167 for (iterator i(begin()); i != end(); ++i) {
169 }
170 }
171}
172
174public:
175 explicit BaseOffset(typelib_InterfaceTypeDescription * type) { calculate(type, 0); }
176
177 sal_Int32 getFunctionOffset(OUString const & name) const
178 { return m_map.find(name)->second; }
179
180private:
181 sal_Int32 calculate(
182 typelib_InterfaceTypeDescription * type, sal_Int32 offset);
183
184 std::unordered_map< OUString, sal_Int32 > m_map;
185};
186
188 typelib_InterfaceTypeDescription * type, sal_Int32 offset)
189{
190 OUString name(type->aBase.pTypeName);
191 if (m_map.find(name) == m_map.end()) {
192 for (sal_Int32 i = 0; i < type->nBaseTypes; ++i) {
193 offset = calculate(type->ppBaseTypes[i], offset);
194 }
195 m_map.insert({name, offset});
197 reinterpret_cast< typelib_TypeDescription ** >(&type));
199 }
200 return offset;
201}
202
203VtableFactory::VtableFactory(): m_arena(
204 rtl_arena_create(
205 "bridges::cpp_uno::shared::VtableFactory",
206 sizeof (void *), // to satisfy alignment requirements
207 0, nullptr, allocExec, freeExec, 0))
208{
209 if (m_arena == nullptr) {
210 throw std::bad_alloc();
211 }
212}
213
215 {
216 std::scoped_lock guard(m_mutex);
217 for (const auto& rEntry : m_map) {
218 for (sal_Int32 j = 0; j < rEntry.second.count; ++j) {
219 freeBlock(rEntry.second.blocks[j]);
220 }
221 }
222 }
223 rtl_arena_destroy(m_arena);
224}
225
227 typelib_InterfaceTypeDescription * type)
228{
229 OUString name(type->aBase.pTypeName);
230 std::scoped_lock guard(m_mutex);
231 Map::iterator i(m_map.find(name));
232 if (i == m_map.end()) {
233 GuardedBlocks blocks(*this);
234 createVtables(blocks, BaseOffset(type), type, 0, type, true);
235 Vtables vtables;
236 assert(blocks.size() <= SAL_MAX_INT32);
237 vtables.count = static_cast< sal_Int32 >(blocks.size());
238 vtables.blocks.reset(new Block[vtables.count]);
239 for (sal_Int32 j = 0; j < vtables.count; ++j) {
240 vtables.blocks[j] = blocks[j];
241 }
242 i = m_map.emplace(name, std::move(vtables)).first;
243 blocks.unguard();
244 }
245 return i->second;
246}
247
248#ifdef USE_DOUBLE_MMAP
249bool VtableFactory::createBlock(Block &block, sal_Int32 slotCount) const
250{
251 std::size_t size = getBlockSize(slotCount);
252 std::size_t pagesize = sysconf(_SC_PAGESIZE);
253 block.size = (size + (pagesize - 1)) & ~(pagesize - 1);
254 block.fd = -1;
255
256 // Try non-doublemmaped allocation first:
257 block.start = block.exec = rtl_arena_alloc(m_arena, &block.size);
258 if (block.start != nullptr) {
259 return true;
260 }
261
262 osl::Security aSecurity;
263 OUString strDirectory;
264 OUString strURLDirectory;
265 if (aSecurity.getHomeDir(strURLDirectory))
266 osl::File::getSystemPathFromFileURL(strURLDirectory, strDirectory);
267
268 for (int i = strDirectory.isEmpty() ? 1 : 0; i < 2; ++i)
269 {
270 if (strDirectory.isEmpty())
271 strDirectory = "/tmp";
272
273 strDirectory += "/.execoooXXXXXX";
274 OString aTmpName = OUStringToOString(strDirectory, osl_getThreadTextEncoding());
275 std::unique_ptr<char[]> tmpfname(new char[aTmpName.getLength()+1]);
276 strncpy(tmpfname.get(), aTmpName.getStr(), aTmpName.getLength()+1);
277 // coverity[secure_temp] - https://communities.coverity.com/thread/3179
278 if ((block.fd = mkstemp(tmpfname.get())) == -1)
279 fprintf(stderr, "mkstemp(\"%s\") failed: %s\n", tmpfname.get(), strerror(errno));
280 if (block.fd == -1)
281 {
282 break;
283 }
284 unlink(tmpfname.get());
285 tmpfname.reset();
286#if defined(HAVE_POSIX_FALLOCATE)
287 int err = posix_fallocate(block.fd, 0, block.size);
288#else
289 int err = ftruncate(block.fd, block.size);
290#endif
291 if (err != 0)
292 {
293#if defined(HAVE_POSIX_FALLOCATE)
294 SAL_WARN("bridges", "posix_fallocate failed with code " << err);
295#else
296 SAL_WARN("bridges", "truncation of executable memory area failed with code " << err);
297#endif
298 close(block.fd);
299 block.fd = -1;
300 break;
301 }
302 block.start = mmap(nullptr, block.size, PROT_READ | PROT_WRITE, MAP_SHARED, block.fd, 0);
303 if (block.start== MAP_FAILED) {
304 block.start = nullptr;
305 }
306 block.exec = mmap(nullptr, block.size, PROT_READ | PROT_EXEC, MAP_SHARED, block.fd, 0);
307 if (block.exec == MAP_FAILED) {
308 block.exec = nullptr;
309 }
310
311 //All good
312 if (block.start && block.exec && block.fd != -1)
313 break;
314
315 freeBlock(block);
316
317 strDirectory.clear();
318 }
319 return (block.start != nullptr && block.exec != nullptr);
320}
321
322void VtableFactory::freeBlock(Block const & block) const {
323 //if the double-map failed we were allocated on the arena
324 if (block.fd == -1 && block.start == block.exec && block.start != nullptr)
325 rtl_arena_free(m_arena, block.start, block.size);
326 else
327 {
328 if (block.start) munmap(block.start, block.size);
329 if (block.exec) munmap(block.exec, block.size);
330 if (block.fd != -1) close(block.fd);
331 }
332}
333#else
334bool VtableFactory::createBlock(Block &block, sal_Int32 slotCount) const
335{
336 block.size = getBlockSize(slotCount);
337 block.start = rtl_arena_alloc(m_arena, &block.size);
338 return block.start != nullptr;
339}
340
341void VtableFactory::freeBlock(Block const & block) const {
342 rtl_arena_free(m_arena, block.start, block.size);
343}
344#endif
345
347 GuardedBlocks & blocks, BaseOffset const & baseOffset,
348 typelib_InterfaceTypeDescription * type, sal_Int32 vtableNumber,
349 typelib_InterfaceTypeDescription * mostDerived, bool includePrimary) const
350{
351 {
352#if defined MACOSX && defined __aarch64__
353 JitMemoryProtectionGuard guard;
354#endif
355 if (includePrimary) {
356 sal_Int32 slotCount
358 Block block;
359 if (!createBlock(block, slotCount)) {
360 throw std::bad_alloc();
361 }
362 try {
363 Slot * slots = initializeBlock(
364 block.start, slotCount, vtableNumber, mostDerived);
365 unsigned char * codeBegin =
366 reinterpret_cast< unsigned char * >(slots);
367 unsigned char * code = codeBegin;
368 sal_Int32 vtableOffset = blocks.size() * sizeof (Slot *);
369 for (typelib_InterfaceTypeDescription const * type2 = type;
370 type2 != nullptr; type2 = type2->pBaseTypeDescription)
371 {
373 &slots, code,
374#ifdef USE_DOUBLE_MMAP
375 reinterpret_cast<sal_uIntPtr>(block.exec) - reinterpret_cast<sal_uIntPtr>(block.start),
376#endif
377 type2,
378 baseOffset.getFunctionOffset(type2->aBase.pTypeName),
380 vtableOffset);
381 }
382 flushCode(codeBegin, code);
383#ifdef USE_DOUBLE_MMAP
384 //Finished generating block, swap writable pointer with executable
385 //pointer
386 std::swap(block.start, block.exec);
387#endif
388 blocks.push_back(block);
389 } catch (...) {
390 freeBlock(block);
391 throw;
392 }
393 }
394 }
395 for (sal_Int32 i = 0; i < type->nBaseTypes; ++i) {
396 vtableNumber = createVtables(
397 blocks, baseOffset, type->ppBaseTypes[i],
398 vtableNumber + (i == 0 ? 0 : 1), mostDerived, i != 0);
399 }
400 return vtableNumber;
401}
402
403/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
std::unordered_map< OUString, sal_Int32 > m_map
BaseOffset(typelib_InterfaceTypeDescription *type)
sal_Int32 calculate(typelib_InterfaceTypeDescription *type, sal_Int32 offset)
sal_Int32 getFunctionOffset(OUString const &name) const
const GuardedBlocks & operator=(const GuardedBlocks &)=delete
Hand out vtable structures for interface type descriptions.
bool createBlock(Block &block, sal_Int32 slotCount) const
const Vtables & getVtables(typelib_InterfaceTypeDescription *type)
Given an interface type description, return its corresponding vtable structure.
sal_Int32 createVtables(GuardedBlocks &blocks, BaseOffset const &baseOffset, typelib_InterfaceTypeDescription *type, sal_Int32 vtableNumber, typelib_InterfaceTypeDescription *mostDerived, bool includePrimary) const
static void flushCode(unsigned char const *begin, unsigned char const *end)
Flush all the generated code snippets of a vtable, on platforms that require it.
static unsigned char * addLocalFunctions(Slot **slots, unsigned char *code, sal_PtrDiff writetoexecdiff, typelib_InterfaceTypeDescription const *type, sal_Int32 functionOffset, sal_Int32 functionCount, sal_Int32 vtableOffset)
Fill the vtable slots corresponding to all local (i.e., not inherited) functions of a given interface...
void freeBlock(Block const &block) const
static Slot * initializeBlock(void *block, sal_Int32 slotCount, sal_Int32 vtableNumber, typelib_InterfaceTypeDescription *type)
Initialize a raw vtable block.
static std::size_t getBlockSize(sal_Int32 slotCount)
Calculate the size of a raw vtable block.
t_map m_map
bool close
char const * name
void * p
sal_Int64 n
#define SAL_WARN(area, stream)
#define SAL_INFO(area, stream)
struct _typelib_TypeDescription typelib_TypeDescription
Definition: msvc/except.hxx:52
def pagesize(n=-1)
err
size
sal_Int32 getLocalFunctions(typelib_InterfaceTypeDescription const *type)
Calculate the number of local functions of an interface type.
Definition: vtables.cxx:114
sal_Int32 getPrimaryFunctions(typelib_InterfaceTypeDescription *type)
Calculate the number of primary functions of an interface type.
Definition: vtables.cxx:122
int i
constexpr OUStringLiteral first
enumrange< T >::Iterator begin(enumrange< T >)
end
OString OUStringToOString(std::u16string_view str, ConnectionSettings const *settings)
sal_Unicode code
sal_Size size
The size of the raw vtable block, in bytes.
void * exec
When separately mmapping the block for writing and executing exec points to the same memory as start,...
void * start
The start of the raw vtable block.
The vtable structure corresponding to an interface type.
std::unique_ptr< Block[]> blocks
An array of blocks, representing the multiple vtables of a (multiple-inheritance) type.
sal_Int32 count
The number of blocks/vtables.
sal_Bool SAL_CALL typelib_typedescription_complete(typelib_TypeDescription **ppTypeDescr) SAL_THROW_EXTERN_C()
#define SAL_MAX_INT32
ResultType type
#define USE_DOUBLE_MMAP