• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

realm / realm-core / 1672

15 Sep 2023 05:11PM UTC coverage: 91.217% (+0.02%) from 91.193%
1672

push

Evergreen

web-flow
Fix open async when rerun on open is set. (#6973)

96008 of 175924 branches covered (0.0%)

160 of 170 new or added lines in 3 files covered. (94.12%)

48 existing lines in 15 files now uncovered.

233765 of 256274 relevant lines covered (91.22%)

7112563.38 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.54
/src/realm/db.cpp
1
/*************************************************************************
2
 *
3
 * Copyright 2016 Realm Inc.
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 *
9
 * http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 *
17
 **************************************************************************/
18

19
#include <realm/transaction.hpp>
20

21
#include <algorithm>
22
#include <atomic>
23
#include <cerrno>
24
#include <fcntl.h>
25
#include <iostream>
26
#include <mutex>
27
#include <sstream>
28
#include <type_traits>
29
#include <random>
30
#include <deque>
31
#include <thread>
32
#include <chrono>
33
#include <condition_variable>
34

35
#include <realm/disable_sync_to_disk.hpp>
36
#include <realm/group_writer.hpp>
37
#include <realm/impl/simulated_failure.hpp>
38
#include <realm/replication.hpp>
39
#include <realm/util/errno.hpp>
40
#include <realm/util/features.h>
41
#include <realm/util/file_mapper.hpp>
42
#include <realm/util/safe_int_ops.hpp>
43
#include <realm/util/scope_exit.hpp>
44
#include <realm/util/thread.hpp>
45
#include <realm/util/to_string.hpp>
46

47
#ifndef _WIN32
48
#include <sys/wait.h>
49
#include <sys/time.h>
50
#include <unistd.h>
51
#else
52
#include <windows.h>
53
#include <process.h>
54
#endif
55

56
// #define REALM_ENABLE_LOGFILE
57

58

59
using namespace realm;
60
using namespace realm::metrics;
61
using namespace realm::util;
62
using Durability = DBOptions::Durability;
63

64
namespace {
65

66
// value   change
67
// --------------------
68
//  4      Unknown
69
//  5      Introduction of SharedInfo::file_format_version and
70
//         SharedInfo::history_type.
71
//  6      Using new robust mutex emulation where applicable
72
//  7      Introducing `commit_in_critical_phase` and `sync_agent_present`, and
73
//         changing `daemon_started` and `daemon_ready` from 1-bit to 8-bit
74
//         fields.
75
//  8      Placing the commitlog history inside the Realm file.
76
//  9      Fair write transactions requires an additional condition variable,
77
//         `write_fairness`
78
// 10      Introducing SharedInfo::history_schema_version.
79
// 11      New impl of InterprocessCondVar on windows.
80
// 12      Change `number_of_versions` to an atomic rather than guarding it
81
//         with a lock.
82
// 13      New impl of VersionList and added mutex for it (former RingBuffer)
83
// 14      Added field for tracking ongoing encrypted writes
84
const uint_fast16_t g_shared_info_version = 14;
85

86

87
struct VersionList {
88
    // the VersionList is an array of ReadCount structures.
89
    // it is placed in the "lock-file" and accessed via memory mapping
90
    struct ReadCount {
91
        uint64_t version;
92
        uint64_t filesize;
93
        uint64_t current_top;
94
        uint32_t count_live;
95
        uint32_t count_frozen;
96
        uint32_t count_full;
97
        bool is_active()
98
        {
145,338,909✔
99
            return version != 0;
145,338,909✔
100
        }
145,338,909✔
101
        void deactivate()
102
        {
10,437,807✔
103
            version = 0;
10,437,807✔
104
            count_live = count_frozen = count_full = 0;
10,437,807✔
105
        }
10,437,807✔
106
        void activate(uint64_t v)
107
        {
1,505,691✔
108
            version = v;
1,505,691✔
109
        }
1,505,691✔
110
    };
111

112
    void reserve(uint32_t size) noexcept
113
    {
287,355✔
114
        for (auto i = entries; i < size; ++i)
9,482,385✔
115
            data()[i].deactivate();
9,195,030✔
116
        if (size > entries) {
287,355✔
117
            // Fence preventing downward motion of above writes
141,450✔
118
            std::atomic_signal_fence(std::memory_order_release);
287,352✔
119
            entries = size;
287,352✔
120
        }
287,352✔
121
    }
287,355✔
122

123
    VersionList() noexcept
124
    {
143,037✔
125
        newest = nil; // empty
143,037✔
126
        entries = 0;
143,037✔
127
        reserve(init_readers_size);
143,037✔
128
    }
143,037✔
129

130
    static size_t compute_required_space(uint_fast32_t num_entries) noexcept
131
    {
143,877✔
132
        // get space required for given number of entries beyond the initial count.
70,668✔
133
        // NB: this not the size of the VersionList, it is the size minus whatever was
70,668✔
134
        // the initial size.
70,668✔
135
        return sizeof(ReadCount) * (num_entries - init_readers_size);
143,877✔
136
    }
143,877✔
137

138
    unsigned int capacity() const noexcept
139
    {
2,728,890✔
140
        return entries;
2,728,890✔
141
    }
2,728,890✔
142

143
    ReadCount& get(uint_fast32_t idx) noexcept
144
    {
6,200,892✔
145
        return data()[idx];
6,200,892✔
146
    }
6,200,892✔
147

148
    ReadCount& get_newest() noexcept
149
    {
×
150
        return get(newest);
×
151
    }
×
152
    // returns nullptr if all entries are in use
153
    ReadCount* try_allocate_entry(uint64_t top, uint64_t size, uint64_t version)
154
    {
1,505,676✔
155
        auto i = allocating.load();
1,505,676✔
156
        if (i == newest.load()) {
1,505,676✔
157
            // if newest != allocating we are recovering from a crash and MUST complete the earlier allocation
686,565✔
158
            // but if not, find lowest free entry by linear search.
686,565✔
159
            uint32_t k = 0;
1,361,373✔
160
            while (k < entries && data()[k].is_active()) {
2,482,638✔
161
                ++k;
1,121,265✔
162
            }
1,121,265✔
163
            if (k == entries)
1,361,373✔
164
                return nullptr;     // no free entries
18✔
165
            allocating.exchange(k); // barrier: prevent upward movement of instructions below
1,361,355✔
166
            i = k;
1,361,355✔
167
        }
1,361,355✔
168
        auto& rc = data()[i];
1,505,667✔
169
        REALM_ASSERT(rc.count_frozen == 0);
1,505,658✔
170
        REALM_ASSERT(rc.count_live == 0);
1,505,658✔
171
        REALM_ASSERT(rc.count_full == 0);
1,505,658✔
172
        rc.current_top = top;
1,505,658✔
173
        rc.filesize = size;
1,505,658✔
174
        rc.activate(version);
1,505,658✔
175
        newest.store(i); // barrier: prevent downward movement of instructions above
1,505,658✔
176
        return &rc;
1,505,658✔
177
    }
1,505,676✔
178

179
    uint32_t index_of(const ReadCount& rc) noexcept
180
    {
1,242,828✔
181
        return (uint32_t)(&rc - data());
1,242,828✔
182
    }
1,242,828✔
183

184
    void free_entry(ReadCount* rc) noexcept
185
    {
1,242,831✔
186
        rc->current_top = rc->filesize = -1ULL; // easy to recognize in debugger
1,242,831✔
187
        rc->deactivate();
1,242,831✔
188
    }
1,242,831✔
189

190
    // This method resets the version list to an empty state, then allocates an entry.
191
    // Precondition: This should *only* be done if the caller has established that she
192
    // is the only thread/process that has access to the VersionList. It is currently
193
    // called from init_versioning(), which is called by DB::open() under the
194
    // condition that it is the session initiator and under guard by the control mutex,
195
    // thus ensuring the precondition. It is also called from compact() in a similar situation.
196
    // It is most likely not suited for any other use.
197
    ReadCount& init_versioning(uint64_t top, uint64_t filesize, uint64_t version) noexcept
198
    {
144,297✔
199
        newest = nil;
144,297✔
200
        allocating = 0;
144,297✔
201
        auto t_free = entries;
144,297✔
202
        entries = 0;
144,297✔
203
        reserve(t_free);
144,297✔
204
        return *try_allocate_entry(top, filesize, version);
144,297✔
205
    }
144,297✔
206

207
    void purge_versions(uint64_t& oldest_live_v, TopRefMap& top_refs, bool& any_new_unreachables)
208
    {
1,361,343✔
209
        oldest_live_v = std::numeric_limits<uint64_t>::max();
1,361,343✔
210
        auto oldest_full_v = std::numeric_limits<uint64_t>::max();
1,361,343✔
211
        any_new_unreachables = false;
1,361,343✔
212
        // correct case where an earlier crash may have left the entry at 'allocating' partially initialized:
686,511✔
213
        const auto index_of_newest = newest.load();
1,361,343✔
214
        if (auto a = allocating.load(); a != index_of_newest) {
1,361,343✔
215
            data()[a].deactivate();
×
216
        }
×
217
        // determine fully locked versions - after one of those all versions are considered live.
686,511✔
218
        for (auto* rc = data(); rc < data() + entries; ++rc) {
45,413,925✔
219
            if (!rc->is_active())
44,052,582✔
220
                continue;
40,702,923✔
221
            if (rc->count_full) {
3,349,659✔
222
                if (rc->version < oldest_full_v)
×
223
                    oldest_full_v = rc->version;
×
224
            }
×
225
        }
3,349,659✔
226
        // collect reachable versions and determine oldest live reachable version
686,511✔
227
        // (oldest reachable version is the first entry in the top_refs map, so no need to find it explicitly)
686,511✔
228
        for (auto* rc = data(); rc < data() + entries; ++rc) {
45,415,152✔
229
            if (!rc->is_active())
44,053,809✔
230
                continue;
40,704,066✔
231
            if (rc->count_frozen || rc->count_live || rc->version >= oldest_full_v) {
3,349,743✔
232
                // entry is still reachable
1,066,209✔
233
                top_refs.emplace(rc->version, VersionInfo{to_ref(rc->current_top), to_ref(rc->filesize)});
2,107,371✔
234
            }
2,107,371✔
235
            if (rc->count_live || rc->version >= oldest_full_v) {
3,349,743✔
236
                if (rc->version < oldest_live_v)
1,554,498✔
237
                    oldest_live_v = rc->version;
1,424,445✔
238
            }
1,554,498✔
239
        }
3,349,743✔
240
        // we must have found at least one reachable version
686,511✔
241
        REALM_ASSERT(top_refs.size());
1,361,343✔
242
        // free unreachable entries and determine if we want to trigger backdating
686,511✔
243
        uint64_t oldest_v = top_refs.begin()->first;
1,361,343✔
244
        for (auto* rc = data(); rc < data() + entries; ++rc) {
45,415,092✔
245
            if (!rc->is_active())
44,053,749✔
246
                continue;
40,703,808✔
247
            if (rc->count_frozen == 0 && rc->count_live == 0 && rc->version < oldest_full_v) {
3,349,941✔
248
                // entry is becoming unreachable.
628,173✔
249
                // if it is also younger than a reachable version, then set 'any_new_unreachables' to trigger
628,173✔
250
                // backdating
628,173✔
251
                if (rc->version > oldest_v) {
1,242,828✔
252
                    any_new_unreachables = true;
60,510✔
253
                }
60,510✔
254
                REALM_ASSERT(index_of(*rc) != index_of_newest);
1,242,828✔
255
                free_entry(rc);
1,242,828✔
256
            }
1,242,828✔
257
        }
3,349,941✔
258
        REALM_ASSERT(oldest_v != std::numeric_limits<uint64_t>::max());
1,361,343✔
259
        REALM_ASSERT(oldest_live_v != std::numeric_limits<uint64_t>::max());
1,361,343✔
260
    }
1,361,343✔
261

262
#if REALM_DEBUG
263
    void dump()
264
    {
×
265
        util::format(std::cout, "VersionList has %1 entries: \n", entries);
×
266
        for (auto* rc = data(); rc < data() + entries; ++rc) {
×
267
            util::format(std::cout, "[%1]: version %2, live: %3, full: %4, frozen: %5\n", index_of(*rc), rc->version,
×
268
                         rc->count_live, rc->count_full, rc->count_frozen);
×
269
        }
×
270
    }
×
271
#endif // REALM_DEBUG
272

273
    constexpr static uint32_t nil = (uint32_t)-1;
274
    const static int init_readers_size = 32;
275
    uint32_t entries;
276
    std::atomic<uint32_t> allocating; // atomic for crash safety, not threading
277
    std::atomic<uint32_t> newest;     // atomic for crash safety, not threading
278

279
    // IMPORTANT: The actual data comprising the version list MUST BE PLACED LAST in
280
    // the VersionList structure, as the data area is extended at run time.
281
    // Similarly, the VersionList must be the final element of the SharedInfo structure.
282
    // IMPORTANT II:
283
    // To ensure proper alignment across all platforms, the SharedInfo structure
284
    // should NOT have a stricter alignment requirement than the ReadCount structure.
285
    ReadCount m_data[init_readers_size];
286

287
    // Silence UBSan errors about out-of-bounds reads on m_data by casting to a pointer
288
    ReadCount* data() noexcept
289
    {
160,917,774✔
290
        return m_data;
160,917,774✔
291
    }
160,917,774✔
292
    const ReadCount* data() const noexcept
293
    {
×
294
        return m_data;
×
295
    }
×
296
};
297

298
// Using lambda rather than function so that shared_ptr shared state doesn't need to hold a function pointer.
299
constexpr auto TransactionDeleter = [](Transaction* t) {
2,639,523✔
300
    t->close();
2,639,523✔
301
    delete t;
2,639,523✔
302
};
2,639,523✔
303

304
template <typename... Args>
305
TransactionRef make_transaction_ref(Args&&... args)
306
{
2,643,054✔
307
    return TransactionRef(new Transaction(std::forward<Args>(args)...), TransactionDeleter);
2,643,054✔
308
}
2,643,054✔
309

310
} // anonymous namespace
311

312
namespace realm {
313

314
/// The structure of the contents of the per session `.lock` file. Note that
315
/// this file is transient in that it is recreated/reinitialized at the
316
/// beginning of every session. A session is any sequence of temporally
317
/// overlapping openings of a particular Realm file via DB objects. For
318
/// example, if there are two DB objects, A and B, and the file is
319
/// first opened via A, then opened via B, then closed via A, and finally closed
320
/// via B, then the session streaches from the opening via A to the closing via
321
/// B.
322
///
323
/// IMPORTANT: Remember to bump `g_shared_info_version` if anything is changed
324
/// in the memory layout of this class, or if the meaning of any of the stored
325
/// values change.
326
///
327
/// Members `init_complete`, `shared_info_version`, `size_of_mutex`, and
328
/// `size_of_condvar` may only be modified only while holding an exclusive lock
329
/// on the file, and may be read only while holding a shared (or exclusive) lock
330
/// on the file. All other members (except for the VersionList which has its own mutex)
331
/// may be accessed only while holding a lock on `controlmutex`.
332
///
333
/// SharedInfo must be 8-byte aligned. On 32-bit Apple platforms, mutexes store their
334
/// alignment as part of the mutex state. We're copying the SharedInfo (including
335
/// embedded but alway unlocked mutexes) and it must retain the same alignment
336
/// throughout.
337
struct alignas(8) DB::SharedInfo {
338
    /// Indicates that initialization of the lock file was completed
339
    /// sucessfully.
340
    ///
341
    /// CAUTION: This member must never move or change type, as that would
342
    /// compromize safety of the the session initiation process.
343
    std::atomic<uint8_t> init_complete; // Offset 0
344

345
    /// The size in bytes of a mutex member of SharedInfo. This allows all
346
    /// session participants to be in agreement. Obviously, a size match is not
347
    /// enough to guarantee identical layout internally in the mutex object, but
348
    /// it is hoped that it will catch some (if not most) of the cases where
349
    /// there is a layout discrepancy internally in the mutex object.
350
    uint8_t size_of_mutex; // Offset 1
351

352
    /// Like size_of_mutex, but for condition variable members of SharedInfo.
353
    uint8_t size_of_condvar; // Offset 2
354

355
    /// Set during the critical phase of a commit, when the logs, the VersionList
356
    /// and the database may be out of sync with respect to each other. If a
357
    /// writer crashes during this phase, there is no safe way of continuing
358
    /// with further write transactions. When beginning a write transaction,
359
    /// this must be checked and an exception thrown if set.
360
    ///
361
    /// Note that std::atomic<uint8_t> is guaranteed to have standard layout.
362
    std::atomic<uint8_t> commit_in_critical_phase = {0}; // Offset 3
363

364
    /// The target Realm file format version for the current session. This
365
    /// allows all session participants to be in agreement. It can only differ
366
    /// from what is returned by Group::get_file_format_version() temporarily,
367
    /// and only during the Realm file opening process. If it differs, it means
368
    /// that the file format needs to be upgraded from its current format
369
    /// (Group::get_file_format_version()), the format specified by this member
370
    /// of SharedInfo.
371
    uint8_t file_format_version; // Offset 4
372

373
    /// Stores a value of type Replication::HistoryType. Must match across all
374
    /// session participants.
375
    int8_t history_type; // Offset 5
376

377
    /// The SharedInfo layout version. This allows all session participants to
378
    /// be in agreement. Must be bumped if the layout of the SharedInfo
379
    /// structure is changed. Note, however, that only the part that lies beyond
380
    /// SharedInfoUnchangingLayout can have its layout changed.
381
    ///
382
    /// CAUTION: This member must never move or change type, as that would
383
    /// compromize version agreement checking.
384
    uint16_t shared_info_version = g_shared_info_version; // Offset 6
385

386
    uint16_t durability;           // Offset 8
387
    uint16_t free_write_slots = 0; // Offset 10
388

389
    /// Number of participating shared groups
390
    uint32_t num_participants = 0; // Offset 12
391

392
    /// Latest version number. Guarded by the controlmutex (for lock-free
393
    /// access, use get_version_of_latest_snapshot() instead)
394
    uint64_t latest_version_number; // Offset 16
395

396
    /// Pid of process initiating the session, but only if that process runs
397
    /// with encryption enabled, zero otherwise. This was used to prevent
398
    /// multiprocess encryption until support for that was added.
399
    uint64_t session_initiator_pid = 0; // Offset 24
400

401
    std::atomic<uint64_t> number_of_versions; // Offset 32
402

403
    /// True (1) if there is a sync agent present (a session participant acting
404
    /// as sync client). It is an error to have a session with more than one
405
    /// sync agent. The purpose of this flag is to prevent that from ever
406
    /// happening. If the sync agent crashes and leaves the flag set, the
407
    /// session will need to be restarted (lock file reinitialized) before a new
408
    /// sync agent can be started.
409
    uint8_t sync_agent_present = 0; // Offset 40
410

411
    /// Set when a participant decides to start the daemon, cleared by the
412
    /// daemon when it decides to exit. Participants check during open() and
413
    /// start the daemon if running in async mode.
414
    uint8_t daemon_started = 0; // Offset 41
415

416
    /// Set by the daemon when it is ready to handle commits. Participants must
417
    /// wait during open() on 'daemon_becomes_ready' for this to become true.
418
    /// Cleared by the daemon when it decides to exit.
419
    uint8_t daemon_ready = 0; // Offset 42
420

421
    uint8_t filler_1; // Offset 43
422

423
    /// Stores a history schema version (as returned by
424
    /// Replication::get_history_schema_version()). Must match across all
425
    /// session participants.
426
    uint16_t history_schema_version; // Offset 44
427

428
    uint16_t filler_2; // Offset 46
429

430
    InterprocessMutex::SharedPart shared_writemutex; // Offset 48
431
    InterprocessMutex::SharedPart shared_controlmutex;
432
    InterprocessMutex::SharedPart shared_versionlist_mutex;
433
    InterprocessCondVar::SharedPart room_to_write;
434
    InterprocessCondVar::SharedPart work_to_do;
435
    InterprocessCondVar::SharedPart daemon_becomes_ready;
436
    InterprocessCondVar::SharedPart new_commit_available;
437
    InterprocessCondVar::SharedPart pick_next_writer;
438
    std::atomic<uint32_t> next_ticket;
439
    std::atomic<uint32_t> next_served = 0;
440
    std::atomic<uint64_t> writing_page_offset;
441
    std::atomic<uint64_t> write_counter;
442

443
    // IMPORTANT: The VersionList MUST be the last field in SharedInfo - see above.
444
    VersionList readers;
445

446
    SharedInfo(Durability, Replication::HistoryType, int history_schema_version);
447
    ~SharedInfo() noexcept {}
25,260✔
448

449
    void init_versioning(ref_type top_ref, size_t file_size, uint64_t initial_version)
450
    {
144,297✔
451
        // Create our first versioning entry:
71,022✔
452
        readers.init_versioning(top_ref, file_size, initial_version);
144,297✔
453
    }
144,297✔
454
};
455

456

457
DB::SharedInfo::SharedInfo(Durability dura, Replication::HistoryType ht, int hsv)
458
    : size_of_mutex(sizeof(shared_writemutex))
459
    , size_of_condvar(sizeof(room_to_write))
460
    , shared_writemutex()   // Throws
461
    , shared_controlmutex() // Throws
462
{
143,040✔
463
    durability = static_cast<uint16_t>(dura); // durability level is fixed from creation
143,040✔
464
    REALM_ASSERT(!util::int_cast_has_overflow<decltype(history_type)>(ht + 0));
143,040✔
465
    REALM_ASSERT(!util::int_cast_has_overflow<decltype(history_schema_version)>(hsv));
143,040✔
466
    history_type = ht;
143,040✔
467
    history_schema_version = static_cast<uint16_t>(hsv);
143,040✔
468
    InterprocessCondVar::init_shared_part(new_commit_available); // Throws
143,040✔
469
    InterprocessCondVar::init_shared_part(pick_next_writer);     // Throws
143,040✔
470
    next_ticket = 0;
143,040✔
471

70,422✔
472
// IMPORTANT: The offsets, types (, and meanings) of these members must
70,422✔
473
// never change, not even when the SharedInfo layout version is bumped. The
70,422✔
474
// eternal constancy of this part of the layout is what ensures that a
70,422✔
475
// joining session participant can reliably verify that the actual format is
70,422✔
476
// as expected.
70,422✔
477
#ifndef _WIN32
143,040✔
478
#pragma GCC diagnostic push
143,040✔
479
#pragma GCC diagnostic ignored "-Winvalid-offsetof"
143,040✔
480
#endif
143,040✔
481
    static_assert(offsetof(SharedInfo, init_complete) == 0 && ATOMIC_BOOL_LOCK_FREE == 2 &&
143,040✔
482
                      std::is_same<decltype(init_complete), std::atomic<uint8_t>>::value &&
143,040✔
483
                      offsetof(SharedInfo, shared_info_version) == 6 &&
143,040✔
484
                      std::is_same<decltype(shared_info_version), uint16_t>::value,
143,040✔
485
                  "Forbidden change in SharedInfo layout");
143,040✔
486

70,422✔
487
    // Try to catch some of the memory layout changes that requires bumping of
70,422✔
488
    // the SharedInfo file format version (shared_info_version).
70,422✔
489
    static_assert(
143,040✔
490
        offsetof(SharedInfo, size_of_mutex) == 1 && std::is_same<decltype(size_of_mutex), uint8_t>::value &&
143,040✔
491
            offsetof(SharedInfo, size_of_condvar) == 2 && std::is_same<decltype(size_of_condvar), uint8_t>::value &&
143,040✔
492
            offsetof(SharedInfo, commit_in_critical_phase) == 3 &&
143,040✔
493
            std::is_same<decltype(commit_in_critical_phase), std::atomic<uint8_t>>::value &&
143,040✔
494
            offsetof(SharedInfo, file_format_version) == 4 &&
143,040✔
495
            std::is_same<decltype(file_format_version), uint8_t>::value && offsetof(SharedInfo, history_type) == 5 &&
143,040✔
496
            std::is_same<decltype(history_type), int8_t>::value && offsetof(SharedInfo, durability) == 8 &&
143,040✔
497
            std::is_same<decltype(durability), uint16_t>::value && offsetof(SharedInfo, free_write_slots) == 10 &&
143,040✔
498
            std::is_same<decltype(free_write_slots), uint16_t>::value &&
143,040✔
499
            offsetof(SharedInfo, num_participants) == 12 &&
143,040✔
500
            std::is_same<decltype(num_participants), uint32_t>::value &&
143,040✔
501
            offsetof(SharedInfo, latest_version_number) == 16 &&
143,040✔
502
            std::is_same<decltype(latest_version_number), uint64_t>::value &&
143,040✔
503
            offsetof(SharedInfo, session_initiator_pid) == 24 &&
143,040✔
504
            std::is_same<decltype(session_initiator_pid), uint64_t>::value &&
143,040✔
505
            offsetof(SharedInfo, number_of_versions) == 32 &&
143,040✔
506
            std::is_same<decltype(number_of_versions), std::atomic<uint64_t>>::value &&
143,040✔
507
            offsetof(SharedInfo, sync_agent_present) == 40 &&
143,040✔
508
            std::is_same<decltype(sync_agent_present), uint8_t>::value &&
143,040✔
509
            offsetof(SharedInfo, daemon_started) == 41 && std::is_same<decltype(daemon_started), uint8_t>::value &&
143,040✔
510
            offsetof(SharedInfo, daemon_ready) == 42 && std::is_same<decltype(daemon_ready), uint8_t>::value &&
143,040✔
511
            offsetof(SharedInfo, filler_1) == 43 && std::is_same<decltype(filler_1), uint8_t>::value &&
143,040✔
512
            offsetof(SharedInfo, history_schema_version) == 44 &&
143,040✔
513
            std::is_same<decltype(history_schema_version), uint16_t>::value && offsetof(SharedInfo, filler_2) == 46 &&
143,040✔
514
            std::is_same<decltype(filler_2), uint16_t>::value && offsetof(SharedInfo, shared_writemutex) == 48 &&
143,040✔
515
            std::is_same<decltype(shared_writemutex), InterprocessMutex::SharedPart>::value,
143,040✔
516
        "Caught layout change requiring SharedInfo file format bumping");
143,040✔
517
    static_assert(std::atomic<uint64_t>::is_always_lock_free);
143,040✔
518
#ifndef _WIN32
143,040✔
519
#pragma GCC diagnostic pop
143,040✔
520
#endif
143,040✔
521
}
143,040✔
522

523
class DB::VersionManager {
524
public:
525
    VersionManager(util::InterprocessMutex& mutex)
526
        : m_mutex(mutex)
527
    {
169,119✔
528
    }
169,119✔
529
    virtual ~VersionManager() {}
169,119✔
530

531
    void cleanup_versions(uint64_t& oldest_live_version, TopRefMap& top_refs, bool& any_new_unreachables)
532
        REQUIRES(!m_info_mutex)
533
    {
1,361,382✔
534
        std::lock_guard lock(m_mutex);
1,361,382✔
535
        util::CheckedLockGuard info_lock(m_info_mutex);
1,361,382✔
536
        ensure_reader_mapping();
1,361,382✔
537
        m_info->readers.purge_versions(oldest_live_version, top_refs, any_new_unreachables);
1,361,382✔
538
    }
1,361,382✔
539

540
    version_type get_newest_version() REQUIRES(!m_local_readers_mutex, !m_info_mutex)
541
    {
1,361,358✔
542
        return get_version_id_of_latest_snapshot().version;
1,361,358✔
543
    }
1,361,358✔
544

545
    VersionID get_version_id_of_latest_snapshot() REQUIRES(!m_local_readers_mutex, !m_info_mutex)
546
    {
2,194,635✔
547
        {
2,194,635✔
548
            // First check the local cache. This is an unlocked read, so it may
1,305,309✔
549
            // race with adding a new version. If this happens we'll either see
1,305,309✔
550
            // a stale value (acceptable for a racing write on one thread and
1,305,309✔
551
            // a read on another), or a new value which is guaranteed to not
1,305,309✔
552
            // be an active index in the local cache.
1,305,309✔
553
            util::CheckedLockGuard lock(m_local_readers_mutex);
2,194,635✔
554
            util::CheckedLockGuard info_lock(m_info_mutex);
2,194,635✔
555
            auto index = m_info->readers.newest.load();
2,194,635✔
556
            if (index < m_local_readers.size()) {
2,194,680✔
557
                auto& r = m_local_readers[index];
2,194,680✔
558
                if (r.is_active()) {
2,194,680✔
559
                    return {r.version, index};
2,190,663✔
560
                }
2,190,663✔
561
            }
3,972✔
562
        }
3,972✔
563

1,701✔
564
        std::lock_guard lock(m_mutex);
3,972✔
565
        util::CheckedLockGuard info_lock(m_info_mutex);
3,972✔
566
        auto index = m_info->readers.newest.load();
3,972✔
567
        ensure_reader_mapping(index);
3,972✔
568
        return {m_info->readers.get(index).version, index};
3,972✔
569
    }
3,972✔
570

571
    void release_read_lock(const ReadLockInfo& read_lock) REQUIRES(!m_local_readers_mutex, !m_info_mutex)
572
    {
5,728,449✔
573
        {
5,728,449✔
574
            util::CheckedLockGuard lock(m_local_readers_mutex);
5,728,449✔
575
            REALM_ASSERT(read_lock.m_reader_idx < m_local_readers.size());
5,728,449✔
576
            auto& r = m_local_readers[read_lock.m_reader_idx];
5,728,449✔
577
            auto& f = field_for_type(r, read_lock.m_type);
5,728,449✔
578
            REALM_ASSERT(f > 0);
5,728,449✔
579
            if (--f > 0)
5,728,449✔
580
                return;
2,629,977✔
581
            if (r.count_live == 0 && r.count_full == 0 && r.count_frozen == 0)
3,098,472✔
582
                r.version = 0;
3,073,239✔
583
        }
3,098,472✔
584

1,555,299✔
585
        std::lock_guard lock(m_mutex);
3,098,472✔
586
        util::CheckedLockGuard info_lock(m_info_mutex);
3,098,472✔
587
        // we should not need to call ensure_full_reader_mapping,
1,555,299✔
588
        // since releasing a read lock means it has been grabbed
1,555,299✔
589
        // earlier - and hence must reside in mapped memory:
1,555,299✔
590
        REALM_ASSERT(read_lock.m_reader_idx < m_local_max_entry);
3,098,472✔
591
        auto& r = m_info->readers.get(read_lock.m_reader_idx);
3,098,472✔
592
        REALM_ASSERT(read_lock.m_version == r.version);
3,098,472✔
593
        --field_for_type(r, read_lock.m_type);
3,098,472✔
594
    }
3,098,472✔
595

596
    ReadLockInfo grab_read_lock(ReadLockInfo::Type type, VersionID version_id = {})
597
        REQUIRES(!m_local_readers_mutex, !m_info_mutex)
598
    {
5,728,431✔
599
        ReadLockInfo read_lock;
5,728,431✔
600
        if (try_grab_local_read_lock(read_lock, type, version_id))
5,728,431✔
601
            return read_lock;
2,629,980✔
602

1,555,314✔
603
        {
3,098,451✔
604
            const bool pick_specific = version_id.version != VersionID().version;
3,098,451✔
605
            std::lock_guard lock(m_mutex);
3,098,451✔
606
            util::CheckedLockGuard info_lock(m_info_mutex);
3,098,451✔
607
            auto newest = m_info->readers.newest.load();
3,098,451✔
608
            REALM_ASSERT(newest != VersionList::nil);
3,098,451✔
609
            read_lock.m_reader_idx = pick_specific ? version_id.index : newest;
3,091,689✔
610
            ensure_reader_mapping((unsigned int)read_lock.m_reader_idx);
3,098,451✔
611
            bool picked_newest = read_lock.m_reader_idx == (unsigned)newest;
3,098,451✔
612
            auto& r = m_info->readers.get(read_lock.m_reader_idx);
3,098,451✔
613
            if (pick_specific && version_id.version != r.version)
3,098,451✔
614
                throw BadVersion(version_id.version);
72✔
615
            if (!picked_newest) {
3,098,379✔
616
                if (type == ReadLockInfo::Frozen && r.count_frozen == 0 && r.count_live == 0)
702✔
617
                    throw BadVersion(version_id.version);
×
618
                if (type != ReadLockInfo::Frozen && r.count_live == 0)
702✔
619
                    throw BadVersion(version_id.version);
60✔
620
            }
3,098,319✔
621
            populate_read_lock(read_lock, r, type);
3,098,319✔
622
        }
3,098,319✔
623

1,555,248✔
624
        {
3,098,319✔
625
            util::CheckedLockGuard local_lock(m_local_readers_mutex);
3,098,319✔
626
            grow_local_cache(read_lock.m_reader_idx + 1);
3,098,319✔
627
            auto& r2 = m_local_readers[read_lock.m_reader_idx];
3,098,319✔
628
            if (!r2.is_active()) {
3,098,319✔
629
                r2.version = read_lock.m_version;
3,073,206✔
630
                r2.filesize = read_lock.m_file_size;
3,073,206✔
631
                r2.current_top = read_lock.m_top_ref;
3,073,206✔
632
                r2.count_full = r2.count_live = r2.count_frozen = 0;
3,073,206✔
633
            }
3,073,206✔
634
            REALM_ASSERT_EX(field_for_type(r2, type) == 0, type, r2.count_full, r2.count_live, r2.count_frozen);
3,098,319✔
635
            field_for_type(r2, type) = 1;
3,098,319✔
636
        }
3,098,319✔
637

1,555,248✔
638
        return read_lock;
3,098,319✔
639
    }
3,098,319✔
640

641
    void init_versioning(ref_type top_ref, size_t file_size, uint64_t initial_version) REQUIRES(!m_info_mutex)
642
    {
119,037✔
643
        std::lock_guard lock(m_mutex);
119,037✔
644
        util::CheckedLockGuard info_lock(m_info_mutex);
119,037✔
645
        m_info->init_versioning(top_ref, file_size, initial_version);
119,037✔
646
    }
119,037✔
647

648
    void add_version(ref_type new_top_ref, size_t new_file_size, uint64_t new_version) REQUIRES(!m_info_mutex)
649
    {
1,361,358✔
650
        std::lock_guard lock(m_mutex);
1,361,358✔
651
        util::CheckedLockGuard info_lock(m_info_mutex);
1,361,358✔
652
        ensure_reader_mapping();
1,361,358✔
653
        if (m_info->readers.try_allocate_entry(new_top_ref, new_file_size, new_version)) {
1,361,367✔
654
            return;
1,361,358✔
655
        }
1,361,358✔
656
        // allocation failed, expand VersionList (and lockfile) and retry
9✔
657
        auto entries = m_info->readers.capacity();
2,147,483,656✔
658
        auto new_entries = entries + 32;
2,147,483,656✔
659
        expand_version_list(new_entries);
2,147,483,656✔
660
        m_local_max_entry = new_entries;
2,147,483,656✔
661
        m_info->readers.reserve(new_entries);
2,147,483,656✔
662
        auto success = m_info->readers.try_allocate_entry(new_top_ref, new_file_size, new_version);
2,147,483,656✔
663
        REALM_ASSERT_EX(success, new_entries, new_version);
2,147,483,656✔
664
    }
2,147,483,656✔
665

666

667
private:
668
    void grow_local_cache(size_t new_size) REQUIRES(m_local_readers_mutex)
669
    {
3,098,508✔
670
        if (new_size > m_local_readers.size())
3,098,508✔
671
            m_local_readers.resize(new_size, VersionList::ReadCount{});
290,799✔
672
    }
3,098,508✔
673

674
    void populate_read_lock(ReadLockInfo& read_lock, VersionList::ReadCount& r, ReadLockInfo::Type type)
675
    {
5,728,377✔
676
        ++field_for_type(r, type);
5,728,377✔
677
        read_lock.m_type = type;
5,728,377✔
678
        read_lock.m_version = r.version;
5,728,377✔
679
        read_lock.m_top_ref = static_cast<ref_type>(r.current_top);
5,728,377✔
680
        read_lock.m_file_size = static_cast<size_t>(r.filesize);
5,728,377✔
681
    }
5,728,377✔
682

683
    bool try_grab_local_read_lock(ReadLockInfo& read_lock, ReadLockInfo::Type type, VersionID version_id)
684
        REQUIRES(!m_local_readers_mutex, !m_info_mutex)
685
    {
5,728,419✔
686
        const bool pick_specific = version_id.version != VersionID().version;
5,728,419✔
687
        auto index = version_id.index;
5,728,419✔
688
        if (!pick_specific) {
5,728,419✔
689
            util::CheckedLockGuard lock(m_info_mutex);
5,443,920✔
690
            index = m_info->readers.newest.load();
5,443,920✔
691
        }
5,443,920✔
692
        util::CheckedLockGuard local_lock(m_local_readers_mutex);
5,728,419✔
693
        if (index >= m_local_readers.size())
5,728,419✔
694
            return false;
290,805✔
695

3,392,466✔
696
        auto& r = m_local_readers[index];
5,437,614✔
697
        if (!r.is_active())
5,437,614✔
698
            return false;
2,782,569✔
699
        if (pick_specific && r.version != version_id.version)
2,655,045✔
700
            return false;
×
701
        if (field_for_type(r, type) == 0)
2,655,045✔
702
            return false;
25,278✔
703

1,980,090✔
704
        read_lock.m_reader_idx = index;
2,629,767✔
705
        populate_read_lock(read_lock, r, type);
2,629,767✔
706
        return true;
2,629,767✔
707
    }
2,629,767✔
708

709
    static uint32_t& field_for_type(VersionList::ReadCount& r, ReadLockInfo::Type type)
710
    {
23,403,771✔
711
        switch (type) {
23,403,771✔
712
            case ReadLockInfo::Frozen:
173,019✔
713
                return r.count_frozen;
173,019✔
714
            case ReadLockInfo::Live:
23,230,917✔
715
                return r.count_live;
23,230,917✔
716
            case ReadLockInfo::Full:
✔
717
                return r.count_full;
×
718
            default:
✔
719
                REALM_UNREACHABLE(); // silence a warning
×
720
        }
23,403,771✔
721
    }
23,403,771✔
722

723
    void mark_page_for_writing(uint64_t page_offset) REQUIRES(!m_info_mutex)
724
    {
2,517✔
725
        util::CheckedLockGuard info_lock(m_info_mutex);
2,517✔
726
        m_info->writing_page_offset = page_offset + 1;
2,517✔
727
        m_info->write_counter++;
2,517✔
728
    }
2,517✔
729
    void clear_writing_marker() REQUIRES(!m_info_mutex)
730
    {
2,517✔
731
        util::CheckedLockGuard info_lock(m_info_mutex);
2,517✔
732
        m_info->write_counter++;
2,517✔
733
        m_info->writing_page_offset = 0;
2,517✔
734
    }
2,517✔
735
    // returns false if no page is marked.
736
    // if a page is marked, returns true and optionally the offset of the page marked for writing
737
    // in all cases returns optionally the write counter
738
    bool observe_writer(uint64_t* page_offset, uint64_t* write_counter) REQUIRES(!m_info_mutex)
739
    {
90✔
740
        util::CheckedLockGuard info_lock(m_info_mutex);
90✔
741
        if (write_counter) {
90✔
742
            *write_counter = m_info->write_counter;
90✔
743
        }
90✔
744
        uint64_t marked = m_info->writing_page_offset;
90✔
745
        if (marked && page_offset) {
90!
746
            *page_offset = marked - 1;
×
747
        }
×
748
        return marked != 0;
90✔
749
    }
90✔
750

751
protected:
752
    util::InterprocessMutex& m_mutex;
753
    util::CheckedMutex m_local_readers_mutex;
754
    std::vector<VersionList::ReadCount> m_local_readers GUARDED_BY(m_local_readers_mutex);
755

756
    util::CheckedMutex m_info_mutex;
757
    unsigned int m_local_max_entry GUARDED_BY(m_info_mutex) = 0;
758
    SharedInfo* m_info GUARDED_BY(m_info_mutex) = nullptr;
759

760
    virtual void ensure_reader_mapping(unsigned int required = -1) REQUIRES(m_info_mutex) = 0;
761
    virtual void expand_version_list(unsigned new_entries) REQUIRES(m_info_mutex) = 0;
762
    friend class DB::EncryptionMarkerObserver;
763
};
764

765
class DB::FileVersionManager final : public DB::VersionManager {
766
public:
767
    FileVersionManager(File& file, util::InterprocessMutex& mutex)
768
        : VersionManager(mutex)
769
        , m_file(file)
770
    {
143,859✔
771
        size_t size = 0, required_size = sizeof(SharedInfo);
143,859✔
772
        while (size < required_size) {
287,718✔
773
            // Map the file without the lock held. This could result in the
70,659✔
774
            // mapping being too small and having to remap if the file is grown
70,659✔
775
            // concurrently, but if this is the case we should always see a bigger
70,659✔
776
            // size the next time.
70,659✔
777
            auto new_size = static_cast<size_t>(m_file.get_size());
143,859✔
778
            REALM_ASSERT(new_size > size);
143,859✔
779
            size = new_size;
143,859✔
780
            m_reader_map.remap(m_file, File::access_ReadWrite, size, File::map_NoSync);
143,859✔
781
            m_info = m_reader_map.get_addr();
143,859✔
782

70,659✔
783
            std::lock_guard lock(m_mutex);
143,859✔
784
            m_local_max_entry = m_info->readers.capacity();
143,859✔
785
            required_size = sizeof(SharedInfo) + m_info->readers.compute_required_space(m_local_max_entry);
143,859✔
786
            REALM_ASSERT(required_size >= size);
143,859✔
787
        }
143,859✔
788
    }
143,859✔
789

790
    void expand_version_list(unsigned new_entries) override REQUIRES(m_info_mutex)
791
    {
18✔
792
        size_t new_info_size = sizeof(SharedInfo) + m_info->readers.compute_required_space(new_entries);
18✔
793
        m_file.prealloc(new_info_size);                                          // Throws
18✔
794
        m_reader_map.remap(m_file, util::File::access_ReadWrite, new_info_size); // Throws
18✔
795
        m_info = m_reader_map.get_addr();
18✔
796
    }
18✔
797

798
private:
799
    void ensure_reader_mapping(unsigned int required = -1) override REQUIRES(m_info_mutex)
800
    {
5,492,232✔
801
        using _impl::SimulatedFailure;
5,492,232✔
802
        SimulatedFailure::trigger(SimulatedFailure::shared_group__grow_reader_mapping); // Throws
5,492,232✔
803

2,763,756✔
804
        if (required < m_local_max_entry)
5,492,232✔
805
            return;
2,932,722✔
806

1,291,605✔
807
        auto new_max_entry = m_info->readers.capacity();
2,559,510✔
808
        if (new_max_entry > m_local_max_entry) {
2,559,510✔
809
            // handle mapping expansion if required
810
            size_t info_size = sizeof(DB::SharedInfo) + m_info->readers.compute_required_space(new_max_entry);
×
811
            m_reader_map.remap(m_file, util::File::access_ReadWrite, info_size); // Throws
×
812
            m_local_max_entry = new_max_entry;
×
813
            m_info = m_reader_map.get_addr();
×
814
        }
×
815
    }
2,559,510✔
816

817
    File& m_file;
818
    File::Map<DB::SharedInfo> m_reader_map;
819

820
    friend class DB::EncryptionMarkerObserver;
821
};
822

823
// adapter class for marking/observing encrypted writes
824
class DB::EncryptionMarkerObserver : public util::WriteMarker, public util::WriteObserver {
825
public:
826
    EncryptionMarkerObserver(DB::VersionManager& vm)
827
        : vm(vm)
828
    {
143,856✔
829
    }
143,856✔
830
    bool no_concurrent_writer_seen() override
831
    {
90✔
832
        uint64_t tmp_write_count;
90✔
833
        auto page_may_have_been_written = vm.observe_writer(nullptr, &tmp_write_count);
90✔
834
        if (tmp_write_count != last_seen_count) {
90✔
835
            page_may_have_been_written = true;
×
836
            last_seen_count = tmp_write_count;
×
837
        }
×
838
        if (page_may_have_been_written) {
90✔
839
            calls_since_last_writer_observed = 0;
×
840
            return false;
×
841
        }
×
842
        ++calls_since_last_writer_observed;
90✔
843
        constexpr size_t max_calls = 5; // an arbitrary handful, > 1
90✔
844
        return (calls_since_last_writer_observed >= max_calls);
90✔
845
    }
90✔
846
    void mark(uint64_t pos) override
847
    {
2,517✔
848
        vm.mark_page_for_writing(pos);
2,517✔
849
    }
2,517✔
850
    void unmark() override
851
    {
2,517✔
852
        vm.clear_writing_marker();
2,517✔
853
    }
2,517✔
854

855
private:
856
    DB::VersionManager& vm;
857
    uint64_t last_seen_count = 0;
858
    size_t calls_since_last_writer_observed = 0;
859
};
860

861
class DB::InMemoryVersionManager final : public DB::VersionManager {
862
public:
863
    InMemoryVersionManager(SharedInfo* info, util::InterprocessMutex& mutex)
864
        : VersionManager(mutex)
865
    {
25,260✔
866
        m_info = info;
25,260✔
867
        m_local_max_entry = m_info->readers.capacity();
25,260✔
868
    }
25,260✔
869
    void expand_version_list(unsigned) override
870
    {
×
871
        REALM_ASSERT(false);
×
872
    }
×
873

874
private:
875
    void ensure_reader_mapping(unsigned int) override {}
332,862✔
876
};
877

878
#if REALM_HAVE_STD_FILESYSTEM
879
std::string DBOptions::sys_tmp_dir = std::filesystem::temp_directory_path().string();
880
#else
881
std::string DBOptions::sys_tmp_dir = getenv("TMPDIR") ? getenv("TMPDIR") : "";
882
#endif
883

884
// NOTES ON CREATION AND DESTRUCTION OF SHARED MUTEXES:
885
//
886
// According to the 'process-sharing example' in the POSIX man page
887
// for pthread_mutexattr_init() other processes may continue to use a
888
// process-shared mutex after exit of the process that initialized
889
// it. Also, the example does not contain any call to
890
// pthread_mutex_destroy(), so apparently a process-shared mutex need
891
// not be destroyed at all, nor can it be that a process-shared mutex
892
// is associated with any resources that are local to the initializing
893
// process, because that would imply a leak.
894
//
895
// While it is not explicitly guaranteed in the man page, we shall
896
// assume that is is valid to initialize a process-shared mutex twice
897
// without an intervening call to pthread_mutex_destroy(). We need to
898
// be able to reinitialize a process-shared mutex if the first
899
// initializing process crashes and leaves the shared memory in an
900
// undefined state.
901

902
void DB::open(const std::string& path, bool no_create_file, const DBOptions& options)
903
{
143,748✔
904
    // Exception safety: Since do_open() is called from constructors, if it
70,632✔
905
    // throws, it must leave the file closed.
70,632✔
906
    using util::format;
143,748✔
907

70,632✔
908
    REALM_ASSERT(!is_attached());
143,748✔
909
    REALM_ASSERT(path.size());
143,748✔
910

70,632✔
911
    m_db_path = path;
143,748✔
912

70,632✔
913
    set_logger(options.logger);
143,748✔
914
    if (m_replication) {
143,748✔
915
        m_replication->set_logger(m_logger.get());
118,908✔
916
    }
118,908✔
917
    if (m_logger)
143,748✔
918
        m_logger->log(util::Logger::Level::detail, "Open file: %1", path);
129,243✔
919
    SlabAlloc& alloc = m_alloc;
143,748✔
920
    if (options.is_immutable) {
143,748✔
921
        SlabAlloc::Config cfg;
180✔
922
        cfg.read_only = true;
180✔
923
        cfg.no_create = true;
180✔
924
        cfg.encryption_key = options.encryption_key;
180✔
925
        auto top_ref = alloc.attach_file(path, cfg);
180✔
926
        SlabAlloc::DetachGuard dg(alloc);
180✔
927
        Group::read_only_version_check(alloc, top_ref, path);
180✔
928
        m_fake_read_lock_if_immutable = ReadLockInfo::make_fake(top_ref, m_alloc.get_baseline());
180✔
929
        dg.release();
180✔
930
        return;
180✔
931
    }
180✔
932
    std::string lockfile_path = get_core_file(path, CoreFileType::Lock);
143,568✔
933
    std::string coordination_dir = get_core_file(path, CoreFileType::Management);
143,568✔
934
    std::string lockfile_prefix = coordination_dir + "/access_control";
143,568✔
935
    m_alloc.set_read_only(false);
143,568✔
936

70,542✔
937
    Replication::HistoryType openers_hist_type = Replication::hist_None;
143,568✔
938
    int openers_hist_schema_version = 0;
143,568✔
939
    if (Replication* repl = get_replication()) {
143,568✔
940
        openers_hist_type = repl->get_history_type();
118,908✔
941
        openers_hist_schema_version = repl->get_history_schema_version();
118,908✔
942
    }
118,908✔
943

70,542✔
944
    int current_file_format_version;
143,568✔
945
    int target_file_format_version;
143,568✔
946
    int stored_hist_schema_version = -1; // Signals undetermined
143,568✔
947

70,542✔
948
    int retries_left = 10; // number of times to retry before throwing exceptions
143,568✔
949
    // in case there is something wrong with the .lock file... the retries allows
70,542✔
950
    // us to pick a new lockfile initializer in case the first one crashes without
70,542✔
951
    // completing the initialization
70,542✔
952
    std::default_random_engine random_gen;
143,568✔
953
    for (;;) {
237,150✔
954

121,827✔
955
        // if we're retrying, we first wait a random time
121,827✔
956
        if (retries_left < 10) {
237,150✔
957
            if (retries_left == 9) { // we seed it from a true random source if possible
240✔
958
                std::random_device r;
24✔
959
                random_gen.seed(r());
24✔
960
            }
24✔
961
            int max_delay = (10 - retries_left) * 10;
240✔
962
            int msecs = random_gen() % max_delay;
240✔
963
            millisleep(msecs);
240✔
964
        }
240✔
965

121,827✔
966
        m_file.open(lockfile_path, File::access_ReadWrite, File::create_Auto, 0); // Throws
237,150✔
967
        File::CloseGuard fcg(m_file);
237,150✔
968
        m_file.set_fifo_path(coordination_dir, "lock.fifo");
237,150✔
969

121,827✔
970
        if (m_file.try_rw_lock_exclusive()) { // Throws
237,150✔
971
            File::UnlockGuard ulg(m_file);
117,780✔
972

57,792✔
973
            // We're alone in the world, and it is Ok to initialize the
57,792✔
974
            // file. Start by truncating the file to zero to ensure that
57,792✔
975
            // the following resize will generate a file filled with zeroes.
57,792✔
976
            //
57,792✔
977
            // This will in particular set m_init_complete to 0.
57,792✔
978
            m_file.resize(0);
117,780✔
979
            m_file.prealloc(sizeof(SharedInfo));
117,780✔
980

57,792✔
981
            // We can crash anytime during this process. A crash prior to
57,792✔
982
            // the first resize could allow another thread which could not
57,792✔
983
            // get the exclusive lock because we hold it, and hence were
57,792✔
984
            // waiting for the shared lock instead, to observe and use an
57,792✔
985
            // old lock file.
57,792✔
986
            m_file_map.map(m_file, File::access_ReadWrite, sizeof(SharedInfo), File::map_NoSync); // Throws
117,780✔
987
            File::UnmapGuard fug(m_file_map);
117,780✔
988
            SharedInfo* info = m_file_map.get_addr();
117,780✔
989

57,792✔
990
            new (info) SharedInfo{options.durability, openers_hist_type, openers_hist_schema_version}; // Throws
117,780✔
991

57,792✔
992
            // Because init_complete is an std::atomic, it's guaranteed not to be observable by others
57,792✔
993
            // as being 1 before the entire SharedInfo header has been written.
57,792✔
994
            info->init_complete = 1;
117,780✔
995
        }
117,780✔
996

121,827✔
997
// We hold the shared lock from here until we close the file!
121,827✔
998
#if REALM_PLATFORM_APPLE
115,323✔
999
        // macOS has a bug which can cause a hang waiting to obtain a lock, even
1000
        // if the lock is already open in shared mode, so we work around it by
1001
        // busy waiting. This should occur only briefly during session initialization.
1002
        while (!m_file.try_rw_lock_shared()) {
116,382✔
1003
            sched_yield();
1,059✔
1004
        }
1,059✔
1005
#else
1006
        m_file.rw_lock_shared(); // Throws
121,827✔
1007
#endif
121,827✔
1008
        File::UnlockGuard ulg(m_file);
237,150✔
1009

121,827✔
1010
        // The coordination/management dir is created as a side effect of the lock
121,827✔
1011
        // operation above if needed for lock emulation. But it may also be needed
121,827✔
1012
        // for other purposes, so make sure it exists.
121,827✔
1013
        // in worst case there'll be a race on creating this directory.
121,827✔
1014
        // This should be safe but a waste of resources.
121,827✔
1015
        // Unfortunately it cannot be created at an earlier point, because
121,827✔
1016
        // it may then be deleted during the above lock_shared() operation.
121,827✔
1017
        try_make_dir(coordination_dir);
237,150✔
1018

121,827✔
1019
        // If the file is not completely initialized at this point in time, the
121,827✔
1020
        // preceeding initialization attempt must have failed. We know that an
121,827✔
1021
        // initialization process was in progress, because this thread (or
121,827✔
1022
        // process) failed to get an exclusive lock on the file. Because this
121,827✔
1023
        // thread (or process) currently has a shared lock on the file, we also
121,827✔
1024
        // know that the initialization process can no longer be in progress, so
121,827✔
1025
        // the initialization must either have completed or failed at this time.
121,827✔
1026

121,827✔
1027
        // The file is taken to be completely initialized if it is large enough
121,827✔
1028
        // to contain the `init_complete` field, and `init_complete` is true. If
121,827✔
1029
        // the file was not completely initialized, this thread must give up its
121,827✔
1030
        // shared lock, and retry to become the initializer. Eventually, one of
121,827✔
1031
        // two things must happen; either this thread, or another thread
121,827✔
1032
        // succeeds in completing the initialization, or this thread becomes the
121,827✔
1033
        // initializer, and fails the initialization. In either case, the retry
121,827✔
1034
        // loop will eventually terminate.
121,827✔
1035

121,827✔
1036
        // An empty file is (and was) never a successfully initialized file.
121,827✔
1037
        size_t info_size = sizeof(SharedInfo);
237,150✔
1038
        {
237,150✔
1039
            auto file_size = m_file.get_size();
237,150✔
1040
            if (util::int_less_than(file_size, info_size)) {
237,150✔
1041
                if (file_size == 0)
93,087✔
1042
                    continue; // Retry
64,959✔
1043
                info_size = size_t(file_size);
28,128✔
1044
            }
28,128✔
1045
        }
237,150✔
1046

121,827✔
1047
        // Map the initial section of the SharedInfo file that corresponds to
121,827✔
1048
        // the SharedInfo struct, or less if the file is smaller. We know that
121,827✔
1049
        // we have at least one byte, and that is enough to read the
121,827✔
1050
        // `init_complete` flag.
121,827✔
1051
        m_file_map.map(m_file, File::access_ReadWrite, info_size, File::map_NoSync);
211,962✔
1052
        File::UnmapGuard fug_1(m_file_map);
172,191✔
1053
        SharedInfo* info = m_file_map.get_addr();
172,191✔
1054

82,056✔
1055
#ifndef _WIN32
172,191✔
1056
#pragma GCC diagnostic push
172,191✔
1057
#pragma GCC diagnostic ignored "-Winvalid-offsetof"
172,191✔
1058
#endif
172,191✔
1059
        static_assert(offsetof(SharedInfo, init_complete) + sizeof SharedInfo::init_complete <= 1,
172,191✔
1060
                      "Unexpected position or size of SharedInfo::init_complete");
172,191✔
1061
#ifndef _WIN32
172,191✔
1062
#pragma GCC diagnostic pop
172,191✔
1063
#endif
172,191✔
1064
        if (info->init_complete == 0)
172,191✔
1065
            continue;
28,062✔
1066
        REALM_ASSERT(info->init_complete == 1);
144,129✔
1067

70,794✔
1068
        // At this time, we know that the file was completely initialized, but
70,794✔
1069
        // we still need to verify that is was initialized with the memory
70,794✔
1070
        // layout expected by this session participant. We could find that it is
70,794✔
1071
        // initializaed with a different memory layout if other concurrent
70,794✔
1072
        // session participants use different versions of the core library.
70,794✔
1073
        if (info_size < sizeof(SharedInfo)) {
144,129✔
1074
            if (retries_left) {
66✔
1075
                --retries_left;
60✔
1076
                continue;
60✔
1077
            }
60✔
1078
            throw IncompatibleLockFile(path, format("Architecture mismatch: SharedInfo size is %1 but should be %2.",
6✔
1079
                                                    info_size, sizeof(SharedInfo)));
6✔
1080
        }
6✔
1081
        if (info->shared_info_version != g_shared_info_version) {
144,063✔
1082
            if (retries_left) {
66✔
1083
                --retries_left;
60✔
1084
                continue;
60✔
1085
            }
60✔
1086
            throw IncompatibleLockFile(path, format("Version mismatch: SharedInfo version is %1 but should be %2.",
6✔
1087
                                                    info->shared_info_version, g_shared_info_version));
6✔
1088
        }
6✔
1089
        // Validate compatible sizes of mutex and condvar types. Sizes of all
70,728✔
1090
        // other fields are architecture independent, so if condvar and mutex
70,728✔
1091
        // sizes match, the entire struct matches. The offsets of
70,728✔
1092
        // `size_of_mutex` and `size_of_condvar` are known to be as expected due
70,728✔
1093
        // to the preceeding check in `shared_info_version`.
70,728✔
1094
        if (info->size_of_mutex != sizeof info->shared_controlmutex) {
143,997✔
1095
            if (retries_left) {
66✔
1096
                --retries_left;
60✔
1097
                continue;
60✔
1098
            }
60✔
1099
            throw IncompatibleLockFile(path, format("Architecture mismatch: Mutex size is %1 but should be %2.",
6✔
1100
                                                    info->size_of_mutex, sizeof(info->shared_controlmutex)));
6✔
1101
        }
6✔
1102

70,695✔
1103
        if (info->size_of_condvar != sizeof info->room_to_write) {
143,931✔
1104
            if (retries_left) {
66✔
1105
                --retries_left;
60✔
1106
                continue;
60✔
1107
            }
60✔
1108
            throw IncompatibleLockFile(
6✔
1109
                path, format("Architecture mismatch: Condition variable size is %1 but should be %2.",
6✔
1110
                             info->size_of_condvar, sizeof(info->room_to_write)));
6✔
1111
        }
6✔
1112
        m_writemutex.set_shared_part(info->shared_writemutex, lockfile_prefix, "write");
143,865✔
1113
        m_controlmutex.set_shared_part(info->shared_controlmutex, lockfile_prefix, "control");
143,865✔
1114
        m_versionlist_mutex.set_shared_part(info->shared_versionlist_mutex, lockfile_prefix, "versions");
143,865✔
1115

70,662✔
1116
        // even though fields match wrt alignment and size, there may still be incompatibilities
70,662✔
1117
        // between implementations, so lets ask one of the mutexes if it thinks it'll work.
70,662✔
1118
        if (!m_controlmutex.is_valid()) {
143,865✔
1119
            throw IncompatibleLockFile(
×
1120
                path, "Control mutex is invalid. This suggests that incompatible pthread libraries are in use.");
×
1121
        }
×
1122

70,662✔
1123
        // OK! lock file appears valid. We can now continue operations under the protection
70,662✔
1124
        // of the controlmutex. The controlmutex protects the following activities:
70,662✔
1125
        // - attachment of the database file
70,662✔
1126
        // - start of the async daemon
70,662✔
1127
        // - stop of the async daemon
70,662✔
1128
        // - restore of a backup, if desired
70,662✔
1129
        // - backup of the realm file in preparation of file format upgrade
70,662✔
1130
        // - DB beginning/ending a session
70,662✔
1131
        // - Waiting for and signalling database changes
70,662✔
1132
        {
143,865✔
1133
            std::lock_guard<InterprocessMutex> lock(m_controlmutex); // Throws
143,865✔
1134
            auto version_manager = std::make_unique<FileVersionManager>(m_file, m_versionlist_mutex);
143,865✔
1135

70,662✔
1136
            // proceed to initialize versioning and other metadata information related to
70,662✔
1137
            // the database. Also create the database if we're beginning a new session
70,662✔
1138
            bool begin_new_session = (info->num_participants == 0);
143,865✔
1139
            SlabAlloc::Config cfg;
143,865✔
1140
            cfg.session_initiator = begin_new_session;
143,865✔
1141
            cfg.is_shared = true;
143,865✔
1142
            cfg.read_only = false;
143,865✔
1143
            cfg.skip_validate = !begin_new_session;
143,865✔
1144
            cfg.disable_sync = options.durability == Durability::MemOnly || options.durability == Durability::Unsafe;
143,865✔
1145

70,662✔
1146
            // only the session initiator is allowed to create the database, all other
70,662✔
1147
            // must assume that it already exists.
70,662✔
1148
            cfg.no_create = (begin_new_session ? no_create_file : true);
131,475✔
1149

70,662✔
1150
            // if we're opening a MemOnly file that isn't already opened by
70,662✔
1151
            // someone else then it's a file which should have been deleted on
70,662✔
1152
            // close previously, but wasn't (perhaps due to the process crashing)
70,662✔
1153
            cfg.clear_file = (options.durability == Durability::MemOnly && begin_new_session);
143,865✔
1154

70,662✔
1155
            cfg.encryption_key = options.encryption_key;
143,865✔
1156
            ref_type top_ref;
143,865✔
1157
            m_marker_observer = std::make_unique<EncryptionMarkerObserver>(*version_manager);
143,865✔
1158
            try {
143,865✔
1159
                top_ref = alloc.attach_file(path, cfg, m_marker_observer.get()); // Throws
143,865✔
1160
            }
143,865✔
1161
            catch (const SlabAlloc::Retry&) {
70,662✔
1162
                // On a SlabAlloc::Retry file mappings are already unmapped, no
1163
                // need to do more
1164
                continue;
×
1165
            }
×
1166

70,620✔
1167
            // Determine target file format version for session (upgrade
70,620✔
1168
            // required if greater than file format version of attached file).
70,620✔
1169
            current_file_format_version = alloc.get_committed_file_format_version();
143,781✔
1170
            target_file_format_version =
143,781✔
1171
                Group::get_target_file_format_version_for_session(current_file_format_version, openers_hist_type);
143,781✔
1172
            BackupHandler backup(path, options.accepted_versions, options.to_be_deleted);
143,781✔
1173
            if (backup.must_restore_from_backup(current_file_format_version)) {
143,781✔
1174
                // we need to unmap before any file ops that'll change the realm
6✔
1175
                // file:
6✔
1176
                // (only strictly needed for Windows)
6✔
1177
                alloc.detach();
12✔
1178
                backup.restore_from_backup();
12✔
1179
                // finally, retry with the restored file instead of the original
6✔
1180
                // one:
6✔
1181
                continue;
12✔
1182
            }
12✔
1183
            backup.cleanup_backups();
143,769✔
1184

70,614✔
1185
            // From here on, if we fail in any way, we must detach the
70,614✔
1186
            // allocator.
70,614✔
1187
            SlabAlloc::DetachGuard alloc_detach_guard(alloc);
143,769✔
1188
            alloc.note_reader_start(this);
143,769✔
1189
            // must come after the alloc detach guard
70,614✔
1190
            auto handler = [this, &alloc]() noexcept {
143,769✔
1191
                alloc.note_reader_end(this);
143,763✔
1192
            };
143,763✔
1193
            auto reader_end_guard = make_scope_exit(handler);
143,769✔
1194

70,614✔
1195
            // Check validity of top array (to give more meaningful errors
70,614✔
1196
            // early)
70,614✔
1197
            if (top_ref) {
143,769✔
1198
                try {
93,321✔
1199
                    alloc.note_reader_start(this);
93,321✔
1200
                    auto reader_end_guard = make_scope_exit([&]() noexcept {
93,321✔
1201
                        alloc.note_reader_end(this);
93,321✔
1202
                    });
93,321✔
1203
                    Array top{alloc};
93,321✔
1204
                    top.init_from_ref(top_ref);
93,321✔
1205
                    Group::validate_top_array(top, alloc);
93,321✔
1206
                }
93,321✔
1207
                catch (const InvalidDatabase& e) {
46,059✔
1208
                    if (e.get_path().empty()) {
×
1209
                        throw InvalidDatabase(e.what(), path);
×
1210
                    }
×
1211
                    throw;
×
1212
                }
×
1213
            }
93,321✔
1214
            if (options.backup_at_file_format_change) {
143,769✔
1215
                backup.backup_realm_if_needed(current_file_format_version, target_file_format_version);
143,760✔
1216
            }
143,760✔
1217
            using gf = _impl::GroupFriend;
143,769✔
1218
            bool file_format_ok;
143,769✔
1219
            // In shared mode (Realm file opened via a DB instance) this
70,614✔
1220
            // version of the core library is able to open Realms using file format
70,614✔
1221
            // versions listed below. Please see Group::get_file_format_version() for
70,614✔
1222
            // information about the individual file format versions.
70,614✔
1223
            if (current_file_format_version == 0) {
143,769✔
1224
                file_format_ok = (top_ref == 0);
50,448✔
1225
            }
50,448✔
1226
            else {
93,321✔
1227
                file_format_ok = backup.is_accepted_file_format(current_file_format_version);
93,321✔
1228
            }
93,321✔
1229

70,614✔
1230
            if (REALM_UNLIKELY(!file_format_ok)) {
143,769✔
1231
                throw UnsupportedFileFormatVersion(current_file_format_version);
12✔
1232
            }
12✔
1233

70,608✔
1234
            if (begin_new_session) {
143,757✔
1235
                // Determine version (snapshot number) and check history
58,461✔
1236
                // compatibility
58,461✔
1237
                version_type version = 0;
119,232✔
1238
                int stored_hist_type = 0;
119,232✔
1239
                gf::get_version_and_history_info(alloc, top_ref, version, stored_hist_type,
119,232✔
1240
                                                 stored_hist_schema_version);
119,232✔
1241
                bool good_history_type = false;
119,232✔
1242
                switch (openers_hist_type) {
119,232✔
1243
                    case Replication::hist_None:
6,675✔
1244
                        good_history_type = (stored_hist_type == Replication::hist_None);
6,675✔
1245
                        if (!good_history_type)
6,675✔
1246
                            throw IncompatibleHistories(
6✔
1247
                                util::format("Realm file at path '%1' has history type '%2', but is being opened "
6✔
1248
                                             "with replication disabled.",
6✔
1249
                                             path, Replication::history_type_name(stored_hist_type)),
6✔
1250
                                path);
6✔
1251
                        break;
6,669✔
1252
                    case Replication::hist_OutOfRealm:
3,288✔
1253
                        REALM_ASSERT(false); // No longer in use
×
1254
                        break;
×
1255
                    case Replication::hist_InRealm:
84,627✔
1256
                        good_history_type = (stored_hist_type == Replication::hist_InRealm ||
84,627✔
1257
                                             stored_hist_type == Replication::hist_None);
50,922✔
1258
                        if (!good_history_type)
84,627✔
1259
                            throw IncompatibleHistories(
6✔
1260
                                util::format("Realm file at path '%1' has history type '%2', but is being opened in "
6✔
1261
                                             "local history mode.",
6✔
1262
                                             path, Replication::history_type_name(stored_hist_type)),
6✔
1263
                                path);
6✔
1264
                        break;
84,621✔
1265
                    case Replication::hist_SyncClient:
55,020✔
1266
                        good_history_type = ((stored_hist_type == Replication::hist_SyncClient) || (top_ref == 0));
26,232✔
1267
                        if (!good_history_type)
26,232✔
1268
                            throw IncompatibleHistories(
6✔
1269
                                util::format("Realm file at path '%1' has history type '%2', but is being opened in "
6✔
1270
                                             "synchronized history mode.",
6✔
1271
                                             path, Replication::history_type_name(stored_hist_type)),
6✔
1272
                                path);
6✔
1273
                        break;
26,226✔
1274
                    case Replication::hist_SyncServer:
13,854✔
1275
                        good_history_type = ((stored_hist_type == Replication::hist_SyncServer) || (top_ref == 0));
1,698✔
1276
                        if (!good_history_type)
1,698✔
1277
                            throw IncompatibleHistories(
×
1278
                                util::format("Realm file at path '%1' has history type '%2', but is being opened in "
×
1279
                                             "server history mode.",
×
1280
                                             path, Replication::history_type_name(stored_hist_type)),
×
1281
                                path);
×
1282
                        break;
1,698✔
1283
                }
119,214✔
1284

58,452✔
1285
                REALM_ASSERT(stored_hist_schema_version >= 0);
119,214✔
1286
                if (stored_hist_schema_version > openers_hist_schema_version)
119,214✔
1287
                    throw IncompatibleHistories(
×
1288
                        util::format("Unexpected future history schema version %1, current schema %2",
×
1289
                                     stored_hist_schema_version, openers_hist_schema_version),
×
1290
                        path);
×
1291
                bool need_hist_schema_upgrade =
119,214✔
1292
                    (stored_hist_schema_version < openers_hist_schema_version && top_ref != 0);
119,214✔
1293
                if (need_hist_schema_upgrade) {
119,214✔
1294
                    Replication* repl = get_replication();
15✔
1295
                    if (!repl->is_upgradable_history_schema(stored_hist_schema_version))
15✔
1296
                        throw IncompatibleHistories(util::format("Nonupgradable history schema %1, current schema %2",
×
1297
                                                                 stored_hist_schema_version,
×
1298
                                                                 openers_hist_schema_version),
×
1299
                                                    path);
×
1300
                }
119,214✔
1301

58,452✔
1302
                bool need_file_format_upgrade =
119,214✔
1303
                    current_file_format_version < target_file_format_version && top_ref != 0;
119,214✔
1304
                if (!options.allow_file_format_upgrade && (need_hist_schema_upgrade || need_file_format_upgrade)) {
119,214✔
1305
                    throw FileFormatUpgradeRequired(m_db_path);
6✔
1306
                }
6✔
1307

58,449✔
1308
                alloc.convert_from_streaming_form(top_ref);
119,208✔
1309
                try {
119,208✔
1310
                    bool file_changed_size = alloc.align_filesize_for_mmap(top_ref, cfg);
119,208✔
1311
                    if (file_changed_size) {
119,208✔
1312
                        // we need to re-establish proper mappings after file size change.
129✔
1313
                        // we do this simply by aborting and starting all over:
129✔
1314
                        continue;
315✔
1315
                    }
315✔
1316
                }
×
1317
                // something went wrong. Retry.
1318
                catch (SlabAlloc::Retry&) {
×
1319
                    continue;
×
1320
                }
×
1321
                if (options.encryption_key) {
118,893✔
1322
#ifdef _WIN32
1323
                    uint64_t pid = GetCurrentProcessId();
1324
#else
1325
                    static_assert(sizeof(pid_t) <= sizeof(uint64_t), "process identifiers too large");
201✔
1326
                    uint64_t pid = getpid();
201✔
1327
#endif
201✔
1328
                    info->session_initiator_pid = pid;
201✔
1329
                }
201✔
1330

58,320✔
1331
                info->file_format_version = uint_fast8_t(target_file_format_version);
118,893✔
1332

58,320✔
1333
                // Initially there is a single version in the file
58,320✔
1334
                info->number_of_versions = 1;
118,893✔
1335

58,320✔
1336
                info->latest_version_number = version;
118,893✔
1337
                alloc.init_mapping_management(version);
118,893✔
1338

58,320✔
1339
                size_t file_size = 24;
118,893✔
1340
                if (top_ref) {
118,893✔
1341
                    Array top(alloc);
69,936✔
1342
                    top.init_from_ref(top_ref);
69,936✔
1343
                    file_size = Group::get_logical_file_size(top);
69,936✔
1344
                }
69,936✔
1345
                version_manager->init_versioning(top_ref, file_size, version);
118,893✔
1346
            }
118,893✔
1347
            else { // Not the session initiator
24,525✔
1348
                // Durability setting must be consistent across a session. An
12,147✔
1349
                // inconsistency is a logic error, as the user is required to
12,147✔
1350
                // make sure that all possible concurrent session participants
12,147✔
1351
                // use the same durability setting for the same Realm file.
12,147✔
1352
                if (Durability(info->durability) != options.durability)
24,525✔
1353
                    throw RuntimeError(ErrorCodes::IncompatibleSession, "Durability not consistent");
6✔
1354

12,144✔
1355
                // History type must be consistent across a session. An
12,144✔
1356
                // inconsistency is a logic error, as the user is required to
12,144✔
1357
                // make sure that all possible concurrent session participants
12,144✔
1358
                // use the same history type for the same Realm file.
12,144✔
1359
                if (info->history_type != openers_hist_type)
24,519✔
1360
                    throw RuntimeError(ErrorCodes::IncompatibleSession, "History type not consistent");
6✔
1361

12,141✔
1362
                // History schema version must be consistent across a
12,141✔
1363
                // session. An inconsistency is a logic error, as the user is
12,141✔
1364
                // required to make sure that all possible concurrent session
12,141✔
1365
                // participants use the same history schema version for the same
12,141✔
1366
                // Realm file.
12,141✔
1367
                if (info->history_schema_version != openers_hist_schema_version)
24,513✔
1368
                    throw RuntimeError(ErrorCodes::IncompatibleSession, "History schema version not consistent");
×
1369

12,141✔
1370
                // We need per session agreement among all participants on the
12,141✔
1371
                // target Realm file format. From a technical perspective, the
12,141✔
1372
                // best way to ensure that, would be to require a bumping of the
12,141✔
1373
                // SharedInfo file format version on any change that could lead
12,141✔
1374
                // to a different result from
12,141✔
1375
                // get_target_file_format_for_session() given the same current
12,141✔
1376
                // Realm file format version and the same history type, as that
12,141✔
1377
                // would prevent the outcome of the Realm opening process from
12,141✔
1378
                // depending on race conditions. However, for practical reasons,
12,141✔
1379
                // we shall instead simply check that there is agreement, and
12,141✔
1380
                // throw the same kind of exception, as would have been thrown
12,141✔
1381
                // with a bumped SharedInfo file format version, if there isn't.
12,141✔
1382
                if (info->file_format_version != target_file_format_version) {
24,513✔
1383
                    throw IncompatibleLockFile(path,
×
1384
                                               format("Version mismatch: File format version is %1 but should be %2.",
×
1385
                                                      info->file_format_version, target_file_format_version));
×
1386
                }
×
1387

12,141✔
1388
                // Even though this session participant is not the session initiator,
12,141✔
1389
                // it may be the one that has to perform the history schema upgrade.
12,141✔
1390
                // See upgrade_file_format(). However we cannot get the actual value
12,141✔
1391
                // at this point as the allocator is not synchronized with the file.
12,141✔
1392
                // The value will be read in a ReadTransaction later.
12,141✔
1393

12,141✔
1394
                // We need to setup the allocators version information, as it is needed
12,141✔
1395
                // to correctly age and later reclaim memory mappings.
12,141✔
1396
                version_type version = info->latest_version_number;
24,513✔
1397
                alloc.init_mapping_management(version);
24,513✔
1398
            }
24,513✔
1399

70,608✔
1400
            m_new_commit_available.set_shared_part(info->new_commit_available, lockfile_prefix, "new_commit",
143,553✔
1401
                                                   options.temp_dir);
143,406✔
1402
            m_pick_next_writer.set_shared_part(info->pick_next_writer, lockfile_prefix, "pick_writer",
143,406✔
1403
                                               options.temp_dir);
143,406✔
1404

70,461✔
1405
            // make our presence noted:
70,461✔
1406
            ++info->num_participants;
143,406✔
1407
            m_info = info;
143,406✔
1408

70,461✔
1409
            // Keep the mappings and file open:
70,461✔
1410
            m_version_manager = std::move(version_manager);
143,406✔
1411
            alloc_detach_guard.release();
143,406✔
1412
            fug_1.release(); // Do not unmap
143,406✔
1413
            fcg.release();   // Do not close
143,406✔
1414
        }
143,406✔
1415
        ulg.release(); // Do not release shared lock
143,406✔
1416
        break;
143,406✔
1417
    }
143,757✔
1418

70,542✔
1419
    // Upgrade file format and/or history schema
70,542✔
1420
    try {
143,490✔
1421
        if (stored_hist_schema_version == -1) {
143,412✔
1422
            // current_hist_schema_version has not been read. Read it now
12,141✔
1423
            stored_hist_schema_version = start_read()->get_history_schema_version();
24,513✔
1424
        }
24,513✔
1425
        if (current_file_format_version == 0) {
143,412✔
1426
            // If the current file format is still undecided, no upgrade is
24,546✔
1427
            // necessary, but we still need to make the chosen file format
24,546✔
1428
            // visible to the rest of the core library by updating the value
24,546✔
1429
            // that will be subsequently returned by
24,546✔
1430
            // Group::get_file_format_version(). For this to work, all session
24,546✔
1431
            // participants must adopt the chosen target Realm file format when
24,546✔
1432
            // the stored file format version is zero regardless of the version
24,546✔
1433
            // of the core library used.
24,546✔
1434
            m_file_format_version = target_file_format_version;
50,433✔
1435
        }
50,433✔
1436
        else {
92,979✔
1437
            m_file_format_version = current_file_format_version;
92,979✔
1438
            upgrade_file_format(options.allow_file_format_upgrade, target_file_format_version,
92,979✔
1439
                                stored_hist_schema_version, openers_hist_schema_version); // Throws
92,979✔
1440
        }
92,979✔
1441
    }
143,412✔
1442
    catch (...) {
70,467✔
1443
        close();
6✔
1444
        throw;
6✔
1445
    }
6✔
1446
#if REALM_METRICS
143,397✔
1447
    if (options.enable_metrics) {
143,397✔
1448
        m_metrics = std::make_shared<Metrics>(options.metrics_buffer_size);
96✔
1449
    }
96✔
1450
#endif // REALM_METRICS
143,397✔
1451
    m_alloc.set_read_only(true);
143,397✔
1452
}
143,397✔
1453

1454
void DB::open(BinaryData buffer, bool take_ownership)
1455
{
6✔
1456
    auto top_ref = m_alloc.attach_buffer(buffer.data(), buffer.size());
6✔
1457
    m_fake_read_lock_if_immutable = ReadLockInfo::make_fake(top_ref, buffer.size());
6✔
1458
    if (take_ownership)
6✔
1459
        m_alloc.own_buffer();
×
1460
}
6✔
1461

1462
void DB::open(Replication& repl, const std::string& file, const DBOptions& options)
1463
{
118,908✔
1464
    // Exception safety: Since open() is called from constructors, if it throws,
58,212✔
1465
    // it must leave the file closed.
58,212✔
1466

58,212✔
1467
    REALM_ASSERT(!is_attached());
118,908✔
1468

58,212✔
1469
    repl.initialize(*this); // Throws
118,908✔
1470

58,212✔
1471
    set_replication(&repl);
118,908✔
1472

58,212✔
1473
    bool no_create = false;
118,908✔
1474
    open(file, no_create, options); // Throws
118,908✔
1475
}
118,908✔
1476
class DBLogger : public Logger {
1477
public:
1478
    DBLogger(const std::shared_ptr<Logger>& base_logger, unsigned hash) noexcept
1479
        : Logger(base_logger)
1480
        , m_hash(hash)
1481
    {
154,491✔
1482
    }
154,491✔
1483

1484
protected:
1485
    void do_log(Level level, const std::string& message) final
1486
    {
1,424,862✔
1487
        std::ostringstream ostr;
1,424,862✔
1488
        auto id = std::this_thread::get_id();
1,424,862✔
1489
        ostr << "DB: " << m_hash << " Thread " << id << ": ";
1,424,862✔
1490
        Logger::do_log(*m_base_logger_ptr, level, ostr.str() + message);
1,424,862✔
1491
    }
1,424,862✔
1492

1493
private:
1494
    unsigned m_hash;
1495
};
1496

1497
void DB::set_logger(const std::shared_ptr<util::Logger>& logger) noexcept
1498
{
169,008✔
1499
    if (logger)
169,008✔
1500
        m_logger = std::make_shared<DBLogger>(logger, m_log_id);
154,491✔
1501
}
169,008✔
1502

1503
void DB::open(Replication& repl, const DBOptions options)
1504
{
25,260✔
1505
    REALM_ASSERT(!is_attached());
25,260✔
1506
    repl.initialize(*this); // Throws
25,260✔
1507
    set_replication(&repl);
25,260✔
1508

12,630✔
1509
    m_alloc.init_in_memory_buffer();
25,260✔
1510

12,630✔
1511
    set_logger(options.logger);
25,260✔
1512
    m_replication->set_logger(m_logger.get());
25,260✔
1513
    if (m_logger)
25,260✔
1514
        m_logger->log(util::Logger::Level::detail, "Open memory-only realm");
25,248✔
1515

12,630✔
1516
    auto hist_type = repl.get_history_type();
25,260✔
1517
    m_in_memory_info =
25,260✔
1518
        std::make_unique<SharedInfo>(DBOptions::Durability::MemOnly, hist_type, repl.get_history_schema_version());
25,260✔
1519
    SharedInfo* info = m_in_memory_info.get();
25,260✔
1520
    m_writemutex.set_shared_part(info->shared_writemutex, "", "write");
25,260✔
1521
    m_controlmutex.set_shared_part(info->shared_controlmutex, "", "control");
25,260✔
1522
    m_new_commit_available.set_shared_part(info->new_commit_available, "", "new_commit", options.temp_dir);
25,260✔
1523
    m_pick_next_writer.set_shared_part(info->pick_next_writer, "", "pick_writer", options.temp_dir);
25,260✔
1524
    m_versionlist_mutex.set_shared_part(info->shared_versionlist_mutex, "", "versions");
25,260✔
1525

12,630✔
1526
    auto target_file_format_version = uint_fast8_t(Group::get_target_file_format_version_for_session(0, hist_type));
25,260✔
1527
    info->file_format_version = target_file_format_version;
25,260✔
1528
    info->number_of_versions = 1;
25,260✔
1529
    info->latest_version_number = 1;
25,260✔
1530
    info->init_versioning(0, m_alloc.get_baseline(), 1);
25,260✔
1531
    ++info->num_participants;
25,260✔
1532

12,630✔
1533
    m_version_manager = std::make_unique<InMemoryVersionManager>(info, m_versionlist_mutex);
25,260✔
1534

12,630✔
1535
    m_file_format_version = target_file_format_version;
25,260✔
1536

12,630✔
1537
#if REALM_METRICS
25,260✔
1538
    if (options.enable_metrics) {
25,260✔
1539
        m_metrics = std::make_shared<Metrics>(options.metrics_buffer_size);
×
1540
    }
×
1541
#endif // REALM_METRICS
25,260✔
1542
    m_info = info;
25,260✔
1543
    m_alloc.set_read_only(true);
25,260✔
1544
}
25,260✔
1545

1546
void DB::create_new_history(Replication& repl)
1547
{
36✔
1548
    Replication* old_repl = get_replication();
36✔
1549
    try {
36✔
1550
        repl.initialize(*this);
36✔
1551
        set_replication(&repl);
36✔
1552

18✔
1553
        auto tr = start_write();
36✔
1554
        tr->clear_history();
36✔
1555
        tr->replicate(tr.get(), repl);
36✔
1556
        tr->commit();
36✔
1557
    }
36✔
1558
    catch (...) {
18✔
1559
        set_replication(old_repl);
×
1560
        throw;
×
1561
    }
×
1562
}
36✔
1563

1564
void DB::create_new_history(std::unique_ptr<Replication> repl)
1565
{
36✔
1566
    create_new_history(*repl);
36✔
1567
    m_history = std::move(repl);
36✔
1568
}
36✔
1569

1570
// WARNING / FIXME: compact() should NOT be exposed publicly on Windows because it's not crash safe! It may
1571
// corrupt your database if something fails.
1572
// Tracked by https://github.com/realm/realm-core/issues/4111
1573

1574
// A note about lock ordering.
1575
// The local mutex, m_mutex, guards transaction start/stop and map/unmap of the lock file.
1576
// Except for compact(), open() and close(), it should only be held briefly.
1577
// The controlmutex guards operations which change the file size, session initialization
1578
// and session exit.
1579
// The writemutex guards the integrity of the (write) transaction data.
1580
// The controlmutex and writemutex resides in the .lock file and thus requires
1581
// the mapping of the .lock file to work. A straightforward approach would be to lock
1582
// the m_mutex whenever the other mutexes are taken or released...but that would be too
1583
// bad for performance of transaction start/stop.
1584
//
1585
// The locks are to be taken in this order: writemutex->controlmutex->m_mutex
1586
//
1587
// The .lock file is mapped during DB::create() and unmapped by a call to DB::close().
1588
// Once unmapped, it is never mapped again. Hence any observer with a valid DBRef may
1589
// only see the transition from mapped->unmapped, never the opposite.
1590
//
1591
// Trying to create a transaction if the .lock file is unmapped will result in an assert.
1592
// Unmapping (during close()) while transactions are live, is not considered an error. There
1593
// is a potential race between unmapping during close() and any operation carried out by a live
1594
// transaction. The user must ensure that this race never happens if she uses DB::close().
1595
bool DB::compact(bool bump_version_number, util::Optional<const char*> output_encryption_key)
1596
    NO_THREAD_SAFETY_ANALYSIS // this would work except for a known limitation: "No alias analysis" where clang cannot
1597
                              // tell that tr->db->m_mutex is the same thing as m_mutex
1598
{
150✔
1599
    REALM_ASSERT(!m_fake_read_lock_if_immutable);
150✔
1600
    std::string tmp_path = m_db_path + ".tmp_compaction_space";
150✔
1601

75✔
1602
    // To enter compact, the DB object must already have been attached to a file,
75✔
1603
    // since this happens in DB::create().
75✔
1604

75✔
1605
    // Verify that the lock file is still attached. There is no attempt to guard against
75✔
1606
    // a race between close() and compact().
75✔
1607
    if (is_attached() == false) {
150✔
1608
        throw Exception(ErrorCodes::IllegalOperation, m_db_path + ": compact must be done on an open/attached DB");
×
1609
    }
×
1610
    auto info = m_info;
150✔
1611
    Durability dura = Durability(info->durability);
150✔
1612
    const char* write_key = bool(output_encryption_key) ? *output_encryption_key : get_encryption_key();
144✔
1613
    {
150✔
1614
        std::unique_lock<InterprocessMutex> lock(m_controlmutex); // Throws
150✔
1615
        auto t1 = std::chrono::steady_clock::now();
150✔
1616

75✔
1617
        // We must be the ONLY DB object attached if we're to do compaction
75✔
1618
        if (info->num_participants > 1)
150✔
1619
            return false;
×
1620

75✔
1621
        // Holding the controlmutex prevents any other DB from attaching to the file.
75✔
1622

75✔
1623
        // Using start_read here ensures that we have access to the latest entry
75✔
1624
        // in the VersionList. We need to have access to that later to update top_ref and file_size.
75✔
1625
        // This is also needed to attach the group (get the proper top pointer, etc)
75✔
1626
        TransactionRef tr = start_read();
150✔
1627
        auto file_size_before = tr->get_logical_file_size();
150✔
1628

75✔
1629
        // local lock blocking any transaction from starting (and stopping)
75✔
1630
        CheckedLockGuard local_lock(m_mutex);
150✔
1631

75✔
1632
        // We should be the only transaction active - otherwise back out
75✔
1633
        if (m_transaction_count != 1)
150✔
1634
            return false;
6✔
1635

72✔
1636
        // group::write() will throw if the file already exists.
72✔
1637
        // To prevent this, we have to remove the file (should it exist)
72✔
1638
        // before calling group::write().
72✔
1639
        File::try_remove(tmp_path);
144✔
1640

72✔
1641
        // Compact by writing a new file holding only live data, then renaming the new file
72✔
1642
        // so it becomes the database file, replacing the old one in the process.
72✔
1643
        try {
144✔
1644
            File file;
144✔
1645
            file.open(tmp_path, File::access_ReadWrite, File::create_Must, 0);
144✔
1646
            int incr = bump_version_number ? 1 : 0;
138✔
1647
            Group::DefaultTableWriter writer;
144✔
1648
            tr->write(file, write_key, info->latest_version_number + incr, writer); // Throws
144✔
1649
            // Data needs to be flushed to the disk before renaming.
72✔
1650
            bool disable_sync = get_disable_sync_to_disk();
144✔
1651
            if (!disable_sync && dura != Durability::Unsafe)
144!
1652
                file.sync(); // Throws
×
1653
        }
144✔
1654
        catch (...) {
72✔
1655
            // If writing the compact version failed in any way, delete the partially written file to clean up disk
1656
            // space. This is so that we don't fail with 100% disk space used when compacting on a mostly full disk.
1657
            if (File::exists(tmp_path)) {
×
1658
                File::remove(tmp_path);
×
1659
            }
×
1660
            throw;
×
1661
        }
×
1662
        // if we've written a file with a bumped version number, we need to update the lock file to match.
72✔
1663
        if (bump_version_number) {
144✔
1664
            ++info->latest_version_number;
12✔
1665
        }
12✔
1666
        // We need to release any shared mapping *before* releasing the control mutex.
72✔
1667
        // When someone attaches to the new database file, they *must* *not* see and
72✔
1668
        // reuse any existing memory mapping of the stale file.
72✔
1669
        tr->close_read_with_lock();
144✔
1670
        m_alloc.detach();
144✔
1671

72✔
1672
        util::File::move(tmp_path, m_db_path);
144✔
1673

72✔
1674
        SlabAlloc::Config cfg;
144✔
1675
        cfg.session_initiator = true;
144✔
1676
        cfg.is_shared = true;
144✔
1677
        cfg.read_only = false;
144✔
1678
        cfg.skip_validate = false;
144✔
1679
        cfg.no_create = true;
144✔
1680
        cfg.clear_file = false;
144✔
1681
        cfg.encryption_key = write_key;
144✔
1682
        ref_type top_ref;
144✔
1683
        top_ref = m_alloc.attach_file(m_db_path, cfg, m_marker_observer.get());
144✔
1684
        m_alloc.convert_from_streaming_form(top_ref);
144✔
1685
        m_alloc.init_mapping_management(info->latest_version_number);
144✔
1686
        info->number_of_versions = 1;
144✔
1687
        size_t logical_file_size = sizeof(SlabAlloc::Header);
144✔
1688
        if (top_ref) {
144✔
1689
            Array top(m_alloc);
138✔
1690
            top.init_from_ref(top_ref);
138✔
1691
            logical_file_size = Group::get_logical_file_size(top);
138✔
1692
        }
138✔
1693
        m_version_manager->init_versioning(top_ref, logical_file_size, info->latest_version_number);
144✔
1694
        if (m_logger) {
144✔
1695
            auto t2 = std::chrono::steady_clock::now();
60✔
1696
            m_logger->log(util::Logger::Level::info, "DB compacted from: %1 to %2 in %3 us", file_size_before,
60✔
1697
                          logical_file_size, std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count());
60✔
1698
        }
60✔
1699
    }
144✔
1700
    return true;
144✔
1701
}
144✔
1702

1703
void DB::write_copy(StringData path, const char* output_encryption_key)
1704
{
90✔
1705
    auto tr = start_read();
90✔
1706
    if (auto hist = tr->get_history()) {
90✔
1707
        if (!hist->no_pending_local_changes(tr->get_version())) {
90✔
1708
            throw Exception(ErrorCodes::IllegalOperation,
6✔
1709
                            "All client changes must be integrated in server before writing copy");
6✔
1710
        }
6✔
1711
    }
84✔
1712

42✔
1713
    class NoClientFileIdWriter : public Group::DefaultTableWriter {
84✔
1714
    public:
84✔
1715
        NoClientFileIdWriter()
84✔
1716
            : Group::DefaultTableWriter(true)
84✔
1717
        {
84✔
1718
        }
84✔
1719
        HistoryInfo write_history(_impl::OutputStream& out) override
84✔
1720
        {
81✔
1721
            auto hist = Group::DefaultTableWriter::write_history(out);
78✔
1722
            hist.sync_file_id = 0;
78✔
1723
            return hist;
78✔
1724
        }
78✔
1725
    } writer;
84✔
1726

42✔
1727
    File file;
84✔
1728
    file.open(path, File::access_ReadWrite, File::create_Must, 0);
84✔
1729
    file.resize(0);
84✔
1730

42✔
1731
    auto t1 = std::chrono::steady_clock::now();
84✔
1732
    tr->write(file, output_encryption_key, m_info->latest_version_number, writer);
84✔
1733
    if (m_logger) {
84✔
1734
        auto t2 = std::chrono::steady_clock::now();
60✔
1735
        m_logger->log(util::Logger::Level::info, "DB written to '%1' in %2 us", path,
60✔
1736
                      std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count());
60✔
1737
    }
60✔
1738
}
84✔
1739

1740
uint_fast64_t DB::get_number_of_versions()
1741
{
382,308✔
1742
    if (m_fake_read_lock_if_immutable)
382,308✔
1743
        return 1;
6✔
1744
    return m_info->number_of_versions;
382,302✔
1745
}
382,302✔
1746

1747
size_t DB::get_allocated_size() const
1748
{
6✔
1749
    return m_alloc.get_allocated_size();
6✔
1750
}
6✔
1751

1752
DB::~DB() noexcept
1753
{
169,014✔
1754
    close();
169,014✔
1755
}
169,014✔
1756

1757
void DB::release_all_read_locks() noexcept
1758
{
168,666✔
1759
    REALM_ASSERT(!m_fake_read_lock_if_immutable);
168,666✔
1760
    CheckedLockGuard local_lock(m_mutex); // mx on m_local_locks_held
168,666✔
1761
    for (auto& read_lock : m_local_locks_held) {
83,094✔
1762
        --m_transaction_count;
6✔
1763
        m_version_manager->release_read_lock(read_lock);
6✔
1764
    }
6✔
1765
    m_local_locks_held.clear();
168,666✔
1766
    REALM_ASSERT(m_transaction_count == 0);
168,666✔
1767
}
168,666✔
1768

1769
// Note: close() and close_internal() may be called from the DB::~DB().
1770
// in that case, they will not throw. Throwing can only happen if called
1771
// directly.
1772
void DB::close(bool allow_open_read_transactions)
1773
{
169,287✔
1774
    // make helper thread(s) terminate
83,403✔
1775
    m_commit_helper.reset();
169,287✔
1776

83,403✔
1777
    if (m_fake_read_lock_if_immutable) {
169,287✔
1778
        if (!is_attached())
186✔
1779
            return;
×
1780
        {
186✔
1781
            CheckedLockGuard local_lock(m_mutex);
186✔
1782
            if (!allow_open_read_transactions && m_transaction_count)
186✔
1783
                throw WrongTransactionState("Closing with open read transactions");
×
1784
        }
186✔
1785
        if (m_alloc.is_attached())
186✔
1786
            m_alloc.detach();
186✔
1787
        m_fake_read_lock_if_immutable.reset();
186✔
1788
    }
186✔
1789
    else {
169,101✔
1790
        close_internal(std::unique_lock<InterprocessMutex>(m_controlmutex, std::defer_lock),
169,101✔
1791
                       allow_open_read_transactions);
169,101✔
1792
    }
169,101✔
1793
}
169,287✔
1794

1795
void DB::close_internal(std::unique_lock<InterprocessMutex> lock, bool allow_open_read_transactions)
1796
{
169,101✔
1797
    if (!is_attached())
169,101✔
1798
        return;
423✔
1799

83,097✔
1800
    {
168,678✔
1801
        CheckedLockGuard local_lock(m_mutex);
168,678✔
1802
        if (m_write_transaction_open)
168,678✔
1803
            throw WrongTransactionState("Closing with open write transactions");
6✔
1804
        if (!allow_open_read_transactions && m_transaction_count)
168,672✔
1805
            throw WrongTransactionState("Closing with open read transactions");
6✔
1806
    }
168,666✔
1807
    SharedInfo* info = m_info;
168,666✔
1808
    {
168,666✔
1809
        if (!lock.owns_lock())
168,666✔
1810
            lock.lock();
168,666✔
1811

83,091✔
1812
        if (m_alloc.is_attached())
168,666✔
1813
            m_alloc.detach();
168,666✔
1814

83,091✔
1815
        if (m_is_sync_agent) {
168,666✔
1816
            REALM_ASSERT(info->sync_agent_present);
1,551✔
1817
            info->sync_agent_present = 0; // Set to false
1,551✔
1818
        }
1,551✔
1819
        release_all_read_locks();
168,666✔
1820
        --info->num_participants;
168,666✔
1821
        bool end_of_session = info->num_participants == 0;
168,666✔
1822
        // std::cerr << "closing" << std::endl;
83,091✔
1823
        if (end_of_session) {
168,666✔
1824

70,941✔
1825
            // If the db file is just backing for a transient data structure,
70,941✔
1826
            // we can delete it when done.
70,941✔
1827
            if (Durability(info->durability) == Durability::MemOnly && !m_in_memory_info) {
144,132✔
1828
                try {
20,094✔
1829
                    util::File::remove(m_db_path.c_str());
20,094✔
1830
                }
20,094✔
1831
                catch (...) {
10,059✔
1832
                } // ignored on purpose.
24✔
1833
            }
20,094✔
1834
        }
144,132✔
1835
        lock.unlock();
168,666✔
1836
    }
168,666✔
1837
    {
168,666✔
1838
        CheckedLockGuard local_lock(m_mutex);
168,666✔
1839

83,091✔
1840
        m_new_commit_available.close();
168,666✔
1841
        m_pick_next_writer.close();
168,666✔
1842

83,091✔
1843
        if (m_in_memory_info) {
168,666✔
1844
            m_in_memory_info.reset();
25,260✔
1845
        }
25,260✔
1846
        else {
143,406✔
1847
            // On Windows it is important that we unmap before unlocking, else a SetEndOfFile() call from another
70,461✔
1848
            // thread may interleave which is not permitted on Windows. It is permitted on *nix.
70,461✔
1849
            m_file_map.unmap();
143,406✔
1850
            m_version_manager.reset();
143,406✔
1851
            m_file.rw_unlock();
143,406✔
1852
            // info->~SharedInfo(); // DO NOT Call destructor
70,461✔
1853
            m_file.close();
143,406✔
1854
        }
143,406✔
1855
        m_info = nullptr;
168,666✔
1856
        if (m_logger)
168,666✔
1857
            m_logger->log(util::Logger::Level::detail, "DB closed");
154,272✔
1858
    }
168,666✔
1859
}
168,666✔
1860

1861
bool DB::other_writers_waiting_for_lock() const
1862
{
64,770✔
1863
    SharedInfo* info = m_info;
64,770✔
1864

32,832✔
1865
    uint32_t next_ticket = info->next_ticket.load(std::memory_order_relaxed);
64,770✔
1866
    uint32_t next_served = info->next_served.load(std::memory_order_relaxed);
64,770✔
1867
    // When holding the write lock, next_ticket = next_served + 1, hence, if the diference between 'next_ticket' and
32,832✔
1868
    // 'next_served' is greater than 1, there is at least one thread waiting to acquire the write lock.
32,832✔
1869
    return next_ticket > next_served + 1;
64,770✔
1870
}
64,770✔
1871

1872
class DB::AsyncCommitHelper {
1873
public:
1874
    AsyncCommitHelper(DB* db)
1875
        : m_db(db)
1876
    {
130,377✔
1877
    }
130,377✔
1878
    ~AsyncCommitHelper()
1879
    {
130,377✔
1880
        {
130,377✔
1881
            std::unique_lock lg(m_mutex);
130,377✔
1882
            if (!m_running) {
130,377✔
1883
                return;
79,737✔
1884
            }
79,737✔
1885
            m_running = false;
50,640✔
1886
            m_cv_worker.notify_one();
50,640✔
1887
        }
50,640✔
1888
        m_thread.join();
50,640✔
1889
    }
50,640✔
1890

1891
    void begin_write(util::UniqueFunction<void()> fn)
1892
    {
1,614✔
1893
        std::unique_lock lg(m_mutex);
1,614✔
1894
        start_thread();
1,614✔
1895
        m_pending_writes.emplace_back(std::move(fn));
1,614✔
1896
        m_cv_worker.notify_one();
1,614✔
1897
    }
1,614✔
1898

1899
    void blocking_begin_write()
1900
    {
258,675✔
1901
        std::unique_lock lg(m_mutex);
258,675✔
1902

127,266✔
1903
        // If we support unlocking InterprocessMutex from a different thread
127,266✔
1904
        // than it was locked on, we can sometimes just begin the write on
127,266✔
1905
        // the current thread. This requires that no one is currently waiting
127,266✔
1906
        // for the worker thread to acquire the write lock, as we'll deadlock
127,266✔
1907
        // if we try to async commit while the worker is waiting for the lock.
127,266✔
1908
        bool can_lock_on_caller =
258,675✔
1909
            !InterprocessMutex::is_thread_confined && (!m_owns_write_mutex && m_pending_writes.empty() &&
258,678✔
1910
                                                       m_write_lock_claim_ticket == m_write_lock_claim_fulfilled);
131,352✔
1911

127,266✔
1912
        // If we support cross-thread unlocking and m_running is false,
127,266✔
1913
        // can_lock_on_caller should always be true or we forgot to launch the thread
127,266✔
1914
        REALM_ASSERT(can_lock_on_caller || m_running || InterprocessMutex::is_thread_confined);
258,675✔
1915

127,266✔
1916
        // If possible, just begin the write on the current thread
127,266✔
1917
        if (can_lock_on_caller) {
258,675✔
1918
            m_waiting_for_write_mutex = true;
131,352✔
1919
            lg.unlock();
131,352✔
1920
            m_db->do_begin_write();
131,352✔
1921
            lg.lock();
131,352✔
1922
            m_waiting_for_write_mutex = false;
131,352✔
1923
            m_has_write_mutex = true;
131,352✔
1924
            m_owns_write_mutex = false;
131,352✔
1925
            return;
131,352✔
1926
        }
131,352✔
1927

127,266✔
1928
        // Otherwise we have to ask the worker thread to acquire it and wait
127,266✔
1929
        // for that
127,266✔
1930
        start_thread();
127,323✔
1931
        size_t ticket = ++m_write_lock_claim_ticket;
127,323✔
1932
        m_cv_worker.notify_one();
127,323✔
1933
        m_cv_callers.wait(lg, [this, ticket] {
257,355✔
1934
            return ticket == m_write_lock_claim_fulfilled;
257,355✔
1935
        });
257,355✔
1936
    }
127,323✔
1937

1938
    void end_write()
1939
    {
54✔
1940
        std::unique_lock lg(m_mutex);
54✔
1941
        REALM_ASSERT(m_has_write_mutex);
54✔
1942
        REALM_ASSERT(m_owns_write_mutex || !InterprocessMutex::is_thread_confined);
54✔
1943

27✔
1944
        // If we acquired the write lock on the worker thread, also release it
27✔
1945
        // there even if our mutex supports unlocking cross-thread as it simplifies things.
27✔
1946
        if (m_owns_write_mutex) {
54✔
1947
            m_pending_mx_release = true;
51✔
1948
            m_cv_worker.notify_one();
51✔
1949
        }
51✔
1950
        else {
3✔
1951
            m_db->do_end_write();
3✔
1952
            m_has_write_mutex = false;
3✔
1953
        }
3✔
1954
    }
54✔
1955

1956
    bool blocking_end_write()
1957
    {
304,689✔
1958
        std::unique_lock lg(m_mutex);
304,689✔
1959
        if (!m_has_write_mutex) {
304,689✔
1960
            return false;
45,807✔
1961
        }
45,807✔
1962
        REALM_ASSERT(m_owns_write_mutex || !InterprocessMutex::is_thread_confined);
258,882✔
1963

127,326✔
1964
        // If we acquired the write lock on the worker thread, also release it
127,326✔
1965
        // there even if our mutex supports unlocking cross-thread as it simplifies things.
127,326✔
1966
        if (m_owns_write_mutex) {
258,882✔
1967
            m_pending_mx_release = true;
127,851✔
1968
            m_cv_worker.notify_one();
127,851✔
1969
            m_cv_callers.wait(lg, [this] {
255,702✔
1970
                return !m_pending_mx_release;
255,702✔
1971
            });
255,702✔
1972
        }
127,851✔
1973
        else {
131,031✔
1974
            m_db->do_end_write();
131,031✔
1975
            m_has_write_mutex = false;
131,031✔
1976

1977
            // The worker thread may have ignored a request for the write mutex
1978
            // while we were acquiring it, so we need to wake up the thread
1979
            if (has_pending_write_requests()) {
131,031✔
1980
                lg.unlock();
×
1981
                m_cv_worker.notify_one();
×
1982
            }
×
1983
        }
131,031✔
1984
        return true;
258,882✔
1985
    }
258,882✔
1986

1987

1988
    void sync_to_disk(util::UniqueFunction<void()> fn)
1989
    {
1,356✔
1990
        REALM_ASSERT(fn);
1,356✔
1991
        std::unique_lock lg(m_mutex);
1,356✔
1992
        REALM_ASSERT(!m_pending_sync);
1,356✔
1993
        start_thread();
1,356✔
1994
        m_pending_sync = std::move(fn);
1,356✔
1995
        m_cv_worker.notify_one();
1,356✔
1996
    }
1,356✔
1997

1998
private:
1999
    DB* m_db;
2000
    std::thread m_thread;
2001
    std::mutex m_mutex;
2002
    std::condition_variable m_cv_worker;
2003
    std::condition_variable m_cv_callers;
2004
    std::deque<util::UniqueFunction<void()>> m_pending_writes;
2005
    util::UniqueFunction<void()> m_pending_sync;
2006
    size_t m_write_lock_claim_ticket = 0;
2007
    size_t m_write_lock_claim_fulfilled = 0;
2008
    bool m_pending_mx_release = false;
2009
    bool m_running = false;
2010
    bool m_has_write_mutex = false;
2011
    bool m_owns_write_mutex = false;
2012
    bool m_waiting_for_write_mutex = false;
2013

2014
    void main();
2015

2016
    void start_thread()
2017
    {
130,296✔
2018
        if (m_running) {
130,296✔
2019
            return;
79,656✔
2020
        }
79,656✔
2021
        m_running = true;
50,640✔
2022
        m_thread = std::thread([this]() {
50,640✔
2023
            main();
50,640✔
2024
        });
50,640✔
2025
    }
50,640✔
2026

2027
    bool has_pending_write_requests()
2028
    {
381,741✔
2029
        return m_write_lock_claim_fulfilled < m_write_lock_claim_ticket || !m_pending_writes.empty();
381,741✔
2030
    }
381,741✔
2031
};
2032

2033
void DB::AsyncCommitHelper::main()
2034
{
50,640✔
2035
    std::unique_lock lg(m_mutex);
50,640✔
2036
    while (m_running) {
566,694✔
2037
#if 0 // Enable for testing purposes
2038
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
2039
#endif
2040
        if (m_has_write_mutex) {
516,054✔
2041
            if (auto cb = std::move(m_pending_sync)) {
265,203✔
2042
                // Only one of sync_to_disk(), end_write(), or blocking_end_write()
306✔
2043
                // should be called, so we should never have both a pending sync
306✔
2044
                // and pending release.
306✔
2045
                REALM_ASSERT(!m_pending_mx_release);
1,356✔
2046
                lg.unlock();
1,356✔
2047
                cb();
1,356✔
2048
                cb = nullptr; // Release things captured by the callback before reacquiring the lock
1,356✔
2049
                lg.lock();
1,356✔
2050
                m_pending_mx_release = true;
1,356✔
2051
            }
1,356✔
2052
            if (m_pending_mx_release) {
265,203✔
2053
                REALM_ASSERT(!InterprocessMutex::is_thread_confined || m_owns_write_mutex);
129,258!
2054
                m_db->do_end_write();
129,258✔
2055
                m_pending_mx_release = false;
129,258✔
2056
                m_has_write_mutex = false;
129,258✔
2057
                m_owns_write_mutex = false;
129,258✔
2058

127,659✔
2059
                lg.unlock();
129,258✔
2060
                m_cv_callers.notify_all();
129,258✔
2061
                lg.lock();
129,258✔
2062
                continue;
129,258✔
2063
            }
129,258✔
2064
        }
250,851✔
2065
        else {
250,851✔
2066
            REALM_ASSERT(!m_pending_sync && !m_pending_mx_release);
250,851✔
2067

248,877✔
2068
            // Acquire the write lock if anyone has requested it, but only if
248,877✔
2069
            // another thread is not already waiting for it. If there's another
248,877✔
2070
            // thread requesting and they get it while we're waiting, we'll
248,877✔
2071
            // deadlock if they ask us to perform the sync.
248,877✔
2072
            if (!m_waiting_for_write_mutex && has_pending_write_requests()) {
250,851✔
2073
                lg.unlock();
128,940✔
2074
                m_db->do_begin_write();
128,940✔
2075
                lg.lock();
128,940✔
2076

127,659✔
2077
                REALM_ASSERT(!m_has_write_mutex);
128,940✔
2078
                m_has_write_mutex = true;
128,940✔
2079
                m_owns_write_mutex = true;
128,940✔
2080

127,659✔
2081
                // Synchronous transaction requests get priority over async
127,659✔
2082
                if (m_write_lock_claim_fulfilled < m_write_lock_claim_ticket) {
128,940✔
2083
                    ++m_write_lock_claim_fulfilled;
127,326✔
2084
                    m_cv_callers.notify_all();
127,326✔
2085
                    continue;
127,326✔
2086
                }
127,326✔
2087

393✔
2088
                REALM_ASSERT(!m_pending_writes.empty());
1,614✔
2089
                auto callback = std::move(m_pending_writes.front());
1,614✔
2090
                m_pending_writes.pop_front();
1,614✔
2091
                lg.unlock();
1,614✔
2092
                callback();
1,614✔
2093
                // Release things captured by the callback before reacquiring the lock
393✔
2094
                callback = nullptr;
1,614✔
2095
                lg.lock();
1,614✔
2096
                continue;
1,614✔
2097
            }
1,614✔
2098
        }
250,851✔
2099
        m_cv_worker.wait(lg);
257,856✔
2100
    }
257,856✔
2101
    if (m_has_write_mutex && m_owns_write_mutex) {
50,640!
2102
        m_db->do_end_write();
×
2103
    }
×
2104
}
50,640✔
2105

2106

2107
void DB::async_begin_write(util::UniqueFunction<void()> fn)
2108
{
1,614✔
2109
    REALM_ASSERT(m_commit_helper);
1,614✔
2110
    m_commit_helper->begin_write(std::move(fn));
1,614✔
2111
}
1,614✔
2112

2113
void DB::async_end_write()
2114
{
54✔
2115
    REALM_ASSERT(m_commit_helper);
54✔
2116
    m_commit_helper->end_write();
54✔
2117
}
54✔
2118

2119
void DB::async_sync_to_disk(util::UniqueFunction<void()> fn)
2120
{
1,356✔
2121
    REALM_ASSERT(m_commit_helper);
1,356✔
2122
    m_commit_helper->sync_to_disk(std::move(fn));
1,356✔
2123
}
1,356✔
2124

2125
bool DB::has_changed(TransactionRef& tr)
2126
{
619,998✔
2127
    if (m_fake_read_lock_if_immutable)
619,998✔
2128
        return false; // immutable doesn't change
×
2129
    bool changed = tr->m_read_lock.m_version != get_version_of_latest_snapshot();
619,998✔
2130
    return changed;
619,998✔
2131
}
619,998✔
2132

2133
bool DB::wait_for_change(TransactionRef& tr)
2134
{
×
2135
    REALM_ASSERT(!m_fake_read_lock_if_immutable);
×
2136
    std::lock_guard<InterprocessMutex> lock(m_controlmutex);
×
2137
    while (tr->m_read_lock.m_version == m_info->latest_version_number && m_wait_for_change_enabled) {
×
2138
        m_new_commit_available.wait(m_controlmutex, 0);
×
2139
    }
×
2140
    return tr->m_read_lock.m_version != m_info->latest_version_number;
×
2141
}
×
2142

2143

2144
void DB::wait_for_change_release()
2145
{
×
2146
    if (m_fake_read_lock_if_immutable)
×
2147
        return;
×
2148
    std::lock_guard<InterprocessMutex> lock(m_controlmutex);
×
2149
    m_wait_for_change_enabled = false;
×
2150
    m_new_commit_available.notify_all();
×
2151
}
×
2152

2153

2154
void DB::enable_wait_for_change()
2155
{
×
2156
    REALM_ASSERT(!m_fake_read_lock_if_immutable);
×
2157
    std::lock_guard<InterprocessMutex> lock(m_controlmutex);
×
2158
    m_wait_for_change_enabled = true;
×
2159
}
×
2160

2161
void DB::upgrade_file_format(bool allow_file_format_upgrade, int target_file_format_version,
2162
                             int current_hist_schema_version, int target_hist_schema_version)
2163
{
92,970✔
2164
    // In a multithreaded scenario multiple threads may initially see a need to
45,912✔
2165
    // upgrade (maybe_upgrade == true) even though one onw thread is supposed to
45,912✔
2166
    // perform the upgrade, but that is ok, because the condition is rechecked
45,912✔
2167
    // in a fully reliable way inside a transaction.
45,912✔
2168

45,912✔
2169
    // First a non-threadsafe but fast check
45,912✔
2170
    int current_file_format_version = m_file_format_version;
92,970✔
2171
    REALM_ASSERT(current_file_format_version <= target_file_format_version);
92,970✔
2172
    REALM_ASSERT(current_hist_schema_version <= target_hist_schema_version);
92,970✔
2173
    bool maybe_upgrade_file_format = (current_file_format_version < target_file_format_version);
92,970✔
2174
    bool maybe_upgrade_hist_schema = (current_hist_schema_version < target_hist_schema_version);
92,970✔
2175
    bool maybe_upgrade = maybe_upgrade_file_format || maybe_upgrade_hist_schema;
92,970✔
2176
    if (maybe_upgrade) {
92,970✔
2177

120✔
2178
#ifdef REALM_DEBUG
240✔
2179
// This sleep() only exists in order to increase the quality of the
120✔
2180
// TEST(Upgrade_Database_2_3_Writes_New_File_Format_new) unit test.
120✔
2181
// The unit test creates multiple threads that all call
120✔
2182
// upgrade_file_format() simultaneously. This sleep() then acts like
120✔
2183
// a simple thread barrier that makes sure the threads meet here, to
120✔
2184
// increase the likelyhood of detecting any potential race problems.
120✔
2185
// See the unit test for details.
120✔
2186
//
120✔
2187
// NOTE: This sleep has been disabled because no problems have been found with
120✔
2188
// this code in a long while, and it was dramatically slowing down a unit test
120✔
2189
// in realm-sync.
120✔
2190

120✔
2191
// millisleep(200);
120✔
2192
#endif
240✔
2193

120✔
2194
        // WriteTransaction wt(*this);
120✔
2195
        auto wt = start_write();
240✔
2196
        bool dirty = false;
240✔
2197

120✔
2198
        // We need to upgrade history first. We may need to access it during migration
120✔
2199
        // when processing the !OID columns
120✔
2200
        int current_hist_schema_version_2 = wt->get_history_schema_version();
240✔
2201
        // The history must either still be using its initial schema or have
120✔
2202
        // been upgraded already to the chosen target schema version via a
120✔
2203
        // concurrent DB object.
120✔
2204
        REALM_ASSERT(current_hist_schema_version_2 == current_hist_schema_version ||
240!
2205
                     current_hist_schema_version_2 == target_hist_schema_version);
240✔
2206
        bool need_hist_schema_upgrade = (current_hist_schema_version_2 < target_hist_schema_version);
240✔
2207
        if (need_hist_schema_upgrade) {
240✔
2208
            if (!allow_file_format_upgrade)
12✔
2209
                throw FileFormatUpgradeRequired(this->m_db_path);
×
2210

6✔
2211
            Replication* repl = get_replication();
12✔
2212
            repl->upgrade_history_schema(current_hist_schema_version_2); // Throws
12✔
2213
            wt->set_history_schema_version(target_hist_schema_version);  // Throws
12✔
2214
            dirty = true;
12✔
2215
        }
12✔
2216

120✔
2217
        // File format upgrade
120✔
2218
        int current_file_format_version_2 = m_alloc.get_committed_file_format_version();
240✔
2219
        // The file must either still be using its initial file_format or have
120✔
2220
        // been upgraded already to the chosen target file format via a
120✔
2221
        // concurrent DB object.
120✔
2222
        REALM_ASSERT(current_file_format_version_2 == current_file_format_version ||
240!
2223
                     current_file_format_version_2 == target_file_format_version);
240✔
2224
        bool need_file_format_upgrade = (current_file_format_version_2 < target_file_format_version);
240✔
2225
        if (need_file_format_upgrade) {
240✔
2226
            if (!allow_file_format_upgrade)
234✔
2227
                throw FileFormatUpgradeRequired(this->m_db_path);
×
2228
            wt->upgrade_file_format(target_file_format_version); // Throws
234✔
2229
            // Note: The file format version stored in the Realm file will be
117✔
2230
            // updated to the new file format version as part of the following
117✔
2231
            // commit operation. This happens in GroupWriter::commit().
117✔
2232
            if (m_upgrade_callback)
234✔
2233
                m_upgrade_callback(current_file_format_version_2, target_file_format_version); // Throws
18✔
2234
            dirty = true;
234✔
2235
        }
234✔
2236
        wt->set_file_format_version(target_file_format_version);
240✔
2237
        m_file_format_version = target_file_format_version;
240✔
2238

120✔
2239
        if (dirty)
240✔
2240
            wt->commit(); // Throws
234✔
2241
    }
240✔
2242
}
92,970✔
2243

2244
void DB::release_read_lock(ReadLockInfo& read_lock) noexcept
2245
{
5,720,505✔
2246
    // ignore if opened with immutable file (then we have no lockfile)
3,527,637✔
2247
    if (m_fake_read_lock_if_immutable)
5,720,505✔
2248
        return;
366✔
2249
    CheckedLockGuard lock(m_mutex); // mx on m_local_locks_held
5,720,139✔
2250
    do_release_read_lock(read_lock);
5,720,139✔
2251
}
5,720,139✔
2252

2253
// this is called with m_mutex locked
2254
void DB::do_release_read_lock(ReadLockInfo& read_lock) noexcept
2255
{
5,728,392✔
2256
    REALM_ASSERT(!m_fake_read_lock_if_immutable);
5,728,392✔
2257
    bool found_match = false;
5,728,392✔
2258
    // simple linear search and move-last-over if a match is found.
3,535,692✔
2259
    // common case should have only a modest number of transactions in play..
3,535,692✔
2260
    for (size_t j = 0; j < m_local_locks_held.size(); ++j) {
9,575,163✔
2261
        if (m_local_locks_held[j].m_version == read_lock.m_version) {
9,575,094✔
2262
            m_local_locks_held[j] = m_local_locks_held.back();
5,728,332✔
2263
            m_local_locks_held.pop_back();
5,728,332✔
2264
            found_match = true;
5,728,332✔
2265
            break;
5,728,332✔
2266
        }
5,728,332✔
2267
    }
9,575,094✔
2268
    if (!found_match) {
5,728,392✔
2269
        REALM_ASSERT(!is_attached());
6✔
2270
        // it's OK, someone called close() and all locks where released
3✔
2271
        return;
6✔
2272
    }
6✔
2273
    --m_transaction_count;
5,728,386✔
2274
    m_version_manager->release_read_lock(read_lock);
5,728,386✔
2275
}
5,728,386✔
2276

2277

2278
DB::ReadLockInfo DB::grab_read_lock(ReadLockInfo::Type type, VersionID version_id)
2279
{
5,693,346✔
2280
    CheckedLockGuard lock(m_mutex); // mx on m_local_locks_held
5,693,346✔
2281
    REALM_ASSERT_RELEASE(is_attached());
5,693,346✔
2282
    auto read_lock = m_version_manager->grab_read_lock(type, version_id);
5,693,346✔
2283

3,500,583✔
2284
    m_local_locks_held.emplace_back(read_lock);
5,693,346✔
2285
    ++m_transaction_count;
5,693,346✔
2286
    REALM_ASSERT(read_lock.m_file_size > read_lock.m_top_ref);
5,693,346✔
2287
    return read_lock;
5,693,346✔
2288
}
5,693,346✔
2289

2290
void DB::leak_read_lock(ReadLockInfo& read_lock) noexcept
2291
{
6✔
2292
    CheckedLockGuard lock(m_mutex); // mx on m_local_locks_held
6✔
2293
    // simple linear search and move-last-over if a match is found.
3✔
2294
    // common case should have only a modest number of transactions in play..
3✔
2295
    for (size_t j = 0; j < m_local_locks_held.size(); ++j) {
6✔
2296
        if (m_local_locks_held[j].m_version == read_lock.m_version) {
6✔
2297
            m_local_locks_held[j] = m_local_locks_held.back();
6✔
2298
            m_local_locks_held.pop_back();
6✔
2299
            --m_transaction_count;
6✔
2300
            return;
6✔
2301
        }
6✔
2302
    }
6✔
2303
}
6✔
2304

2305
bool DB::do_try_begin_write()
2306
{
84✔
2307
    // In the non-blocking case, we will only succeed if there is no contention for
42✔
2308
    // the write mutex. For this case we are trivially fair and can ignore the
42✔
2309
    // fairness machinery.
42✔
2310
    bool got_the_lock = m_writemutex.try_lock();
84✔
2311
    if (got_the_lock) {
84✔
2312
        finish_begin_write();
72✔
2313
    }
72✔
2314
    return got_the_lock;
84✔
2315
}
84✔
2316

2317
void DB::do_begin_write()
2318
{
1,383,951✔
2319
    if (m_logger) {
1,383,951✔
2320
        m_logger->log(util::Logger::Level::trace, "acquire writemutex");
306,246✔
2321
    }
306,246✔
2322

697,779✔
2323
    SharedInfo* info = m_info;
1,383,951✔
2324

697,779✔
2325
    // Get write lock - the write lock is held until do_end_write().
697,779✔
2326
    //
697,779✔
2327
    // We use a ticketing scheme to ensure fairness wrt performing write transactions.
697,779✔
2328
    // (But cannot do that on Windows until we have interprocess condition variables there)
697,779✔
2329
    uint32_t my_ticket = info->next_ticket.fetch_add(1, std::memory_order_relaxed);
1,383,951✔
2330
    m_writemutex.lock(); // Throws
1,383,951✔
2331

697,779✔
2332
    // allow for comparison even after wrap around of ticket numbering:
697,779✔
2333
    int32_t diff = int32_t(my_ticket - info->next_served.load(std::memory_order_relaxed));
1,383,951✔
2334
    bool should_yield = diff > 0; // ticket is in the future
1,383,951✔
2335
    // a) the above comparison is only guaranteed to be correct, if the distance
697,779✔
2336
    //    between my_ticket and info->next_served is less than 2^30. This will
697,779✔
2337
    //    be the case since the distance will be bounded by the number of threads
697,779✔
2338
    //    and each thread cannot ever hold more than one ticket.
697,779✔
2339
    // b) we could use 64 bit counters instead, but it is unclear if all platforms
697,779✔
2340
    //    have support for interprocess atomics for 64 bit values.
697,779✔
2341

697,779✔
2342
    timespec time_limit; // only compute the time limit if we're going to use it:
1,383,951✔
2343
    if (should_yield) {
1,383,951✔
2344
        // This clock is not monotonic, so time can move backwards. This can lead
18,213✔
2345
        // to a wrong time limit, but the only effect of a wrong time limit is that
18,213✔
2346
        // we momentarily lose fairness, so we accept it.
18,213✔
2347
        timeval tv;
20,235✔
2348
        gettimeofday(&tv, nullptr);
20,235✔
2349
        time_limit.tv_sec = tv.tv_sec;
20,235✔
2350
        time_limit.tv_nsec = tv.tv_usec * 1000;
20,235✔
2351
        time_limit.tv_nsec += 500000000;        // 500 msec wait
20,235✔
2352
        if (time_limit.tv_nsec >= 1000000000) { // overflow
20,235✔
2353
            time_limit.tv_nsec -= 1000000000;
10,725✔
2354
            time_limit.tv_sec += 1;
10,725✔
2355
        }
10,725✔
2356
    }
20,235✔
2357

697,779✔
2358
    while (should_yield) {
1,522,905✔
2359

134,526✔
2360
        m_pick_next_writer.wait(m_writemutex, &time_limit);
138,954✔
2361
        timeval tv;
138,954✔
2362
        gettimeofday(&tv, nullptr);
138,954✔
2363
        if (time_limit.tv_sec < tv.tv_sec ||
138,954✔
2364
            (time_limit.tv_sec == tv.tv_sec && time_limit.tv_nsec < tv.tv_usec * 1000)) {
138,954!
2365
            // Timeout!
UNCOV
2366
            break;
×
UNCOV
2367
        }
×
2368
        diff = int32_t(my_ticket - info->next_served);
138,954✔
2369
        should_yield = diff > 0; // ticket is in the future, so yield to someone else
138,954✔
2370
    }
138,954✔
2371

697,779✔
2372
    // we may get here because a) it's our turn, b) we timed out
697,779✔
2373
    // we don't distinguish, satisfied that event b) should be rare.
697,779✔
2374
    // In case b), we have to *make* it our turn. Failure to do so could leave us
697,779✔
2375
    // with 'next_served' permanently trailing 'next_ticket'.
697,779✔
2376
    //
697,779✔
2377
    // In doing so, we may bypass other waiters, hence the condition for yielding
697,779✔
2378
    // should take this situation into account by comparing with '>' instead of '!='
697,779✔
2379
    info->next_served = my_ticket;
1,383,951✔
2380
    finish_begin_write();
1,383,951✔
2381
    if (m_logger) {
1,383,951✔
2382
        m_logger->log(util::Logger::Level::trace, "writemutex acquired");
306,246✔
2383
    }
306,246✔
2384
}
1,383,951✔
2385

2386
void DB::finish_begin_write()
2387
{
1,384,053✔
2388
    if (m_info->commit_in_critical_phase) {
1,384,053✔
2389
        m_writemutex.unlock();
×
2390
        throw RuntimeError(ErrorCodes::BrokenInvariant, "Crash of other process detected, session restart required");
×
2391
    }
×
2392

697,842✔
2393

697,842✔
2394
    {
1,384,053✔
2395
        CheckedLockGuard local_lock(m_mutex);
1,384,053✔
2396
        m_write_transaction_open = true;
1,384,053✔
2397
    }
1,384,053✔
2398
    m_alloc.set_read_only(false);
1,384,053✔
2399
}
1,384,053✔
2400

2401
void DB::do_end_write() noexcept
2402
{
1,384,047✔
2403
    m_info->next_served.fetch_add(1, std::memory_order_relaxed);
1,384,047✔
2404

697,848✔
2405
    CheckedLockGuard local_lock(m_mutex);
1,384,047✔
2406
    REALM_ASSERT(m_write_transaction_open);
1,384,047✔
2407
    m_alloc.set_read_only(true);
1,384,047✔
2408
    m_write_transaction_open = false;
1,384,047✔
2409
    m_pick_next_writer.notify_all();
1,384,047✔
2410
    m_writemutex.unlock();
1,384,047✔
2411
    if (m_logger) {
1,384,047✔
2412
        m_logger->log(util::Logger::Level::trace, "writemutex released");
306,294✔
2413
    }
306,294✔
2414
}
1,384,047✔
2415

2416

2417
Replication::version_type DB::do_commit(Transaction& transaction, bool commit_to_disk)
2418
{
1,361,340✔
2419
    version_type current_version;
1,361,340✔
2420
    {
1,361,340✔
2421
        current_version = m_version_manager->get_newest_version();
1,361,340✔
2422
    }
1,361,340✔
2423
    version_type new_version = current_version + 1;
1,361,340✔
2424

686,502✔
2425
    if (!transaction.m_objects_to_delete.empty()) {
1,361,340✔
2426
        for (auto it : transaction.m_objects_to_delete) {
1,260✔
2427
            transaction.get_table(it.table_key)->remove_object(it.obj_key);
1,260✔
2428
        }
1,260✔
2429
        transaction.m_objects_to_delete.clear();
654✔
2430
    }
654✔
2431
    if (Replication* repl = get_replication()) {
1,361,340✔
2432
        // If Replication::prepare_commit() fails, then the entire transaction
677,580✔
2433
        // fails. The application then has the option of terminating the
677,580✔
2434
        // transaction with a call to Transaction::Rollback(), which in turn
677,580✔
2435
        // must call Replication::abort_transact().
677,580✔
2436
        new_version = repl->prepare_commit(current_version);        // Throws
1,343,451✔
2437
        low_level_commit(new_version, transaction, commit_to_disk); // Throws
1,343,451✔
2438
        repl->finalize_commit();
1,343,451✔
2439
    }
1,343,451✔
2440
    else {
17,889✔
2441
        low_level_commit(new_version, transaction); // Throws
17,889✔
2442
    }
17,889✔
2443
    return new_version;
1,361,340✔
2444
}
1,361,340✔
2445

2446
VersionID DB::get_version_id_of_latest_snapshot()
2447
{
833,358✔
2448
    if (m_fake_read_lock_if_immutable)
833,358✔
2449
        return {m_fake_read_lock_if_immutable->m_version, 0};
12✔
2450
    return m_version_manager->get_version_id_of_latest_snapshot();
833,346✔
2451
}
833,346✔
2452

2453

2454
DB::version_type DB::get_version_of_latest_snapshot()
2455
{
832,803✔
2456
    return get_version_id_of_latest_snapshot().version;
832,803✔
2457
}
832,803✔
2458

2459

2460
void DB::low_level_commit(uint_fast64_t new_version, Transaction& transaction, bool commit_to_disk)
2461
{
1,361,394✔
2462
    SharedInfo* info = m_info;
1,361,394✔
2463

686,538✔
2464
    // Version of oldest snapshot currently (or recently) bound in a transaction
686,538✔
2465
    // of the current session.
686,538✔
2466
    uint64_t oldest_version = 0, oldest_live_version = 0;
1,361,394✔
2467
    TopRefMap top_refs;
1,361,394✔
2468
    bool any_new_unreachables;
1,361,394✔
2469
    {
1,361,394✔
2470
        CheckedLockGuard lock(m_mutex);
1,361,394✔
2471
        m_version_manager->cleanup_versions(oldest_live_version, top_refs, any_new_unreachables);
1,361,394✔
2472
        oldest_version = top_refs.begin()->first;
1,361,394✔
2473
        // Allow for trimming of the history. Some types of histories do not
686,538✔
2474
        // need store changesets prior to the oldest *live* bound snapshot.
686,538✔
2475
        if (auto hist = transaction.get_history()) {
1,361,394✔
2476
            hist->set_oldest_bound_version(oldest_live_version); // Throws
1,343,427✔
2477
        }
1,343,427✔
2478
        // Cleanup any stale mappings
686,538✔
2479
        m_alloc.purge_old_mappings(oldest_version, new_version);
1,361,394✔
2480
    }
1,361,394✔
2481
    // save number of live versions for later:
686,538✔
2482
    // (top_refs is std::moved into GroupWriter so we'll loose it in the call to set_versions below)
686,538✔
2483
    auto live_versions = top_refs.size();
1,361,394✔
2484
    // Do the actual commit
686,538✔
2485
    REALM_ASSERT(oldest_version <= new_version);
1,361,394✔
2486
#if REALM_METRICS
1,361,394✔
2487
    transaction.update_num_objects();
1,361,394✔
2488
#endif // REALM_METRICS
1,361,394✔
2489

686,538✔
2490
    GroupWriter out(transaction, Durability(info->durability), m_marker_observer.get()); // Throws
1,361,394✔
2491
    out.set_versions(new_version, top_refs, any_new_unreachables);
1,361,394✔
2492
    out.prepare_evacuation();
1,361,394✔
2493
    auto t1 = std::chrono::steady_clock::now();
1,361,394✔
2494
    auto commit_size = m_alloc.get_commit_size();
1,361,394✔
2495
    if (m_logger) {
1,361,394✔
2496
        m_logger->log(util::Logger::Level::debug, "Initiate commit version: %1", new_version);
285,273✔
2497
    }
285,273✔
2498
    if (auto limit = out.get_evacuation_limit()) {
1,361,394✔
2499
        // Get a work limit based on the size of the transaction we're about to commit
2,655✔
2500
        // Add 4k to ensure progress on small commits
2,655✔
2501
        size_t work_limit = commit_size / 2 + out.get_free_list_size() + 0x1000;
5,301✔
2502
        transaction.cow_outliers(out.get_evacuation_progress(), limit, work_limit);
5,301✔
2503
    }
5,301✔
2504

686,538✔
2505
    ref_type new_top_ref;
1,361,394✔
2506
    // Recursively write all changed arrays to end of file
686,538✔
2507
    {
1,361,394✔
2508
        // protect against race with any other DB trying to attach to the file
686,538✔
2509
        std::lock_guard<InterprocessMutex> lock(m_controlmutex); // Throws
1,361,394✔
2510
        new_top_ref = out.write_group();                         // Throws
1,361,394✔
2511
    }
1,361,394✔
2512
    {
1,361,394✔
2513
        // protect access to shared variables and m_reader_mapping from here
686,538✔
2514
        CheckedLockGuard lock_guard(m_mutex);
1,361,394✔
2515
        m_free_space = out.get_free_space_size();
1,361,394✔
2516
        m_locked_space = out.get_locked_space_size();
1,361,394✔
2517
        m_used_space = out.get_logical_size() - m_free_space;
1,361,394✔
2518
        m_evac_stage.store(EvacStage(out.get_evacuation_stage()));
1,361,394✔
2519
        out.sync_according_to_durability();
1,361,394✔
2520
        if (Durability(info->durability) == Durability::Full || Durability(info->durability) == Durability::Unsafe) {
1,361,394✔
2521
            if (commit_to_disk) {
1,199,889✔
2522
                GroupCommitter cm(transaction, Durability(info->durability), m_marker_observer.get());
1,192,359✔
2523
                cm.commit(new_top_ref);
1,192,359✔
2524
            }
1,192,359✔
2525
        }
1,199,889✔
2526
        size_t new_file_size = out.get_logical_size();
1,361,394✔
2527
        // We must reset the allocators free space tracking before communicating the new
686,538✔
2528
        // version through the ring buffer. If not, a reader may start updating the allocators
686,538✔
2529
        // mappings while the allocator is in dirty state.
686,538✔
2530
        reset_free_space_tracking();
1,361,394✔
2531
        // Add the new version. If this fails in any way, the VersionList may be corrupted.
686,538✔
2532
        // This can lead to readers seing invalid data which is likely to cause them
686,538✔
2533
        // to crash. Other writers *must* be prevented from writing any further updates
686,538✔
2534
        // to the database. The flag "commit_in_critical_phase" is used to prevent such updates.
686,538✔
2535
        info->commit_in_critical_phase = 1;
1,361,394✔
2536
        {
1,361,394✔
2537
            m_version_manager->add_version(new_top_ref, new_file_size, new_version);
1,361,394✔
2538

686,538✔
2539
            // REALM_ASSERT(m_alloc.matches_section_boundary(new_file_size));
686,538✔
2540
            REALM_ASSERT(new_top_ref < new_file_size);
1,361,394✔
2541
        }
1,361,394✔
2542
        // At this point, the VersionList has been succesfully updated, and the next writer
686,538✔
2543
        // can safely proceed once the writemutex has been lifted.
686,538✔
2544
        info->commit_in_critical_phase = 0;
1,361,394✔
2545
    }
1,361,394✔
2546
    {
1,361,394✔
2547
        // protect against concurrent updates to the .lock file.
686,538✔
2548
        // must release m_mutex before this point to obey lock order
686,538✔
2549
        std::lock_guard<InterprocessMutex> lock(m_controlmutex);
1,361,394✔
2550

686,538✔
2551
        info->number_of_versions = live_versions + 1;
1,361,394✔
2552
        info->latest_version_number = new_version;
1,361,394✔
2553

686,538✔
2554
        m_new_commit_available.notify_all();
1,361,394✔
2555
    }
1,361,394✔
2556
    auto t2 = std::chrono::steady_clock::now();
1,361,394✔
2557
    if (m_logger) {
1,361,394✔
2558
        std::string to_disk_str = commit_to_disk ? util::format(" ref %1", new_top_ref) : " (no commit to disk)";
281,136✔
2559
        m_logger->log(util::Logger::Level::debug, "Commit of size %1 done in %2 us%3", commit_size,
285,273✔
2560
                      std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count(), to_disk_str);
285,273✔
2561
    }
285,273✔
2562
}
1,361,394✔
2563

2564
#ifdef REALM_DEBUG
2565
void DB::reserve(size_t size)
2566
{
36✔
2567
    REALM_ASSERT(is_attached());
36✔
2568
    m_alloc.reserve_disk_space(size); // Throws
36✔
2569
}
36✔
2570
#endif
2571

2572
bool DB::call_with_lock(const std::string& realm_path, CallbackWithLock&& callback)
2573
{
693✔
2574
    auto lockfile_path = get_core_file(realm_path, CoreFileType::Lock);
693✔
2575

306✔
2576
    File lockfile;
693✔
2577
    lockfile.open(lockfile_path, File::access_ReadWrite, File::create_Auto, 0); // Throws
693✔
2578
    File::CloseGuard fcg(lockfile);
693✔
2579
    lockfile.set_fifo_path(realm_path + ".management", "lock.fifo");
693✔
2580
    if (lockfile.try_rw_lock_exclusive()) { // Throws
693✔
2581
        callback(realm_path);
651✔
2582
        return true;
651✔
2583
    }
651✔
2584
    return false;
42✔
2585
}
42✔
2586

2587
std::string DB::get_core_file(const std::string& base_path, CoreFileType type)
2588
{
308,109✔
2589
    switch (type) {
308,109✔
2590
        case CoreFileType::Lock:
144,447✔
2591
            return base_path + ".lock";
144,447✔
2592
        case CoreFileType::Storage:
732✔
2593
            return base_path;
732✔
2594
        case CoreFileType::Management:
144,300✔
2595
            return base_path + ".management";
144,300✔
2596
        case CoreFileType::Note:
17,898✔
2597
            return base_path + ".note";
17,898✔
2598
        case CoreFileType::Log:
732✔
2599
            return base_path + ".log";
732✔
2600
    }
×
2601
    REALM_UNREACHABLE();
×
2602
}
×
2603

2604
void DB::delete_files(const std::string& base_path, bool* did_delete, bool delete_lockfile)
2605
{
726✔
2606
    if (File::try_remove(get_core_file(base_path, CoreFileType::Storage)) && did_delete) {
726✔
2607
        *did_delete = true;
168✔
2608
    }
168✔
2609

363✔
2610
    File::try_remove(get_core_file(base_path, CoreFileType::Note));
726✔
2611
    File::try_remove(get_core_file(base_path, CoreFileType::Log));
726✔
2612
    util::try_remove_dir_recursive(get_core_file(base_path, CoreFileType::Management));
726✔
2613

363✔
2614
    if (delete_lockfile) {
726✔
2615
        File::try_remove(get_core_file(base_path, CoreFileType::Lock));
180✔
2616
    }
180✔
2617
}
726✔
2618

2619
TransactionRef DB::start_read(VersionID version_id)
2620
{
1,610,970✔
2621
    if (!is_attached())
1,610,970✔
2622
        throw StaleAccessor("Stale transaction");
6✔
2623
    TransactionRef tr;
1,610,964✔
2624
    if (m_fake_read_lock_if_immutable) {
1,610,964✔
2625
        tr = make_transaction_ref(shared_from_this(), &m_alloc, *m_fake_read_lock_if_immutable, DB::transact_Reading);
354✔
2626
    }
354✔
2627
    else {
1,610,610✔
2628
        ReadLockInfo read_lock = grab_read_lock(ReadLockInfo::Live, version_id);
1,610,610✔
2629
        ReadLockGuard g(*this, read_lock);
1,610,610✔
2630
        read_lock.check();
1,610,610✔
2631
        tr = make_transaction_ref(shared_from_this(), &m_alloc, read_lock, DB::transact_Reading);
1,610,610✔
2632
        g.release();
1,610,610✔
2633
    }
1,610,610✔
2634
    tr->set_file_format_version(get_file_format_version());
1,610,964✔
2635
    return tr;
1,610,964✔
2636
}
1,610,964✔
2637

2638
TransactionRef DB::start_frozen(VersionID version_id)
2639
{
30,045✔
2640
    if (!is_attached())
30,045✔
2641
        throw StaleAccessor("Stale transaction");
×
2642
    TransactionRef tr;
30,045✔
2643
    if (m_fake_read_lock_if_immutable) {
30,045✔
2644
        tr = make_transaction_ref(shared_from_this(), &m_alloc, *m_fake_read_lock_if_immutable, DB::transact_Frozen);
12✔
2645
    }
12✔
2646
    else {
30,033✔
2647
        ReadLockInfo read_lock = grab_read_lock(ReadLockInfo::Frozen, version_id);
30,033✔
2648
        ReadLockGuard g(*this, read_lock);
30,033✔
2649
        read_lock.check();
30,033✔
2650
        tr = make_transaction_ref(shared_from_this(), &m_alloc, read_lock, DB::transact_Frozen);
30,033✔
2651
        g.release();
30,033✔
2652
    }
30,033✔
2653
    tr->set_file_format_version(get_file_format_version());
30,045✔
2654
    return tr;
30,045✔
2655
}
30,045✔
2656

2657
TransactionRef DB::start_write(bool nonblocking)
2658
{
999,390✔
2659
    if (m_fake_read_lock_if_immutable) {
999,390✔
2660
        REALM_ASSERT(false && "Can't write an immutable DB");
×
2661
    }
×
2662
    if (nonblocking) {
999,390✔
2663
        bool success = do_try_begin_write();
84✔
2664
        if (!success) {
84✔
2665
            return TransactionRef();
12✔
2666
        }
12✔
2667
    }
999,306✔
2668
    else {
999,306✔
2669
        do_begin_write();
999,306✔
2670
    }
999,306✔
2671
    {
999,384✔
2672
        CheckedUniqueLock local_lock(m_mutex);
999,378✔
2673
        if (!is_attached()) {
999,378✔
2674
            local_lock.unlock();
×
2675
            end_write_on_correct_thread();
×
2676
            throw StaleAccessor("Stale transaction");
×
2677
        }
×
2678
        m_write_transaction_open = true;
999,378✔
2679
    }
999,378✔
2680
    TransactionRef tr;
999,378✔
2681
    try {
999,378✔
2682
        ReadLockInfo read_lock = grab_read_lock(ReadLockInfo::Live, VersionID());
999,378✔
2683
        ReadLockGuard g(*this, read_lock);
999,378✔
2684
        read_lock.check();
999,378✔
2685

506,604✔
2686
        tr = make_transaction_ref(shared_from_this(), &m_alloc, read_lock, DB::transact_Writing);
999,378✔
2687
        tr->set_file_format_version(get_file_format_version());
999,378✔
2688
        version_type current_version = read_lock.m_version;
999,378✔
2689
        m_alloc.init_mapping_management(current_version);
999,378✔
2690
        if (Replication* repl = get_replication()) {
999,378✔
2691
            bool history_updated = false;
981,798✔
2692
            repl->initiate_transact(*tr, current_version, history_updated); // Throws
981,798✔
2693
        }
981,798✔
2694
        g.release();
999,378✔
2695
    }
999,378✔
2696
    catch (...) {
506,604✔
2697
        end_write_on_correct_thread();
×
2698
        throw;
×
2699
    }
×
2700

506,592✔
2701
    return tr;
999,354✔
2702
}
999,354✔
2703

2704
void DB::async_request_write_mutex(TransactionRef& tr, util::UniqueFunction<void()>&& when_acquired)
2705
{
1,614✔
2706
    {
1,614✔
2707
        util::CheckedLockGuard lck(tr->m_async_mutex);
1,614✔
2708
        REALM_ASSERT(tr->m_async_stage == Transaction::AsyncState::Idle);
1,614✔
2709
        tr->m_async_stage = Transaction::AsyncState::Requesting;
1,614✔
2710
        tr->m_request_time_point = std::chrono::steady_clock::now();
1,614✔
2711
        if (tr->db->m_logger) {
1,614✔
2712
            tr->db->m_logger->log(util::Logger::Level::trace, "Tr %1: Async request write lock", tr->m_log_id);
1,614✔
2713
        }
1,614✔
2714
    }
1,614✔
2715
    std::weak_ptr<Transaction> weak_tr = tr;
1,614✔
2716
    async_begin_write([weak_tr, cb = std::move(when_acquired)]() {
1,614✔
2717
        if (auto tr = weak_tr.lock()) {
1,614✔
2718
            util::CheckedLockGuard lck(tr->m_async_mutex);
1,614✔
2719
            // If a synchronous transaction happened while we were pending
393✔
2720
            // we may be in HasCommits
393✔
2721
            if (tr->m_async_stage == Transaction::AsyncState::Requesting) {
1,614✔
2722
                tr->m_async_stage = Transaction::AsyncState::HasLock;
1,614✔
2723
            }
1,614✔
2724
            if (tr->db->m_logger) {
1,614✔
2725
                auto t2 = std::chrono::steady_clock::now();
1,614✔
2726
                tr->db->m_logger->log(
1,614✔
2727
                    util::Logger::Level::trace, "Tr %1, Got write lock in %2 us", tr->m_log_id,
1,614✔
2728
                    std::chrono::duration_cast<std::chrono::microseconds>(t2 - tr->m_request_time_point).count());
1,614✔
2729
            }
1,614✔
2730
            if (tr->m_waiting_for_write_lock) {
1,614✔
2731
                tr->m_waiting_for_write_lock = false;
132✔
2732
                tr->m_async_cv.notify_one();
132✔
2733
            }
132✔
2734
            else if (cb) {
1,482✔
2735
                cb();
1,482✔
2736
            }
1,482✔
2737
            tr.reset(); // Release pointer while lock is held
1,614✔
2738
        }
1,614✔
2739
    });
1,614✔
2740
}
1,614✔
2741

2742
inline DB::DB(const DBOptions& options)
2743
    : m_upgrade_callback(std::move(options.upgrade_callback))
2744
    , m_log_id(util::gen_log_id(this))
2745
{
169,014✔
2746
    if (options.enable_async_writes) {
169,014✔
2747
        m_commit_helper = std::make_unique<AsyncCommitHelper>(this);
130,377✔
2748
    }
130,377✔
2749
}
169,014✔
2750

2751
namespace {
2752
class DBInit : public DB {
2753
public:
2754
    explicit DBInit(const DBOptions& options)
2755
        : DB(options)
2756
    {
169,014✔
2757
    }
169,014✔
2758
};
2759
} // namespace
2760

2761
DBRef DB::create(const std::string& file, bool no_create, const DBOptions& options) NO_THREAD_SAFETY_ANALYSIS
2762
{
24,840✔
2763
    DBRef retval = std::make_shared<DBInit>(options);
24,840✔
2764
    retval->open(file, no_create, options);
24,840✔
2765
    return retval;
24,840✔
2766
}
24,840✔
2767

2768
DBRef DB::create(Replication& repl, const std::string& file, const DBOptions& options) NO_THREAD_SAFETY_ANALYSIS
2769
{
10,491✔
2770
    DBRef retval = std::make_shared<DBInit>(options);
10,491✔
2771
    retval->open(repl, file, options);
10,491✔
2772
    return retval;
10,491✔
2773
}
10,491✔
2774

2775
DBRef DB::create(std::unique_ptr<Replication> repl, const std::string& file,
2776
                 const DBOptions& options) NO_THREAD_SAFETY_ANALYSIS
2777
{
108,417✔
2778
    REALM_ASSERT(repl);
108,417✔
2779
    DBRef retval = std::make_shared<DBInit>(options);
108,417✔
2780
    retval->m_history = std::move(repl);
108,417✔
2781
    retval->open(*retval->m_history, file, options);
108,417✔
2782
    return retval;
108,417✔
2783
}
108,417✔
2784

2785
DBRef DB::create(std::unique_ptr<Replication> repl, const DBOptions& options) NO_THREAD_SAFETY_ANALYSIS
2786
{
25,260✔
2787
    REALM_ASSERT(repl);
25,260✔
2788
    DBRef retval = std::make_shared<DBInit>(options);
25,260✔
2789
    retval->m_history = std::move(repl);
25,260✔
2790
    retval->open(*retval->m_history, options);
25,260✔
2791
    return retval;
25,260✔
2792
}
25,260✔
2793

2794
DBRef DB::create_in_memory(std::unique_ptr<Replication> repl, const std::string& in_memory_path,
2795
                           const DBOptions& options) NO_THREAD_SAFETY_ANALYSIS
2796
{
×
2797
    DBRef db = create(std::move(repl), options);
×
2798
    db->m_db_path = in_memory_path;
×
2799
    return db;
×
2800
}
×
2801

2802
DBRef DB::create(BinaryData buffer, bool take_ownership) NO_THREAD_SAFETY_ANALYSIS
2803
{
6✔
2804
    DBOptions options;
6✔
2805
    options.is_immutable = true;
6✔
2806
    DBRef retval = std::make_shared<DBInit>(options);
6✔
2807
    retval->open(buffer, take_ownership);
6✔
2808
    return retval;
6✔
2809
}
6✔
2810

2811
void DB::claim_sync_agent()
2812
{
15,951✔
2813
    REALM_ASSERT(is_attached());
15,951✔
2814
    std::unique_lock<InterprocessMutex> lock(m_controlmutex);
15,951✔
2815
    if (m_info->sync_agent_present)
15,951✔
2816
        throw MultipleSyncAgents{};
6✔
2817
    m_info->sync_agent_present = 1; // Set to true
15,945✔
2818
    m_is_sync_agent = true;
15,945✔
2819
}
15,945✔
2820

2821
void DB::release_sync_agent()
2822
{
14,658✔
2823
    REALM_ASSERT(is_attached());
14,658✔
2824
    std::unique_lock<InterprocessMutex> lock(m_controlmutex);
14,658✔
2825
    if (!m_is_sync_agent)
14,658✔
2826
        return;
264✔
2827
    REALM_ASSERT(m_info->sync_agent_present);
14,394✔
2828
    m_info->sync_agent_present = 0;
14,394✔
2829
    m_is_sync_agent = false;
14,394✔
2830
}
14,394✔
2831

2832
void DB::do_begin_possibly_async_write()
2833
{
383,058✔
2834
    if (m_commit_helper) {
383,058✔
2835
        m_commit_helper->blocking_begin_write();
258,678✔
2836
    }
258,678✔
2837
    else {
124,380✔
2838
        do_begin_write();
124,380✔
2839
    }
124,380✔
2840
}
383,058✔
2841

2842
void DB::end_write_on_correct_thread() noexcept
2843
{
1,382,616✔
2844
    //    m_local_write_mutex.unlock();
697,515✔
2845
    if (!m_commit_helper || !m_commit_helper->blocking_end_write()) {
1,382,616✔
2846
        do_end_write();
1,123,731✔
2847
    }
1,123,731✔
2848
}
1,382,616✔
2849

2850
DisableReplication::DisableReplication(Transaction& t)
2851
    : m_tr(t)
2852
    , m_owner(t.get_db())
2853
    , m_repl(m_owner->get_replication())
2854
    , m_version(t.get_version())
2855
{
102✔
2856
    m_owner->set_replication(nullptr);
102✔
2857
    t.m_history = nullptr;
102✔
2858
}
102✔
2859

2860
DisableReplication::~DisableReplication()
2861
{
102✔
2862
    m_owner->set_replication(m_repl);
102✔
2863
    if (m_version != m_tr.get_version())
102✔
2864
        m_tr.initialize_replication();
102✔
2865
}
102✔
2866

2867
} // namespace realm
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc