1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
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>
37 #include <unordered_map>
46 #define WIN32_LEAN_AND_MEAN
49 #error Unsupported platform
52 #if defined USE_DOUBLE_MMAP
56 #if defined MACOSX && defined __aarch64__
60 using bridges::cpp_uno::shared::VtableFactory
;
64 extern "C" void * allocExec(
65 SAL_UNUSED_PARAMETER rtl_arena_type
*, sal_Size
* size
)
69 #if defined FREEBSD || defined NETBSD || defined OPENBSD || defined DRAGONFLY || defined HAIKU
70 pagesize
= getpagesize();
72 pagesize
= sysconf(_SC_PAGESIZE
);
77 pagesize
= info
.dwPageSize
;
79 #error Unsupported platform
81 std::size_t n
= (*size
+ (pagesize
- 1)) & ~(pagesize
- 1);
86 nullptr, n
, PROT_READ
| PROT_WRITE
| PROT_EXEC
, MAP_PRIVATE
| MAP_ANON
| MAP_JIT
, -1,
88 if (p
!= MAP_FAILED
) {
93 SAL_INFO("bridges.osx", "mmap failed with " << e
);
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:
104 nullptr, n
, PROT_READ
| PROT_WRITE
, MAP_PRIVATE
| MAP_ANON
, -1,
106 if (p
== MAP_FAILED
) {
109 else if (mprotect (p
, n
, PROT_READ
| PROT_WRITE
| PROT_EXEC
) == -1)
118 p
= VirtualAlloc(nullptr, n
, MEM_COMMIT
, PAGE_EXECUTE_READWRITE
);
126 extern "C" void freeExec(
127 SAL_UNUSED_PARAMETER rtl_arena_type
*, void * address
, sal_Size size
)
130 munmap(address
, size
);
132 (void) size
; // unused
133 VirtualFree(address
, 0, MEM_RELEASE
);
139 class VtableFactory::GuardedBlocks
:
140 public std::vector
<Block
>
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) {}
151 void unguard() { m_guarded
= false; }
154 VtableFactory
const & m_factory
;
158 VtableFactory::GuardedBlocks::~GuardedBlocks() {
160 for (iterator
i(begin()); i
!= end(); ++i
) {
161 m_factory
.freeBlock(*i
);
166 class VtableFactory::BaseOffset
{
168 explicit BaseOffset(typelib_InterfaceTypeDescription
* type
) { calculate(type
, 0); }
170 sal_Int32
getFunctionOffset(OUString
const & name
) const
171 { return m_map
.find(name
)->second
; }
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
);
197 VtableFactory::VtableFactory(): m_arena(
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);
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
;
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);
250 // Try non-doublemmaped allocation first:
251 block
.start
= block
.exec
= rtl_arena_alloc(m_arena
, &block
.size
);
252 if (block
.start
!= nullptr) {
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
));
278 unlink(tmpfname
.get());
280 #if defined(HAVE_POSIX_FALLOCATE)
281 int err
= posix_fallocate(block
.fd
, 0, block
.size
);
283 int err
= ftruncate(block
.fd
, block
.size
);
287 #if defined(HAVE_POSIX_FALLOCATE)
288 SAL_WARN("bridges", "posix_fallocate failed with code " << err
);
290 SAL_WARN("bridges", "truncation of executable memory area failed with code " << err
);
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;
306 if (block
.start
&& block
.exec
&& block
.fd
!= -1)
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
);
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
);
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
);
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);
349 if (includePrimary
) {
351 = bridges::cpp_uno::shared::getPrimaryFunctions(type
);
353 if (!createBlock(block
, slotCount
)) {
354 throw std::bad_alloc();
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(
368 #ifdef USE_DOUBLE_MMAP
369 reinterpret_cast<sal_uIntPtr
>(block
.exec
) - reinterpret_cast<sal_uIntPtr
>(block
.start
),
372 baseOffset
.getFunctionOffset(type2
->aBase
.pTypeName
),
373 bridges::cpp_uno::shared::getLocalFunctions(type2
),
376 flushCode(codeBegin
, code
);
377 #ifdef USE_DOUBLE_MMAP
378 //Finished generating block, swap writable pointer with executable
380 std::swap(block
.start
, block
.exec
);
382 blocks
.push_back(block
);
388 #if defined MACOSX && defined __aarch64__
389 pthread_jit_write_protect_np(1);
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);
399 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */