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

realm / realm-core / 2387

05 Jun 2024 03:48PM UTC coverage: 90.873% (+0.03%) from 90.844%
2387

push

Evergreen

web-flow
Revert "Disable replication when writing to the pending bootstrap store" (#7776)

This reverts commit afe0e0f3b.

DisableReplication actually disables replication on the DB, not the
Transaction, so it's extremely unsafe to use.

101884 of 180236 branches covered (56.53%)

27 of 31 new or added lines in 1 file covered. (87.1%)

43 existing lines in 14 files now uncovered.

214843 of 236420 relevant lines covered (90.87%)

5990812.98 hits per line

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

91.71
/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::util;
61
using Durability = DBOptions::Durability;
62

63
namespace {
64

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

85

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

111
    void reserve(uint32_t size) noexcept
112
    {
194,823✔
113
        for (auto i = entries; i < size; ++i)
6,429,045✔
114
            data()[i].deactivate();
6,234,222✔
115
        if (size > entries) {
194,829✔
116
            // Fence preventing downward motion of above writes
117
            std::atomic_signal_fence(std::memory_order_release);
194,829✔
118
            entries = size;
194,829✔
119
        }
194,829✔
120
    }
194,823✔
121

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

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

137
    unsigned int capacity() const noexcept
138
    {
1,208,667✔
139
        return entries;
1,208,667✔
140
    }
1,208,667✔
141

142
    ReadCount& get(uint_fast32_t idx) noexcept
143
    {
3,297,450✔
144
        return data()[idx];
3,297,450✔
145
    }
3,297,450✔
146

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

178
    uint32_t index_of(const ReadCount& rc) noexcept
179
    {
528,015✔
180
        return (uint32_t)(&rc - data());
528,015✔
181
    }
528,015✔
182

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

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

206
    void purge_versions(uint64_t& oldest_live_v, TopRefMap& top_refs, bool& any_new_unreachables)
207
    {
623,304✔
208
        oldest_live_v = std::numeric_limits<uint64_t>::max();
623,304✔
209
        auto oldest_full_v = std::numeric_limits<uint64_t>::max();
623,304✔
210
        any_new_unreachables = false;
623,304✔
211
        // correct case where an earlier crash may have left the entry at 'allocating' partially initialized:
212
        const auto index_of_newest = newest.load();
623,304✔
213
        if (auto a = allocating.load(); a != index_of_newest) {
623,304✔
214
            data()[a].deactivate();
×
215
        }
×
216
        // determine fully locked versions - after one of those all versions are considered live.
217
        for (auto* rc = data(); rc < data() + entries; ++rc) {
21,232,347✔
218
            if (!rc->is_active())
20,609,043✔
219
                continue;
18,462,390✔
220
            if (rc->count_full) {
2,146,653✔
221
                if (rc->version < oldest_full_v)
×
222
                    oldest_full_v = rc->version;
×
223
            }
×
224
        }
2,146,653✔
225
        // collect reachable versions and determine oldest live reachable version
226
        // (oldest reachable version is the first entry in the top_refs map, so no need to find it explicitly)
227
        for (auto* rc = data(); rc < data() + entries; ++rc) {
21,233,766✔
228
            if (!rc->is_active())
20,610,462✔
229
                continue;
18,463,908✔
230
            if (rc->count_frozen || rc->count_live || rc->version >= oldest_full_v) {
2,146,554✔
231
                // entry is still reachable
232
                top_refs.emplace(rc->version, VersionInfo{to_ref(rc->current_top), to_ref(rc->filesize)});
1,618,845✔
233
            }
1,618,845✔
234
            if (rc->count_live || rc->version >= oldest_full_v) {
2,146,554✔
235
                if (rc->version < oldest_live_v)
1,059,162✔
236
                    oldest_live_v = rc->version;
697,563✔
237
            }
1,059,162✔
238
        }
2,146,554✔
239
        // we must have found at least one reachable version
240
        REALM_ASSERT(top_refs.size());
623,304✔
241
        // free unreachable entries and determine if we want to trigger backdating
242
        uint64_t oldest_v = top_refs.begin()->first;
623,304✔
243
        for (auto* rc = data(); rc < data() + entries; ++rc) {
21,232,458✔
244
            if (!rc->is_active())
20,609,154✔
245
                continue;
18,462,495✔
246
            if (rc->count_frozen == 0 && rc->count_live == 0 && rc->version < oldest_full_v) {
2,146,659✔
247
                // entry is becoming unreachable.
248
                // if it is also younger than a reachable version, then set 'any_new_unreachables' to trigger
249
                // backdating
250
                if (rc->version > oldest_v) {
528,018✔
251
                    any_new_unreachables = true;
76,764✔
252
                }
76,764✔
253
                REALM_ASSERT(index_of(*rc) != index_of_newest);
528,018✔
254
                free_entry(rc);
528,018✔
255
            }
528,018✔
256
        }
2,146,659✔
257
        REALM_ASSERT(oldest_v != std::numeric_limits<uint64_t>::max());
623,304✔
258
        REALM_ASSERT(oldest_live_v != std::numeric_limits<uint64_t>::max());
623,304✔
259
    }
623,304✔
260

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

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

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

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

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

303
template <typename... Args>
304
TransactionRef make_transaction_ref(Args&&... args)
305
{
1,774,719✔
306
    return TransactionRef(new Transaction(std::forward<Args>(args)...), TransactionDeleter);
1,774,719✔
307
}
1,774,719✔
308

309
} // anonymous namespace
310

311
namespace realm {
312

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

420
    uint8_t filler_1; // Offset 43
421

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

427
    uint16_t filler_2; // Offset 46
428

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

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

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

448
    void init_versioning(ref_type top_ref, size_t file_size, uint64_t initial_version)
449
    {
98,592✔
450
        // Create our first versioning entry:
451
        readers.init_versioning(top_ref, file_size, initial_version);
98,592✔
452
    }
98,592✔
453
};
454

455

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

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

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

522
class DB::VersionManager {
523
public:
524
    VersionManager(util::InterprocessMutex& mutex)
525
        : m_mutex(mutex)
61,911✔
526
    {
125,535✔
527
    }
125,535✔
528
    virtual ~VersionManager() {}
125,517✔
529

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

539
    version_type get_newest_version() REQUIRES(!m_local_readers_mutex, !m_info_mutex)
540
    {
623,310✔
541
        return get_version_id_of_latest_snapshot().version;
623,310✔
542
    }
623,310✔
543

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

563
        std::lock_guard lock(m_mutex);
24,567✔
564
        util::CheckedLockGuard info_lock(m_info_mutex);
24,567✔
565
        auto index = m_info->readers.newest.load();
24,567✔
566
        ensure_reader_mapping(index);
24,567✔
567
        return {m_info->readers.get(index).version, index};
24,567✔
568
    }
41,153,040✔
569

570
    void release_read_lock(const ReadLockInfo& read_lock) REQUIRES(!m_local_readers_mutex, !m_info_mutex)
571
    {
4,333,158✔
572
        {
4,333,158✔
573
            util::CheckedLockGuard lock(m_local_readers_mutex);
4,333,158✔
574
            REALM_ASSERT(read_lock.m_reader_idx < m_local_readers.size());
4,333,158✔
575
            auto& r = m_local_readers[read_lock.m_reader_idx];
4,333,158✔
576
            auto& f = field_for_type(r, read_lock.m_type);
4,333,158✔
577
            REALM_ASSERT(f > 0);
4,333,158✔
578
            if (--f > 0)
4,333,158✔
579
                return;
2,696,763✔
580
            if (r.count_live == 0 && r.count_full == 0 && r.count_frozen == 0)
1,636,395✔
581
                r.version = 0;
1,612,806✔
582
        }
1,636,395✔
583

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

595
    ReadLockInfo grab_read_lock(ReadLockInfo::Type type, VersionID version_id = {})
596
        REQUIRES(!m_local_readers_mutex, !m_info_mutex)
597
    {
4,333,257✔
598
        ReadLockInfo read_lock;
4,333,257✔
599
        if (try_grab_local_read_lock(read_lock, type, version_id))
4,333,257✔
600
            return read_lock;
2,696,763✔
601

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

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

637
        return read_lock;
1,636,362✔
638
    }
1,636,422✔
639

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

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

665

666
private:
667
    void grow_local_cache(size_t new_size) REQUIRES(m_local_readers_mutex)
668
    {
1,636,566✔
669
        if (new_size > m_local_readers.size())
1,636,566✔
670
            m_local_readers.resize(new_size, VersionList::ReadCount{});
227,667✔
671
    }
1,636,566✔
672

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

682
    bool try_grab_local_read_lock(ReadLockInfo& read_lock, ReadLockInfo::Type type, VersionID version_id)
683
        REQUIRES(!m_local_readers_mutex, !m_info_mutex)
684
    {
4,333,275✔
685
        const bool pick_specific = version_id.version != VersionID().version;
4,333,275✔
686
        auto index = version_id.index;
4,333,275✔
687
        if (!pick_specific) {
4,333,275✔
688
            util::CheckedLockGuard lock(m_info_mutex);
4,038,525✔
689
            index = m_info->readers.newest.load();
4,038,525✔
690
        }
4,038,525✔
691
        util::CheckedLockGuard local_lock(m_local_readers_mutex);
4,333,275✔
692
        if (index >= m_local_readers.size())
4,333,275✔
693
            return false;
227,670✔
694

695
        auto& r = m_local_readers[index];
4,105,605✔
696
        if (!r.is_active())
4,105,605✔
697
            return false;
1,385,205✔
698
        if (pick_specific && r.version != version_id.version)
2,720,400✔
699
            return false;
×
700
        if (field_for_type(r, type) == 0)
2,720,400✔
701
            return false;
23,730✔
702

703
        read_lock.m_reader_idx = index;
2,696,670✔
704
        populate_read_lock(read_lock, r, type);
2,696,670✔
705
        return true;
2,696,670✔
706
    }
2,720,400✔
707

708
    static uint32_t& field_for_type(VersionList::ReadCount& r, ReadLockInfo::Type type)
709
    {
16,294,179✔
710
        switch (type) {
16,294,179✔
711
            case ReadLockInfo::Frozen:
220,578✔
712
                return r.count_frozen;
220,578✔
713
            case ReadLockInfo::Live:
16,073,697✔
714
                return r.count_live;
16,073,697✔
715
            case ReadLockInfo::Full:
✔
716
                return r.count_full;
×
717
            default:
✔
718
                REALM_UNREACHABLE(); // silence a warning
719
        }
16,294,179✔
720
    }
16,294,179✔
721

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

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

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

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

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

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

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

797
private:
798
    void ensure_reader_mapping(unsigned int required = -1) override REQUIRES(m_info_mutex)
799
    {
2,571,654✔
800
        using _impl::SimulatedFailure;
2,571,654✔
801
        SimulatedFailure::trigger(SimulatedFailure::shared_group__grow_reader_mapping); // Throws
2,571,654✔
802

803
        if (required < m_local_max_entry)
2,571,654✔
804
            return;
1,488,531✔
805

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

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

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

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

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

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

873
private:
874
    void ensure_reader_mapping(unsigned int) override {}
335,934✔
875
};
876

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

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

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

907
    REALM_ASSERT(!is_attached());
99,183✔
908
    REALM_ASSERT(path.size());
99,183✔
909

910
    m_db_path = path;
99,183✔
911

912
    set_logger(options.logger);
99,183✔
913
    if (m_replication) {
99,183✔
914
        m_replication->set_logger(m_logger.get());
71,916✔
915
    }
71,916✔
916
    if (m_logger) {
99,183✔
917
        m_logger->log(util::Logger::Level::detail, "Open file: %1", path);
80,874✔
918
    }
80,874✔
919
    SlabAlloc& alloc = m_alloc;
99,183✔
920
    ref_type top_ref = 0;
99,183✔
921

922
    if (options.is_immutable) {
99,183✔
923
        SlabAlloc::Config cfg;
186✔
924
        cfg.read_only = true;
186✔
925
        cfg.no_create = true;
186✔
926
        cfg.encryption_key = options.encryption_key;
186✔
927
        top_ref = alloc.attach_file(path, cfg);
186✔
928
        SlabAlloc::DetachGuard dg(alloc);
186✔
929
        Group::read_only_version_check(alloc, top_ref, path);
186✔
930
        m_fake_read_lock_if_immutable = ReadLockInfo::make_fake(top_ref, m_alloc.get_baseline());
186✔
931
        dg.release();
186✔
932
        return;
186✔
933
    }
186✔
934
    std::string lockfile_path = get_core_file(path, CoreFileType::Lock);
98,997✔
935
    std::string coordination_dir = get_core_file(path, CoreFileType::Management);
98,997✔
936
    std::string lockfile_prefix = coordination_dir + "/access_control";
98,997✔
937
    m_alloc.set_read_only(false);
98,997✔
938

939
    Replication::HistoryType openers_hist_type = Replication::hist_None;
98,997✔
940
    int openers_hist_schema_version = 0;
98,997✔
941
    if (Replication* repl = get_replication()) {
98,997✔
942
        openers_hist_type = repl->get_history_type();
71,916✔
943
        openers_hist_schema_version = repl->get_history_schema_version();
71,916✔
944
    }
71,916✔
945

946
    int current_file_format_version;
98,997✔
947
    int target_file_format_version;
98,997✔
948
    int stored_hist_schema_version = -1; // Signals undetermined
98,997✔
949

950
    int retries_left = 10; // number of times to retry before throwing exceptions
98,997✔
951
    // in case there is something wrong with the .lock file... the retries allows
952
    // us to pick a new lockfile initializer in case the first one crashes without
953
    // completing the initialization
954
    std::default_random_engine random_gen;
98,997✔
955
    for (;;) {
140,697✔
956

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

968
        m_file.open(lockfile_path, File::access_ReadWrite, File::create_Auto, 0); // Throws
140,697✔
969
        File::CloseGuard fcg(m_file);
140,697✔
970
        m_file.set_fifo_path(coordination_dir, "lock.fifo");
140,697✔
971

972
        if (m_file.try_rw_lock_exclusive()) { // Throws
140,697✔
973
            File::UnlockGuard ulg(m_file);
70,677✔
974

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

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

992
            new (info) SharedInfo{options.durability, openers_hist_type, openers_hist_schema_version}; // Throws
70,677✔
993

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

999
// We hold the shared lock from here until we close the file!
1000
#if REALM_PLATFORM_APPLE
79,539✔
1001
        // macOS has a bug which can cause a hang waiting to obtain a lock, even
1002
        // if the lock is already open in shared mode, so we work around it by
1003
        // busy waiting. This should occur only briefly during session initialization.
1004
        while (!m_file.try_rw_lock_shared()) {
92,538✔
1005
            sched_yield();
12,999✔
1006
        }
12,999✔
1007
#else
1008
        m_file.rw_lock_shared(); // Throws
61,158✔
1009
#endif
61,158✔
1010
        File::UnlockGuard ulg(m_file);
140,697✔
1011

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

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

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

1038
        // An empty file is (and was) never a successfully initialized file.
1039
        size_t info_size = sizeof(SharedInfo);
140,697✔
1040
        {
140,697✔
1041
            auto file_size = m_file.get_size();
140,697✔
1042
            if (util::int_less_than(file_size, info_size)) {
140,697✔
1043
                if (file_size == 0)
40,470✔
1044
                    continue; // Retry
20,535✔
1045
                info_size = size_t(file_size);
19,935✔
1046
            }
19,935✔
1047
        }
140,697✔
1048

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

1057
#ifndef _WIN32
120,162✔
1058
#pragma GCC diagnostic push
120,162✔
1059
#pragma GCC diagnostic ignored "-Winvalid-offsetof"
120,162✔
1060
#endif
120,162✔
1061
        static_assert(offsetof(SharedInfo, init_complete) + sizeof SharedInfo::init_complete <= 1,
120,162✔
1062
                      "Unexpected position or size of SharedInfo::init_complete");
120,162✔
1063
#ifndef _WIN32
120,162✔
1064
#pragma GCC diagnostic pop
120,162✔
1065
#endif
120,162✔
1066
        if (info->init_complete == 0)
120,162✔
1067
            continue;
19,869✔
1068
        REALM_ASSERT(info->init_complete == 1);
100,293✔
1069

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

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

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

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

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

1149
            // only the session initiator is allowed to create the database, all other
1150
            // must assume that it already exists.
1151
            cfg.no_create = (begin_new_session ? options.no_create : true);
100,029✔
1152

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

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

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

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

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

1231
            if (REALM_UNLIKELY(!file_format_ok)) {
99,927✔
1232
                throw UnsupportedFileFormatVersion(current_file_format_version);
12✔
1233
            }
12✔
1234

1235
            if (begin_new_session) {
99,915✔
1236
                // Determine version (snapshot number) and check history
1237
                // compatibility
1238
                version_type version = 0;
74,019✔
1239
                int stored_hist_type = 0;
74,019✔
1240
                gf::get_version_and_history_info(alloc, top_ref, version, stored_hist_type,
74,019✔
1241
                                                 stored_hist_schema_version);
74,019✔
1242
                bool good_history_type = false;
74,019✔
1243
                switch (openers_hist_type) {
74,019✔
1244
                    case Replication::hist_None:
6,915✔
1245
                        good_history_type = (stored_hist_type == Replication::hist_None);
6,915✔
1246
                        if (!good_history_type)
6,915✔
1247
                            throw IncompatibleHistories(
6✔
1248
                                util::format("Realm file at path '%1' has history type '%2', but is being opened "
6✔
1249
                                             "with replication disabled.",
6✔
1250
                                             path, Replication::history_type_name(stored_hist_type)),
6✔
1251
                                path);
6✔
1252
                        break;
6,909✔
1253
                    case Replication::hist_OutOfRealm:
6,909✔
1254
                        REALM_ASSERT(false); // No longer in use
×
1255
                        break;
×
1256
                    case Replication::hist_InRealm:
35,208✔
1257
                        good_history_type = (stored_hist_type == Replication::hist_InRealm ||
35,208✔
1258
                                             stored_hist_type == Replication::hist_None);
35,208✔
1259
                        if (!good_history_type)
35,208✔
1260
                            throw IncompatibleHistories(
6✔
1261
                                util::format("Realm file at path '%1' has history type '%2', but is being opened in "
6✔
1262
                                             "local history mode.",
6✔
1263
                                             path, Replication::history_type_name(stored_hist_type)),
6✔
1264
                                path);
6✔
1265
                        break;
35,202✔
1266
                    case Replication::hist_SyncClient:
35,202✔
1267
                        good_history_type = ((stored_hist_type == Replication::hist_SyncClient) || (top_ref == 0));
30,159✔
1268
                        if (!good_history_type)
30,159✔
1269
                            throw IncompatibleHistories(
6✔
1270
                                util::format("Realm file at path '%1' has history type '%2', but is being opened in "
6✔
1271
                                             "synchronized history mode.",
6✔
1272
                                             path, Replication::history_type_name(stored_hist_type)),
6✔
1273
                                path);
6✔
1274
                        break;
30,153✔
1275
                    case Replication::hist_SyncServer:
30,153✔
1276
                        good_history_type = ((stored_hist_type == Replication::hist_SyncServer) || (top_ref == 0));
1,737✔
1277
                        if (!good_history_type)
1,737✔
1278
                            throw IncompatibleHistories(
×
1279
                                util::format("Realm file at path '%1' has history type '%2', but is being opened in "
×
1280
                                             "server history mode.",
×
1281
                                             path, Replication::history_type_name(stored_hist_type)),
×
1282
                                path);
×
1283
                        break;
1,737✔
1284
                }
74,019✔
1285

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

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

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

1332
                info->file_format_version = uint_fast8_t(target_file_format_version);
72,954✔
1333

1334
                // Initially there is a single version in the file
1335
                info->number_of_versions = 1;
72,954✔
1336

1337
                info->latest_version_number = version;
72,954✔
1338
                alloc.init_mapping_management(version);
72,954✔
1339

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

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

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

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

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

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

1401
            m_new_commit_available.set_shared_part(info->new_commit_available, lockfile_prefix, "new_commit",
98,838✔
1402
                                                   options.temp_dir);
98,838✔
1403
            m_pick_next_writer.set_shared_part(info->pick_next_writer, lockfile_prefix, "pick_writer",
98,838✔
1404
                                               options.temp_dir);
98,838✔
1405

1406
            // make our presence noted:
1407
            ++info->num_participants;
98,838✔
1408
            m_info = info;
98,838✔
1409

1410
            // Keep the mappings and file open:
1411
            m_version_manager = std::move(version_manager);
98,838✔
1412
            alloc_detach_guard.release();
98,838✔
1413
            fug_1.release(); // Do not unmap
98,838✔
1414
            fcg.release();   // Do not close
98,838✔
1415
        }
98,838✔
1416
        ulg.release(); // Do not release shared lock
×
1417
        break;
98,838✔
1418
    }
99,915✔
1419

1420
    if (m_logger) {
98,835✔
1421
        m_logger->log(util::Logger::Level::debug, "   Number of participants: %1", m_info->num_participants);
80,673✔
1422
        m_logger->log(util::Logger::Level::debug, "   Durability: %1", [&] {
80,673✔
1423
            switch (options.durability) {
80,673✔
1424
                case DBOptions::Durability::Full:
58,059✔
1425
                    return "Full";
58,059✔
1426
                case DBOptions::Durability::MemOnly:
22,614✔
1427
                    return "MemOnly";
22,614✔
1428
                case realm::DBOptions::Durability::Unsafe:
✔
1429
                    return "Unsafe";
×
1430
            }
80,673✔
1431
            return "";
×
1432
        }());
80,673✔
1433
        m_logger->log(util::Logger::Level::debug, "   EncryptionKey: %1", options.encryption_key ? "yes" : "no");
80,673✔
1434
        if (m_logger->would_log(util::Logger::Level::debug)) {
80,673✔
1435
            if (top_ref) {
49,539✔
1436
                Array top(alloc);
25,725✔
1437
                top.init_from_ref(top_ref);
25,725✔
1438
                auto file_size = Group::get_logical_file_size(top);
25,725✔
1439
                auto history_size = Group::get_history_size(top);
25,725✔
1440
                auto freee_space_size = Group::get_free_space_size(top);
25,725✔
1441
                m_logger->log(util::Logger::Level::debug, "   File size: %1", file_size);
25,725✔
1442
                m_logger->log(util::Logger::Level::debug, "   User data size: %1",
25,725✔
1443
                              file_size - (freee_space_size + history_size));
25,725✔
1444
                m_logger->log(util::Logger::Level::debug, "   Free space size: %1", freee_space_size);
25,725✔
1445
                m_logger->log(util::Logger::Level::debug, "   History size: %1", history_size);
25,725✔
1446
            }
25,725✔
1447
            else {
23,814✔
1448
                m_logger->log(util::Logger::Level::debug, "   Empty file");
23,814✔
1449
            }
23,814✔
1450
        }
49,539✔
1451
    }
80,673✔
1452

1453
    // Upgrade file format and/or history schema
1454
    try {
98,835✔
1455
        if (stored_hist_schema_version == -1) {
98,835✔
1456
            // current_hist_schema_version has not been read. Read it now
1457
            stored_hist_schema_version = start_read()->get_history_schema_version();
25,884✔
1458
        }
25,884✔
1459
        if (current_file_format_version == 0) {
98,835✔
1460
            // If the current file format is still undecided, no upgrade is
1461
            // necessary, but we still need to make the chosen file format
1462
            // visible to the rest of the core library by updating the value
1463
            // that will be subsequently returned by
1464
            // Group::get_file_format_version(). For this to work, all session
1465
            // participants must adopt the chosen target Realm file format when
1466
            // the stored file format version is zero regardless of the version
1467
            // of the core library used.
1468
            m_file_format_version = target_file_format_version;
43,890✔
1469
        }
43,890✔
1470
        else {
54,945✔
1471
            m_file_format_version = current_file_format_version;
54,945✔
1472
            upgrade_file_format(options.allow_file_format_upgrade, target_file_format_version,
54,945✔
1473
                                stored_hist_schema_version, openers_hist_schema_version); // Throws
54,945✔
1474
        }
54,945✔
1475
    }
98,835✔
1476
    catch (...) {
98,835✔
1477
        close();
6✔
1478
        throw;
6✔
1479
    }
6✔
1480
    m_alloc.set_read_only(true);
98,832✔
1481
}
98,832✔
1482

1483
void DB::open(BinaryData buffer, bool take_ownership)
1484
{
6✔
1485
    auto top_ref = m_alloc.attach_buffer(buffer.data(), buffer.size());
6✔
1486
    m_fake_read_lock_if_immutable = ReadLockInfo::make_fake(top_ref, buffer.size());
6✔
1487
    if (take_ownership)
6✔
1488
        m_alloc.own_buffer();
×
1489
}
6✔
1490

1491
void DB::open(Replication& repl, const std::string& file, const DBOptions& options)
1492
{
71,913✔
1493
    // Exception safety: Since open() is called from constructors, if it throws,
1494
    // it must leave the file closed.
1495

1496
    REALM_ASSERT(!is_attached());
71,913✔
1497

1498
    repl.initialize(*this); // Throws
71,913✔
1499

1500
    set_replication(&repl);
71,913✔
1501

1502
    open(file, options); // Throws
71,913✔
1503
}
71,913✔
1504

1505
class DBLogger : public Logger {
1506
public:
1507
    DBLogger(const std::shared_ptr<Logger>& base_logger, unsigned hash) noexcept
1508
        : Logger(LogCategory::storage, *base_logger)
52,659✔
1509
        , m_hash(hash)
52,659✔
1510
        , m_base_logger_ptr(base_logger)
52,659✔
1511
    {
106,365✔
1512
    }
106,365✔
1513

1514
protected:
1515
    void do_log(const LogCategory& category, Level level, const std::string& message) final
1516
    {
1,559,928✔
1517
        std::ostringstream ostr;
1,559,928✔
1518
        auto id = std::this_thread::get_id();
1,559,928✔
1519
        ostr << "DB: " << m_hash << " Thread " << id << ": " << message;
1,559,928✔
1520
        Logger::do_log(*m_base_logger_ptr, category, level, ostr.str());
1,559,928✔
1521
    }
1,559,928✔
1522

1523
private:
1524
    unsigned m_hash;
1525
    std::shared_ptr<Logger> m_base_logger_ptr;
1526
};
1527

1528
void DB::set_logger(const std::shared_ptr<util::Logger>& logger) noexcept
1529
{
124,689✔
1530
    if (logger)
124,689✔
1531
        m_logger = std::make_shared<DBLogger>(logger, m_log_id);
106,362✔
1532
}
124,689✔
1533

1534
void DB::open(Replication& repl, const DBOptions& options)
1535
{
25,494✔
1536
    REALM_ASSERT(!is_attached());
25,494✔
1537
    repl.initialize(*this); // Throws
25,494✔
1538
    set_replication(&repl);
25,494✔
1539

1540
    m_alloc.init_in_memory_buffer();
25,494✔
1541

1542
    set_logger(options.logger);
25,494✔
1543
    m_replication->set_logger(m_logger.get());
25,494✔
1544
    if (m_logger)
25,494✔
1545
        m_logger->detail("Open memory-only realm");
25,482✔
1546

1547
    auto hist_type = repl.get_history_type();
25,494✔
1548
    m_in_memory_info =
25,494✔
1549
        std::make_unique<SharedInfo>(DBOptions::Durability::MemOnly, hist_type, repl.get_history_schema_version());
25,494✔
1550
    SharedInfo* info = m_in_memory_info.get();
25,494✔
1551
    m_writemutex.set_shared_part(info->shared_writemutex, "", "write");
25,494✔
1552
    m_controlmutex.set_shared_part(info->shared_controlmutex, "", "control");
25,494✔
1553
    m_new_commit_available.set_shared_part(info->new_commit_available, "", "new_commit", options.temp_dir);
25,494✔
1554
    m_pick_next_writer.set_shared_part(info->pick_next_writer, "", "pick_writer", options.temp_dir);
25,494✔
1555
    m_versionlist_mutex.set_shared_part(info->shared_versionlist_mutex, "", "versions");
25,494✔
1556

1557
    auto target_file_format_version = uint_fast8_t(Group::get_target_file_format_version_for_session(0, hist_type));
25,494✔
1558
    info->file_format_version = target_file_format_version;
25,494✔
1559
    info->number_of_versions = 1;
25,494✔
1560
    info->latest_version_number = 1;
25,494✔
1561
    info->init_versioning(0, m_alloc.get_baseline(), 1);
25,494✔
1562
    ++info->num_participants;
25,494✔
1563

1564
    m_version_manager = std::make_unique<InMemoryVersionManager>(info, m_versionlist_mutex);
25,494✔
1565

1566
    m_file_format_version = target_file_format_version;
25,494✔
1567

1568
    m_info = info;
25,494✔
1569
    m_alloc.set_read_only(true);
25,494✔
1570
}
25,494✔
1571

1572
void DB::create_new_history(Replication& repl)
1573
{
36✔
1574
    Replication* old_repl = get_replication();
36✔
1575
    try {
36✔
1576
        repl.initialize(*this);
36✔
1577
        set_replication(&repl);
36✔
1578

1579
        auto tr = start_write();
36✔
1580
        tr->clear_history();
36✔
1581
        tr->replicate(tr.get(), repl);
36✔
1582
        tr->commit();
36✔
1583
    }
36✔
1584
    catch (...) {
36✔
1585
        set_replication(old_repl);
×
1586
        throw;
×
1587
    }
×
1588
}
36✔
1589

1590
void DB::create_new_history(std::unique_ptr<Replication> repl)
1591
{
36✔
1592
    create_new_history(*repl);
36✔
1593
    m_history = std::move(repl);
36✔
1594
}
36✔
1595

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

1600
// A note about lock ordering.
1601
// The local mutex, m_mutex, guards transaction start/stop and map/unmap of the lock file.
1602
// Except for compact(), open() and close(), it should only be held briefly.
1603
// The controlmutex guards operations which change the file size, session initialization
1604
// and session exit.
1605
// The writemutex guards the integrity of the (write) transaction data.
1606
// The controlmutex and writemutex resides in the .lock file and thus requires
1607
// the mapping of the .lock file to work. A straightforward approach would be to lock
1608
// the m_mutex whenever the other mutexes are taken or released...but that would be too
1609
// bad for performance of transaction start/stop.
1610
//
1611
// The locks are to be taken in this order: writemutex->controlmutex->m_mutex
1612
//
1613
// The .lock file is mapped during DB::create() and unmapped by a call to DB::close().
1614
// Once unmapped, it is never mapped again. Hence any observer with a valid DBRef may
1615
// only see the transition from mapped->unmapped, never the opposite.
1616
//
1617
// Trying to create a transaction if the .lock file is unmapped will result in an assert.
1618
// Unmapping (during close()) while transactions are live, is not considered an error. There
1619
// is a potential race between unmapping during close() and any operation carried out by a live
1620
// transaction. The user must ensure that this race never happens if she uses DB::close().
1621
bool DB::compact(bool bump_version_number, util::Optional<const char*> output_encryption_key)
1622
    NO_THREAD_SAFETY_ANALYSIS // this would work except for a known limitation: "No alias analysis" where clang cannot
1623
                              // tell that tr->db->m_mutex is the same thing as m_mutex
1624
{
150✔
1625
    REALM_ASSERT(!m_fake_read_lock_if_immutable);
150✔
1626
    std::string tmp_path = m_db_path + ".tmp_compaction_space";
150✔
1627

1628
    // To enter compact, the DB object must already have been attached to a file,
1629
    // since this happens in DB::create().
1630

1631
    // Verify that the lock file is still attached. There is no attempt to guard against
1632
    // a race between close() and compact().
1633
    if (is_attached() == false) {
150✔
1634
        throw Exception(ErrorCodes::IllegalOperation, m_db_path + ": compact must be done on an open/attached DB");
×
1635
    }
×
1636
    auto info = m_info;
150✔
1637
    Durability dura = Durability(info->durability);
150✔
1638
    const char* write_key = bool(output_encryption_key) ? *output_encryption_key : get_encryption_key();
150✔
1639
    {
150✔
1640
        std::unique_lock<InterprocessMutex> lock(m_controlmutex); // Throws
150✔
1641
        auto t1 = std::chrono::steady_clock::now();
150✔
1642

1643
        // We must be the ONLY DB object attached if we're to do compaction
1644
        if (info->num_participants > 1)
150✔
1645
            return false;
×
1646

1647
        // Holding the controlmutex prevents any other DB from attaching to the file.
1648

1649
        // Using start_read here ensures that we have access to the latest entry
1650
        // in the VersionList. We need to have access to that later to update top_ref and file_size.
1651
        // This is also needed to attach the group (get the proper top pointer, etc)
1652
        TransactionRef tr = start_read();
150✔
1653
        auto file_size_before = tr->get_logical_file_size();
150✔
1654

1655
        // local lock blocking any transaction from starting (and stopping)
1656
        CheckedLockGuard local_lock(m_mutex);
150✔
1657

1658
        // We should be the only transaction active - otherwise back out
1659
        if (m_transaction_count != 1)
150✔
1660
            return false;
6✔
1661

1662
        // group::write() will throw if the file already exists.
1663
        // To prevent this, we have to remove the file (should it exist)
1664
        // before calling group::write().
1665
        File::try_remove(tmp_path);
144✔
1666

1667
        // Compact by writing a new file holding only live data, then renaming the new file
1668
        // so it becomes the database file, replacing the old one in the process.
1669
        try {
144✔
1670
            File file;
144✔
1671
            file.open(tmp_path, File::access_ReadWrite, File::create_Must, 0);
144✔
1672
            int incr = bump_version_number ? 1 : 0;
144✔
1673
            Group::DefaultTableWriter writer;
144✔
1674
            tr->write(file, write_key, info->latest_version_number + incr, writer); // Throws
144✔
1675
            // Data needs to be flushed to the disk before renaming.
1676
            bool disable_sync = get_disable_sync_to_disk();
144✔
1677
            if (!disable_sync && dura != Durability::Unsafe)
144!
1678
                file.sync(); // Throws
×
1679
        }
144✔
1680
        catch (...) {
144✔
1681
            // If writing the compact version failed in any way, delete the partially written file to clean up disk
1682
            // space. This is so that we don't fail with 100% disk space used when compacting on a mostly full disk.
1683
            if (File::exists(tmp_path)) {
×
1684
                File::remove(tmp_path);
×
1685
            }
×
1686
            throw;
×
1687
        }
×
1688
        // if we've written a file with a bumped version number, we need to update the lock file to match.
1689
        if (bump_version_number) {
144✔
1690
            ++info->latest_version_number;
12✔
1691
        }
12✔
1692
        // We need to release any shared mapping *before* releasing the control mutex.
1693
        // When someone attaches to the new database file, they *must* *not* see and
1694
        // reuse any existing memory mapping of the stale file.
1695
        tr->close_read_with_lock();
144✔
1696
        m_alloc.detach();
144✔
1697

1698
        util::File::move(tmp_path, m_db_path);
144✔
1699

1700
        SlabAlloc::Config cfg;
144✔
1701
        cfg.session_initiator = true;
144✔
1702
        cfg.is_shared = true;
144✔
1703
        cfg.read_only = false;
144✔
1704
        cfg.skip_validate = false;
144✔
1705
        cfg.no_create = true;
144✔
1706
        cfg.clear_file = false;
144✔
1707
        cfg.encryption_key = write_key;
144✔
1708
        ref_type top_ref;
144✔
1709
        top_ref = m_alloc.attach_file(m_db_path, cfg, m_marker_observer.get());
144✔
1710
        m_alloc.convert_from_streaming_form(top_ref);
144✔
1711
        m_alloc.init_mapping_management(info->latest_version_number);
144✔
1712
        info->number_of_versions = 1;
144✔
1713
        size_t logical_file_size = sizeof(SlabAlloc::Header);
144✔
1714
        if (top_ref) {
144✔
1715
            Array top(m_alloc);
138✔
1716
            top.init_from_ref(top_ref);
138✔
1717
            logical_file_size = Group::get_logical_file_size(top);
138✔
1718
        }
138✔
1719
        m_version_manager->init_versioning(top_ref, logical_file_size, info->latest_version_number);
144✔
1720
        if (m_logger) {
144✔
1721
            auto t2 = std::chrono::steady_clock::now();
54✔
1722
            m_logger->log(util::Logger::Level::info, "DB compacted from: %1 to %2 in %3 us", file_size_before,
54✔
1723
                          logical_file_size, std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count());
54✔
1724
        }
54✔
1725
    }
144✔
1726
    return true;
×
1727
}
144✔
1728

1729
void DB::write_copy(StringData path, const char* output_encryption_key)
1730
{
246✔
1731
    auto tr = start_read();
246✔
1732
    if (auto hist = tr->get_history()) {
246✔
1733
        if (!hist->no_pending_local_changes(tr->get_version())) {
246✔
1734
            throw Exception(ErrorCodes::IllegalOperation,
6✔
1735
                            "All client changes must be integrated in server before writing copy");
6✔
1736
        }
6✔
1737
    }
246✔
1738

1739
    class NoClientFileIdWriter : public Group::DefaultTableWriter {
240✔
1740
    public:
240✔
1741
        NoClientFileIdWriter()
240✔
1742
            : Group::DefaultTableWriter(true)
240✔
1743
        {
240✔
1744
        }
240✔
1745
        HistoryInfo write_history(_impl::OutputStream& out) override
240✔
1746
        {
240✔
1747
            auto hist = Group::DefaultTableWriter::write_history(out);
234✔
1748
            hist.sync_file_id = 0;
234✔
1749
            return hist;
234✔
1750
        }
234✔
1751
    } writer;
240✔
1752

1753
    File file;
240✔
1754
    file.open(path, File::access_ReadWrite, File::create_Must, 0);
240✔
1755
    file.resize(0);
240✔
1756

1757
    auto t1 = std::chrono::steady_clock::now();
240✔
1758
    tr->write(file, output_encryption_key, m_info->latest_version_number, writer);
240✔
1759
    if (m_logger) {
240✔
1760
        auto t2 = std::chrono::steady_clock::now();
60✔
1761
        m_logger->log(util::Logger::Level::info, "DB written to '%1' in %2 us", path,
60✔
1762
                      std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count());
60✔
1763
    }
60✔
1764
}
240✔
1765

1766
uint_fast64_t DB::get_number_of_versions()
1767
{
292,137✔
1768
    if (m_fake_read_lock_if_immutable)
292,137✔
1769
        return 1;
6✔
1770
    return m_info->number_of_versions;
292,131✔
1771
}
292,137✔
1772

1773
size_t DB::get_allocated_size() const
1774
{
6✔
1775
    return m_alloc.get_allocated_size();
6✔
1776
}
6✔
1777

1778
void DB::release_all_read_locks() noexcept
1779
{
124,314✔
1780
    REALM_ASSERT(!m_fake_read_lock_if_immutable);
124,314✔
1781
    CheckedLockGuard local_lock(m_mutex); // mx on m_local_locks_held
124,314✔
1782
    for (auto& read_lock : m_local_locks_held) {
124,314✔
1783
        --m_transaction_count;
6✔
1784
        m_version_manager->release_read_lock(read_lock);
6✔
1785
    }
6✔
1786
    m_local_locks_held.clear();
124,314✔
1787
    REALM_ASSERT(m_transaction_count == 0);
124,314✔
1788
}
124,314✔
1789

1790
class DB::AsyncCommitHelper {
1791
public:
1792
    AsyncCommitHelper(DB* db)
1793
        : m_db(db)
40,584✔
1794
    {
82,221✔
1795
    }
82,221✔
1796
    ~AsyncCommitHelper()
1797
    {
82,203✔
1798
        {
82,203✔
1799
            std::unique_lock lg(m_mutex);
82,203✔
1800
            if (!m_running) {
82,203✔
1801
                return;
48,423✔
1802
            }
48,423✔
1803
            m_running = false;
33,780✔
1804
            m_cv_worker.notify_one();
33,780✔
1805
        }
33,780✔
1806
        m_thread.join();
×
1807
    }
33,780✔
1808

1809
    void begin_write(util::UniqueFunction<void()> fn)
1810
    {
1,614✔
1811
        std::unique_lock lg(m_mutex);
1,614✔
1812
        start_thread();
1,614✔
1813
        m_pending_writes.emplace_back(std::move(fn));
1,614✔
1814
        m_cv_worker.notify_one();
1,614✔
1815
    }
1,614✔
1816

1817
    void blocking_begin_write()
1818
    {
206,895✔
1819
        std::unique_lock lg(m_mutex);
206,895✔
1820

1821
        // If we support unlocking InterprocessMutex from a different thread
1822
        // than it was locked on, we can sometimes just begin the write on
1823
        // the current thread. This requires that no one is currently waiting
1824
        // for the worker thread to acquire the write lock, as we'll deadlock
1825
        // if we try to async commit while the worker is waiting for the lock.
1826
        bool can_lock_on_caller =
206,895✔
1827
            !InterprocessMutex::is_thread_confined && (!m_owns_write_mutex && m_pending_writes.empty() &&
206,898✔
1828
                                                       m_write_lock_claim_ticket == m_write_lock_claim_fulfilled);
105,054✔
1829

1830
        // If we support cross-thread unlocking and m_running is false,
1831
        // can_lock_on_caller should always be true or we forgot to launch the thread
1832
        REALM_ASSERT(can_lock_on_caller || m_running || InterprocessMutex::is_thread_confined);
206,895✔
1833

1834
        // If possible, just begin the write on the current thread
1835
        if (can_lock_on_caller) {
206,895✔
1836
            m_waiting_for_write_mutex = true;
104,991✔
1837
            lg.unlock();
104,991✔
1838
            m_db->do_begin_write();
104,991✔
1839
            lg.lock();
104,991✔
1840
            m_waiting_for_write_mutex = false;
104,991✔
1841
            m_has_write_mutex = true;
104,991✔
1842
            m_owns_write_mutex = false;
104,991✔
1843
            return;
104,991✔
1844
        }
104,991✔
1845

1846
        // Otherwise we have to ask the worker thread to acquire it and wait
1847
        // for that
1848
        start_thread();
101,904✔
1849
        size_t ticket = ++m_write_lock_claim_ticket;
101,904✔
1850
        m_cv_worker.notify_one();
101,904✔
1851
        m_cv_callers.wait(lg, [this, ticket] {
204,459✔
1852
            return ticket == m_write_lock_claim_fulfilled;
204,459✔
1853
        });
204,459✔
1854
    }
101,904✔
1855

1856
    void end_write()
1857
    {
54✔
1858
        std::unique_lock lg(m_mutex);
54✔
1859
        REALM_ASSERT(m_has_write_mutex);
54✔
1860
        REALM_ASSERT(m_owns_write_mutex || !InterprocessMutex::is_thread_confined);
54✔
1861

1862
        // If we acquired the write lock on the worker thread, also release it
1863
        // there even if our mutex supports unlocking cross-thread as it simplifies things.
1864
        if (m_owns_write_mutex) {
54✔
1865
            m_pending_mx_release = true;
51✔
1866
            m_cv_worker.notify_one();
51✔
1867
        }
51✔
1868
        else {
3✔
1869
            m_db->do_end_write();
3✔
1870
            m_has_write_mutex = false;
3✔
1871
        }
3✔
1872
    }
54✔
1873

1874
    bool blocking_end_write()
1875
    {
255,648✔
1876
        std::unique_lock lg(m_mutex);
255,648✔
1877
        if (!m_has_write_mutex) {
255,648✔
1878
            return false;
48,552✔
1879
        }
48,552✔
1880
        REALM_ASSERT(m_owns_write_mutex || !InterprocessMutex::is_thread_confined);
207,096✔
1881

1882
        // If we acquired the write lock on the worker thread, also release it
1883
        // there even if our mutex supports unlocking cross-thread as it simplifies things.
1884
        if (m_owns_write_mutex) {
207,096✔
1885
            m_pending_mx_release = true;
102,429✔
1886
            m_cv_worker.notify_one();
102,429✔
1887
            m_cv_callers.wait(lg, [this] {
204,858✔
1888
                return !m_pending_mx_release;
204,858✔
1889
            });
204,858✔
1890
        }
102,429✔
1891
        else {
104,667✔
1892
            m_db->do_end_write();
104,667✔
1893
            m_has_write_mutex = false;
104,667✔
1894

1895
            // The worker thread may have ignored a request for the write mutex
1896
            // while we were acquiring it, so we need to wake up the thread
1897
            if (has_pending_write_requests()) {
104,667✔
1898
                lg.unlock();
×
1899
                m_cv_worker.notify_one();
×
1900
            }
×
1901
        }
104,667✔
1902
        return true;
207,096✔
1903
    }
255,648✔
1904

1905

1906
    void sync_to_disk(util::UniqueFunction<void()> fn)
1907
    {
1,362✔
1908
        REALM_ASSERT(fn);
1,362✔
1909
        std::unique_lock lg(m_mutex);
1,362✔
1910
        REALM_ASSERT(!m_pending_sync);
1,362✔
1911
        start_thread();
1,362✔
1912
        m_pending_sync = std::move(fn);
1,362✔
1913
        m_cv_worker.notify_one();
1,362✔
1914
    }
1,362✔
1915

1916
private:
1917
    DB* m_db;
1918
    std::thread m_thread;
1919
    std::mutex m_mutex;
1920
    std::condition_variable m_cv_worker;
1921
    std::condition_variable m_cv_callers;
1922
    std::deque<util::UniqueFunction<void()>> m_pending_writes;
1923
    util::UniqueFunction<void()> m_pending_sync;
1924
    size_t m_write_lock_claim_ticket = 0;
1925
    size_t m_write_lock_claim_fulfilled = 0;
1926
    bool m_pending_mx_release = false;
1927
    bool m_running = false;
1928
    bool m_has_write_mutex = false;
1929
    bool m_owns_write_mutex = false;
1930
    bool m_waiting_for_write_mutex = false;
1931

1932
    void main();
1933

1934
    void start_thread()
1935
    {
104,883✔
1936
        if (m_running) {
104,883✔
1937
            return;
71,103✔
1938
        }
71,103✔
1939
        m_running = true;
33,780✔
1940
        m_thread = std::thread([this]() {
33,780✔
1941
            main();
33,780✔
1942
        });
33,780✔
1943
    }
33,780✔
1944

1945
    bool has_pending_write_requests()
1946
    {
304,503✔
1947
        return m_write_lock_claim_fulfilled < m_write_lock_claim_ticket || !m_pending_writes.empty();
304,503✔
1948
    }
304,503✔
1949
};
1950

1951
DB::~DB() noexcept
1952
{
124,680✔
1953
    close();
124,680✔
1954
}
124,680✔
1955

1956
// Note: close() and close_internal() may be called from the DB::~DB().
1957
// in that case, they will not throw. Throwing can only happen if called
1958
// directly.
1959
void DB::close(bool allow_open_read_transactions)
1960
{
125,652✔
1961
    // make helper thread(s) terminate
1962
    m_commit_helper.reset();
125,652✔
1963

1964
    if (m_fake_read_lock_if_immutable) {
125,652✔
1965
        if (!is_attached())
192✔
1966
            return;
×
1967
        {
192✔
1968
            CheckedLockGuard local_lock(m_mutex);
192✔
1969
            if (!allow_open_read_transactions && m_transaction_count)
192✔
1970
                throw WrongTransactionState("Closing with open read transactions");
×
1971
        }
192✔
1972
        if (m_alloc.is_attached())
192✔
1973
            m_alloc.detach();
192✔
1974
        m_fake_read_lock_if_immutable.reset();
192✔
1975
    }
192✔
1976
    else {
125,460✔
1977
        close_internal(std::unique_lock<InterprocessMutex>(m_controlmutex, std::defer_lock),
125,460✔
1978
                       allow_open_read_transactions);
125,460✔
1979
    }
125,460✔
1980
}
125,652✔
1981

1982
void DB::close_internal(std::unique_lock<InterprocessMutex> lock, bool allow_open_read_transactions)
1983
{
125,460✔
1984
    if (!is_attached())
125,460✔
1985
        return;
1,134✔
1986

1987
    {
124,326✔
1988
        CheckedLockGuard local_lock(m_mutex);
124,326✔
1989
        if (m_write_transaction_open)
124,326✔
1990
            throw WrongTransactionState("Closing with open write transactions");
6✔
1991
        if (!allow_open_read_transactions && m_transaction_count)
124,320✔
1992
            throw WrongTransactionState("Closing with open read transactions");
6✔
1993
    }
124,320✔
1994
    SharedInfo* info = m_info;
124,314✔
1995
    {
124,314✔
1996
        if (!lock.owns_lock())
124,314✔
1997
            lock.lock();
124,311✔
1998

1999
        if (m_alloc.is_attached())
124,314✔
2000
            m_alloc.detach();
124,314✔
2001

2002
        if (m_is_sync_agent) {
124,314✔
2003
            REALM_ASSERT(info->sync_agent_present);
1,557✔
2004
            info->sync_agent_present = 0; // Set to false
1,557✔
2005
        }
1,557✔
2006
        release_all_read_locks();
124,314✔
2007
        --info->num_participants;
124,314✔
2008
        bool end_of_session = info->num_participants == 0;
124,314✔
2009
        // std::cerr << "closing" << std::endl;
2010
        if (end_of_session) {
124,314✔
2011

2012
            // If the db file is just backing for a transient data structure,
2013
            // we can delete it when done.
2014
            if (Durability(info->durability) == Durability::MemOnly && !m_in_memory_info) {
98,412✔
2015
                try {
22,698✔
2016
                    util::File::remove(m_db_path.c_str());
22,698✔
2017
                }
22,698✔
2018
                catch (...) {
22,698✔
2019
                } // ignored on purpose.
12✔
2020
            }
22,698✔
2021
        }
98,412✔
2022
        lock.unlock();
124,314✔
2023
    }
124,314✔
2024
    {
124,314✔
2025
        CheckedLockGuard local_lock(m_mutex);
124,314✔
2026

2027
        m_new_commit_available.close();
124,314✔
2028
        m_pick_next_writer.close();
124,314✔
2029

2030
        if (m_in_memory_info) {
124,314✔
2031
            m_in_memory_info.reset();
25,494✔
2032
        }
25,494✔
2033
        else {
98,820✔
2034
            // On Windows it is important that we unmap before unlocking, else a SetEndOfFile() call from another
2035
            // thread may interleave which is not permitted on Windows. It is permitted on *nix.
2036
            m_file_map.unmap();
98,820✔
2037
            m_version_manager.reset();
98,820✔
2038
            m_file.rw_unlock();
98,820✔
2039
            // info->~SharedInfo(); // DO NOT Call destructor
2040
            m_file.close();
98,820✔
2041
        }
98,820✔
2042
        m_info = nullptr;
124,314✔
2043
        if (m_logger)
124,314✔
2044
            m_logger->log(util::Logger::Level::detail, "DB closed");
106,122✔
2045
    }
124,314✔
2046
}
124,314✔
2047

2048
bool DB::other_writers_waiting_for_lock() const
2049
{
65,022✔
2050
    SharedInfo* info = m_info;
65,022✔
2051

2052
    uint32_t next_ticket = info->next_ticket.load(std::memory_order_relaxed);
65,022✔
2053
    uint32_t next_served = info->next_served.load(std::memory_order_relaxed);
65,022✔
2054
    // When holding the write lock, next_ticket = next_served + 1, hence, if the diference between 'next_ticket' and
2055
    // 'next_served' is greater than 1, there is at least one thread waiting to acquire the write lock.
2056
    return next_ticket > next_served + 1;
65,022✔
2057
}
65,022✔
2058

2059
void DB::AsyncCommitHelper::main()
2060
{
33,780✔
2061
    std::unique_lock lg(m_mutex);
33,780✔
2062
    while (m_running) {
448,410✔
2063
#if 0 // Enable for testing purposes
2064
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
2065
#endif
2066
        if (m_has_write_mutex) {
414,630✔
2067
            if (auto cb = std::move(m_pending_sync)) {
214,791✔
2068
                // Only one of sync_to_disk(), end_write(), or blocking_end_write()
2069
                // should be called, so we should never have both a pending sync
2070
                // and pending release.
2071
                REALM_ASSERT(!m_pending_mx_release);
1,362✔
2072
                lg.unlock();
1,362✔
2073
                cb();
1,362✔
2074
                cb = nullptr; // Release things captured by the callback before reacquiring the lock
1,362✔
2075
                lg.lock();
1,362✔
2076
                m_pending_mx_release = true;
1,362✔
2077
            }
1,362✔
2078
            if (m_pending_mx_release) {
214,791✔
2079
                REALM_ASSERT(!InterprocessMutex::is_thread_confined || m_owns_write_mutex);
103,842✔
2080
                m_db->do_end_write();
103,842✔
2081
                m_pending_mx_release = false;
103,842✔
2082
                m_has_write_mutex = false;
103,842✔
2083
                m_owns_write_mutex = false;
103,842✔
2084

2085
                lg.unlock();
103,842✔
2086
                m_cv_callers.notify_all();
103,842✔
2087
                lg.lock();
103,842✔
2088
                continue;
103,842✔
2089
            }
103,842✔
2090
        }
214,791✔
2091
        else {
199,839✔
2092
            REALM_ASSERT(!m_pending_sync && !m_pending_mx_release);
199,839✔
2093

2094
            // Acquire the write lock if anyone has requested it, but only if
2095
            // another thread is not already waiting for it. If there's another
2096
            // thread requesting and they get it while we're waiting, we'll
2097
            // deadlock if they ask us to perform the sync.
2098
            if (!m_waiting_for_write_mutex && has_pending_write_requests()) {
199,839✔
2099
                lg.unlock();
103,521✔
2100
                m_db->do_begin_write();
103,521✔
2101
                lg.lock();
103,521✔
2102

2103
                REALM_ASSERT(!m_has_write_mutex);
103,521✔
2104
                m_has_write_mutex = true;
103,521✔
2105
                m_owns_write_mutex = true;
103,521✔
2106

2107
                // Synchronous transaction requests get priority over async
2108
                if (m_write_lock_claim_fulfilled < m_write_lock_claim_ticket) {
103,521✔
2109
                    ++m_write_lock_claim_fulfilled;
101,907✔
2110
                    m_cv_callers.notify_all();
101,907✔
2111
                    continue;
101,907✔
2112
                }
101,907✔
2113

2114
                REALM_ASSERT(!m_pending_writes.empty());
1,614✔
2115
                auto callback = std::move(m_pending_writes.front());
1,614✔
2116
                m_pending_writes.pop_front();
1,614✔
2117
                lg.unlock();
1,614✔
2118
                callback();
1,614✔
2119
                // Release things captured by the callback before reacquiring the lock
2120
                callback = nullptr;
1,614✔
2121
                lg.lock();
1,614✔
2122
                continue;
1,614✔
2123
            }
103,521✔
2124
        }
199,839✔
2125
        m_cv_worker.wait(lg);
207,267✔
2126
    }
207,267✔
2127
    if (m_has_write_mutex && m_owns_write_mutex) {
33,780!
2128
        m_db->do_end_write();
×
2129
    }
×
2130
}
33,780✔
2131

2132
void DB::async_begin_write(util::UniqueFunction<void()> fn)
2133
{
1,614✔
2134
    REALM_ASSERT(m_commit_helper);
1,614✔
2135
    m_commit_helper->begin_write(std::move(fn));
1,614✔
2136
}
1,614✔
2137

2138
void DB::async_end_write()
2139
{
54✔
2140
    REALM_ASSERT(m_commit_helper);
54✔
2141
    m_commit_helper->end_write();
54✔
2142
}
54✔
2143

2144
void DB::async_sync_to_disk(util::UniqueFunction<void()> fn)
2145
{
1,362✔
2146
    REALM_ASSERT(m_commit_helper);
1,362✔
2147
    m_commit_helper->sync_to_disk(std::move(fn));
1,362✔
2148
}
1,362✔
2149

2150
bool DB::has_changed(TransactionRef& tr)
2151
{
40,367,016✔
2152
    if (m_fake_read_lock_if_immutable)
40,367,016✔
2153
        return false; // immutable doesn't change
×
2154
    bool changed = tr->m_read_lock.m_version != get_version_of_latest_snapshot();
40,367,016✔
2155
    return changed;
40,367,016✔
2156
}
40,367,016✔
2157

2158
bool DB::wait_for_change(TransactionRef& tr)
2159
{
×
2160
    REALM_ASSERT(!m_fake_read_lock_if_immutable);
×
2161
    std::lock_guard<InterprocessMutex> lock(m_controlmutex);
×
2162
    while (tr->m_read_lock.m_version == m_info->latest_version_number && m_wait_for_change_enabled) {
×
2163
        m_new_commit_available.wait(m_controlmutex, 0);
×
2164
    }
×
2165
    return tr->m_read_lock.m_version != m_info->latest_version_number;
×
2166
}
×
2167

2168

2169
void DB::wait_for_change_release()
2170
{
×
2171
    if (m_fake_read_lock_if_immutable)
×
2172
        return;
×
2173
    std::lock_guard<InterprocessMutex> lock(m_controlmutex);
×
2174
    m_wait_for_change_enabled = false;
×
2175
    m_new_commit_available.notify_all();
×
2176
}
×
2177

2178

2179
void DB::enable_wait_for_change()
2180
{
×
2181
    REALM_ASSERT(!m_fake_read_lock_if_immutable);
×
2182
    std::lock_guard<InterprocessMutex> lock(m_controlmutex);
×
2183
    m_wait_for_change_enabled = true;
×
2184
}
×
2185

2186
bool DB::needs_file_format_upgrade(const std::string& file, const std::vector<char>& encryption_key)
2187
{
54✔
2188
    SlabAlloc alloc;
54✔
2189
    SlabAlloc::Config cfg;
54✔
2190
    cfg.session_initiator = false;
54✔
2191
    cfg.read_only = true;
54✔
2192
    cfg.no_create = true;
54✔
2193
    if (!encryption_key.empty()) {
54✔
2194
        cfg.encryption_key = encryption_key.data();
×
2195
    }
×
2196
    try {
54✔
2197
        alloc.attach_file(file, cfg);
54✔
2198
        if (auto current_file_format_version = alloc.get_committed_file_format_version()) {
54✔
2199
            auto target_file_format_version = Group::g_current_file_format_version;
42✔
2200
            return current_file_format_version < target_file_format_version;
42✔
2201
        }
42✔
2202
    }
54✔
2203
    catch (const FileAccessError& err) {
54✔
2204
        if (err.code() != ErrorCodes::FileNotFound) {
6✔
2205
            throw;
×
2206
        }
×
2207
    }
6✔
2208
    return false;
12✔
2209
}
54✔
2210

2211
void DB::upgrade_file_format(bool allow_file_format_upgrade, int target_file_format_version,
2212
                             int current_hist_schema_version, int target_hist_schema_version)
2213
{
54,948✔
2214
    // In a multithreaded scenario multiple threads may initially see a need to
2215
    // upgrade (maybe_upgrade == true) even though one onw thread is supposed to
2216
    // perform the upgrade, but that is ok, because the condition is rechecked
2217
    // in a fully reliable way inside a transaction.
2218

2219
    // First a non-threadsafe but fast check
2220
    int current_file_format_version = m_file_format_version;
54,948✔
2221
    REALM_ASSERT(current_file_format_version <= target_file_format_version);
54,948✔
2222
    REALM_ASSERT(current_hist_schema_version <= target_hist_schema_version);
54,948✔
2223
    bool maybe_upgrade_file_format = (current_file_format_version < target_file_format_version);
54,948✔
2224
    bool maybe_upgrade_hist_schema = (current_hist_schema_version < target_hist_schema_version);
54,948✔
2225
    bool maybe_upgrade = maybe_upgrade_file_format || maybe_upgrade_hist_schema;
54,948✔
2226
    if (maybe_upgrade) {
54,948✔
2227

2228
#ifdef REALM_DEBUG
828✔
2229
// This sleep() only exists in order to increase the quality of the
2230
// TEST(Upgrade_Database_2_3_Writes_New_File_Format_new) unit test.
2231
// The unit test creates multiple threads that all call
2232
// upgrade_file_format() simultaneously. This sleep() then acts like
2233
// a simple thread barrier that makes sure the threads meet here, to
2234
// increase the likelyhood of detecting any potential race problems.
2235
// See the unit test for details.
2236
//
2237
// NOTE: This sleep has been disabled because no problems have been found with
2238
// this code in a long while, and it was dramatically slowing down a unit test
2239
// in realm-sync.
2240

2241
// millisleep(200);
2242
#endif
828✔
2243

2244
        // WriteTransaction wt(*this);
2245
        auto wt = start_write();
828✔
2246
        bool dirty = false;
828✔
2247

2248
        // We need to upgrade history first. We may need to access it during migration
2249
        // when processing the !OID columns
2250
        int current_hist_schema_version_2 = wt->get_history_schema_version();
828✔
2251
        // The history must either still be using its initial schema or have
2252
        // been upgraded already to the chosen target schema version via a
2253
        // concurrent DB object.
2254
        REALM_ASSERT(current_hist_schema_version_2 == current_hist_schema_version ||
828✔
2255
                     current_hist_schema_version_2 == target_hist_schema_version);
828✔
2256
        bool need_hist_schema_upgrade = (current_hist_schema_version_2 < target_hist_schema_version);
828✔
2257
        if (need_hist_schema_upgrade) {
828✔
2258
            if (!allow_file_format_upgrade)
744✔
2259
                throw FileFormatUpgradeRequired(this->m_db_path);
×
2260

2261
            Replication* repl = get_replication();
744✔
2262
            repl->upgrade_history_schema(current_hist_schema_version_2); // Throws
744✔
2263
            wt->set_history_schema_version(target_hist_schema_version);  // Throws
744✔
2264
            dirty = true;
744✔
2265
        }
744✔
2266

2267
        // File format upgrade
2268
        int current_file_format_version_2 = m_alloc.get_committed_file_format_version();
828✔
2269
        // The file must either still be using its initial file_format or have
2270
        // been upgraded already to the chosen target file format via a
2271
        // concurrent DB object.
2272
        REALM_ASSERT(current_file_format_version_2 == current_file_format_version ||
828✔
2273
                     current_file_format_version_2 == target_file_format_version);
828✔
2274
        bool need_file_format_upgrade = (current_file_format_version_2 < target_file_format_version);
828✔
2275
        if (need_file_format_upgrade) {
828✔
2276
            if (!allow_file_format_upgrade)
156✔
2277
                throw FileFormatUpgradeRequired(this->m_db_path);
×
2278
            wt->upgrade_file_format(target_file_format_version); // Throws
156✔
2279
            // Note: The file format version stored in the Realm file will be
2280
            // updated to the new file format version as part of the following
2281
            // commit operation. This happens in GroupWriter::commit().
2282
            if (m_upgrade_callback)
156✔
2283
                m_upgrade_callback(current_file_format_version_2, target_file_format_version); // Throws
18✔
2284
            dirty = true;
156✔
2285
        }
156✔
2286
        wt->set_file_format_version(target_file_format_version);
828✔
2287
        m_file_format_version = target_file_format_version;
828✔
2288

2289
        if (dirty)
828✔
2290
            wt->commit(); // Throws
822✔
2291
    }
828✔
2292
}
54,948✔
2293

2294
void DB::release_read_lock(ReadLockInfo& read_lock) noexcept
2295
{
4,329,000✔
2296
    // ignore if opened with immutable file (then we have no lockfile)
2297
    if (m_fake_read_lock_if_immutable)
4,329,000✔
2298
        return;
384✔
2299
    CheckedLockGuard lock(m_mutex); // mx on m_local_locks_held
4,328,616✔
2300
    do_release_read_lock(read_lock);
4,328,616✔
2301
}
4,328,616✔
2302

2303
// this is called with m_mutex locked
2304
void DB::do_release_read_lock(ReadLockInfo& read_lock) noexcept
2305
{
4,333,290✔
2306
    REALM_ASSERT(!m_fake_read_lock_if_immutable);
4,333,290✔
2307
    bool found_match = false;
4,333,290✔
2308
    // simple linear search and move-last-over if a match is found.
2309
    // common case should have only a modest number of transactions in play..
2310
    for (size_t j = 0; j < m_local_locks_held.size(); ++j) {
8,866,737✔
2311
        if (m_local_locks_held[j].m_version == read_lock.m_version) {
8,866,581✔
2312
            m_local_locks_held[j] = m_local_locks_held.back();
4,333,134✔
2313
            m_local_locks_held.pop_back();
4,333,134✔
2314
            found_match = true;
4,333,134✔
2315
            break;
4,333,134✔
2316
        }
4,333,134✔
2317
    }
8,866,581✔
2318
    if (!found_match) {
4,333,290✔
2319
        REALM_ASSERT(!is_attached());
6✔
2320
        // it's OK, someone called close() and all locks where released
2321
        return;
6✔
2322
    }
6✔
2323
    --m_transaction_count;
4,333,284✔
2324
    m_version_manager->release_read_lock(read_lock);
4,333,284✔
2325
}
4,333,284✔
2326

2327

2328
DB::ReadLockInfo DB::grab_read_lock(ReadLockInfo::Type type, VersionID version_id)
2329
{
4,309,074✔
2330
    CheckedLockGuard lock(m_mutex); // mx on m_local_locks_held
4,309,074✔
2331
    REALM_ASSERT_RELEASE(is_attached());
4,309,074✔
2332
    auto read_lock = m_version_manager->grab_read_lock(type, version_id);
4,309,074✔
2333

2334
    m_local_locks_held.emplace_back(read_lock);
4,309,074✔
2335
    ++m_transaction_count;
4,309,074✔
2336
    REALM_ASSERT(read_lock.m_file_size > read_lock.m_top_ref);
4,309,074✔
2337
    return read_lock;
4,309,074✔
2338
}
4,309,074✔
2339

2340
void DB::leak_read_lock(ReadLockInfo& read_lock) noexcept
2341
{
6✔
2342
    CheckedLockGuard lock(m_mutex); // mx on m_local_locks_held
6✔
2343
    // simple linear search and move-last-over if a match is found.
2344
    // common case should have only a modest number of transactions in play..
2345
    for (size_t j = 0; j < m_local_locks_held.size(); ++j) {
6✔
2346
        if (m_local_locks_held[j].m_version == read_lock.m_version) {
6✔
2347
            m_local_locks_held[j] = m_local_locks_held.back();
6✔
2348
            m_local_locks_held.pop_back();
6✔
2349
            --m_transaction_count;
6✔
2350
            return;
6✔
2351
        }
6✔
2352
    }
6✔
2353
}
6✔
2354

2355
bool DB::do_try_begin_write()
2356
{
84✔
2357
    // In the non-blocking case, we will only succeed if there is no contention for
2358
    // the write mutex. For this case we are trivially fair and can ignore the
2359
    // fairness machinery.
2360
    bool got_the_lock = m_writemutex.try_lock();
84✔
2361
    if (got_the_lock) {
84✔
2362
        finish_begin_write();
72✔
2363
    }
72✔
2364
    return got_the_lock;
84✔
2365
}
84✔
2366

2367
void DB::do_begin_write()
2368
{
618,159✔
2369
    if (m_logger) {
618,159✔
2370
        m_logger->log(util::LogCategory::transaction, util::Logger::Level::trace, "acquire writemutex");
257,364✔
2371
    }
257,364✔
2372

2373
    SharedInfo* info = m_info;
618,159✔
2374

2375
    // Get write lock - the write lock is held until do_end_write().
2376
    //
2377
    // We use a ticketing scheme to ensure fairness wrt performing write transactions.
2378
    // (But cannot do that on Windows until we have interprocess condition variables there)
2379
    uint32_t my_ticket = info->next_ticket.fetch_add(1, std::memory_order_relaxed);
618,159✔
2380
    m_writemutex.lock(); // Throws
618,159✔
2381

2382
    // allow for comparison even after wrap around of ticket numbering:
2383
    int32_t diff = int32_t(my_ticket - info->next_served.load(std::memory_order_relaxed));
618,159✔
2384
    bool should_yield = diff > 0; // ticket is in the future
618,159✔
2385
    // a) the above comparison is only guaranteed to be correct, if the distance
2386
    //    between my_ticket and info->next_served is less than 2^30. This will
2387
    //    be the case since the distance will be bounded by the number of threads
2388
    //    and each thread cannot ever hold more than one ticket.
2389
    // b) we could use 64 bit counters instead, but it is unclear if all platforms
2390
    //    have support for interprocess atomics for 64 bit values.
2391

2392
    timespec time_limit; // only compute the time limit if we're going to use it:
618,159✔
2393
    if (should_yield) {
618,159✔
2394
        // This clock is not monotonic, so time can move backwards. This can lead
2395
        // to a wrong time limit, but the only effect of a wrong time limit is that
2396
        // we momentarily lose fairness, so we accept it.
2397
        timeval tv;
27,708✔
2398
        gettimeofday(&tv, nullptr);
27,708✔
2399
        time_limit.tv_sec = tv.tv_sec;
27,708✔
2400
        time_limit.tv_nsec = tv.tv_usec * 1000;
27,708✔
2401
        time_limit.tv_nsec += 500000000;        // 500 msec wait
27,708✔
2402
        if (time_limit.tv_nsec >= 1000000000) { // overflow
27,708✔
2403
            time_limit.tv_nsec -= 1000000000;
14,397✔
2404
            time_limit.tv_sec += 1;
14,397✔
2405
        }
14,397✔
2406
    }
27,708✔
2407

2408
    while (should_yield) {
753,720✔
2409

2410
        m_pick_next_writer.wait(m_writemutex, &time_limit);
135,828✔
2411
        timeval tv;
135,828✔
2412
        gettimeofday(&tv, nullptr);
135,828✔
2413
        if (time_limit.tv_sec < tv.tv_sec ||
135,828✔
2414
            (time_limit.tv_sec == tv.tv_sec && time_limit.tv_nsec < tv.tv_usec * 1000)) {
135,828✔
2415
            // Timeout!
2416
            break;
267✔
2417
        }
267✔
2418
        diff = int32_t(my_ticket - info->next_served);
135,561✔
2419
        should_yield = diff > 0; // ticket is in the future, so yield to someone else
135,561✔
2420
    }
135,561✔
2421

2422
    // we may get here because a) it's our turn, b) we timed out
2423
    // we don't distinguish, satisfied that event b) should be rare.
2424
    // In case b), we have to *make* it our turn. Failure to do so could leave us
2425
    // with 'next_served' permanently trailing 'next_ticket'.
2426
    //
2427
    // In doing so, we may bypass other waiters, hence the condition for yielding
2428
    // should take this situation into account by comparing with '>' instead of '!='
2429
    info->next_served = my_ticket;
618,159✔
2430
    finish_begin_write();
618,159✔
2431
    if (m_logger) {
618,159✔
2432
        m_logger->log(util::LogCategory::transaction, util::Logger::Level::trace, "writemutex acquired");
257,364✔
2433
    }
257,364✔
2434
}
618,159✔
2435

2436
void DB::finish_begin_write()
2437
{
618,231✔
2438
    if (m_info->commit_in_critical_phase) {
618,231✔
2439
        m_writemutex.unlock();
×
2440
        throw RuntimeError(ErrorCodes::BrokenInvariant, "Crash of other process detected, session restart required");
×
2441
    }
×
2442

2443

2444
    {
618,231✔
2445
        CheckedLockGuard local_lock(m_mutex);
618,231✔
2446
        m_write_transaction_open = true;
618,231✔
2447
    }
618,231✔
2448
    m_alloc.set_read_only(false);
618,231✔
2449
}
618,231✔
2450

2451
void DB::do_end_write() noexcept
2452
{
618,246✔
2453
    m_info->next_served.fetch_add(1, std::memory_order_relaxed);
618,246✔
2454

2455
    CheckedLockGuard local_lock(m_mutex);
618,246✔
2456
    REALM_ASSERT(m_write_transaction_open);
618,246✔
2457
    m_alloc.set_read_only(true);
618,246✔
2458
    m_write_transaction_open = false;
618,246✔
2459
    m_pick_next_writer.notify_all();
618,246✔
2460
    m_writemutex.unlock();
618,246✔
2461
    if (m_logger) {
618,246✔
2462
        m_logger->log(util::LogCategory::transaction, util::Logger::Level::trace, "writemutex released");
257,412✔
2463
    }
257,412✔
2464
}
618,246✔
2465

2466

2467
Replication::version_type DB::do_commit(Transaction& transaction, bool commit_to_disk)
2468
{
623,313✔
2469
    version_type current_version;
623,313✔
2470
    {
623,313✔
2471
        current_version = m_version_manager->get_newest_version();
623,313✔
2472
    }
623,313✔
2473
    version_type new_version = current_version + 1;
623,313✔
2474

2475
    if (!transaction.m_tables_to_clear.empty()) {
623,313✔
2476
        for (auto table_key : transaction.m_tables_to_clear) {
678✔
2477
            transaction.get_table_unchecked(table_key)->clear();
678✔
2478
        }
678✔
2479
        transaction.m_tables_to_clear.clear();
678✔
2480
    }
678✔
2481
    if (Replication* repl = get_replication()) {
623,313✔
2482
        // If Replication::prepare_commit() fails, then the entire transaction
2483
        // fails. The application then has the option of terminating the
2484
        // transaction with a call to Transaction::Rollback(), which in turn
2485
        // must call Replication::abort_transact().
2486
        new_version = repl->prepare_commit(current_version);        // Throws
598,851✔
2487
        low_level_commit(new_version, transaction, commit_to_disk); // Throws
598,851✔
2488
        repl->finalize_commit();
598,851✔
2489
    }
598,851✔
2490
    else {
24,462✔
2491
        low_level_commit(new_version, transaction); // Throws
24,462✔
2492
    }
24,462✔
2493

2494
    {
623,313✔
2495
        std::lock_guard lock(m_commit_listener_mutex);
623,313✔
2496
        for (auto listener : m_commit_listeners) {
623,313✔
2497
            listener->on_commit(new_version);
403,212✔
2498
        }
403,212✔
2499
    }
623,313✔
2500

2501
    return new_version;
623,313✔
2502
}
623,313✔
2503

2504
VersionID DB::get_version_id_of_latest_snapshot()
2505
{
40,530,099✔
2506
    if (m_fake_read_lock_if_immutable)
40,530,099✔
2507
        return {m_fake_read_lock_if_immutable->m_version, 0};
12✔
2508
    return m_version_manager->get_version_id_of_latest_snapshot();
40,530,087✔
2509
}
40,530,099✔
2510

2511

2512
DB::version_type DB::get_version_of_latest_snapshot()
2513
{
40,529,343✔
2514
    return get_version_id_of_latest_snapshot().version;
40,529,343✔
2515
}
40,529,343✔
2516

2517

2518
void DB::low_level_commit(uint_fast64_t new_version, Transaction& transaction, bool commit_to_disk)
2519
{
623,310✔
2520
    SharedInfo* info = m_info;
623,310✔
2521

2522
    // Version of oldest snapshot currently (or recently) bound in a transaction
2523
    // of the current session.
2524
    uint64_t oldest_version = 0, oldest_live_version = 0;
623,310✔
2525
    TopRefMap top_refs;
623,310✔
2526
    bool any_new_unreachables;
623,310✔
2527
    {
623,310✔
2528
        CheckedLockGuard lock(m_mutex);
623,310✔
2529
        m_version_manager->cleanup_versions(oldest_live_version, top_refs, any_new_unreachables);
623,310✔
2530
        oldest_version = top_refs.begin()->first;
623,310✔
2531
        // Allow for trimming of the history. Some types of histories do not
2532
        // need store changesets prior to the oldest *live* bound snapshot.
2533
        if (auto hist = transaction.get_history()) {
623,310✔
2534
            hist->set_oldest_bound_version(oldest_live_version); // Throws
598,809✔
2535
        }
598,809✔
2536
        // Cleanup any stale mappings
2537
        m_alloc.purge_old_mappings(oldest_version, new_version);
623,310✔
2538
    }
623,310✔
2539
    // save number of live versions for later:
2540
    // (top_refs is std::moved into GroupWriter so we'll loose it in the call to set_versions below)
2541
    auto live_versions = top_refs.size();
623,310✔
2542
    // Do the actual commit
2543
    REALM_ASSERT(oldest_version <= new_version);
623,310✔
2544

2545
    GroupWriter out(transaction, Durability(info->durability), m_marker_observer.get()); // Throws
623,310✔
2546
    out.set_versions(new_version, top_refs, any_new_unreachables);
623,310✔
2547
    out.prepare_evacuation();
623,310✔
2548
    auto t1 = std::chrono::steady_clock::now();
623,310✔
2549
    auto commit_size = m_alloc.get_commit_size();
623,310✔
2550
    if (m_logger) {
623,310✔
2551
        m_logger->log(util::LogCategory::transaction, util::Logger::Level::debug, "Initiate commit version: %1",
263,736✔
2552
                      new_version);
263,736✔
2553
    }
263,736✔
2554
    if (auto limit = out.get_evacuation_limit()) {
623,310✔
2555
        // Get a work limit based on the size of the transaction we're about to commit
2556
        // Add 4k to ensure progress on small commits
2557
        size_t work_limit = commit_size / 2 + out.get_free_list_size() + 0x1000;
5,325✔
2558
        transaction.cow_outliers(out.get_evacuation_progress(), limit, work_limit);
5,325✔
2559
    }
5,325✔
2560

2561
    ref_type new_top_ref;
623,310✔
2562
    // Recursively write all changed arrays to end of file
2563
    {
623,310✔
2564
        // protect against race with any other DB trying to attach to the file
2565
        std::lock_guard<InterprocessMutex> lock(m_controlmutex); // Throws
623,310✔
2566
        new_top_ref = out.write_group();                         // Throws
623,310✔
2567
    }
623,310✔
2568
    {
623,310✔
2569
        // protect access to shared variables and m_reader_mapping from here
2570
        CheckedLockGuard lock_guard(m_mutex);
623,310✔
2571
        m_free_space = out.get_free_space_size();
623,310✔
2572
        m_locked_space = out.get_locked_space_size();
623,310✔
2573
        m_used_space = out.get_logical_size() - m_free_space;
623,310✔
2574
        m_evac_stage.store(EvacStage(out.get_evacuation_stage()));
623,310✔
2575
        out.sync_according_to_durability();
623,310✔
2576
        if (Durability(info->durability) == Durability::Full || Durability(info->durability) == Durability::Unsafe) {
623,310✔
2577
            if (commit_to_disk) {
422,079✔
2578
                GroupCommitter cm(transaction, Durability(info->durability), m_marker_observer.get());
414,546✔
2579
                cm.commit(new_top_ref);
414,546✔
2580
            }
414,546✔
2581
        }
422,079✔
2582
        size_t new_file_size = out.get_logical_size();
623,310✔
2583
        // We must reset the allocators free space tracking before communicating the new
2584
        // version through the ring buffer. If not, a reader may start updating the allocators
2585
        // mappings while the allocator is in dirty state.
2586
        reset_free_space_tracking();
623,310✔
2587
        // Add the new version. If this fails in any way, the VersionList may be corrupted.
2588
        // This can lead to readers seing invalid data which is likely to cause them
2589
        // to crash. Other writers *must* be prevented from writing any further updates
2590
        // to the database. The flag "commit_in_critical_phase" is used to prevent such updates.
2591
        info->commit_in_critical_phase = 1;
623,310✔
2592
        {
623,310✔
2593
            m_version_manager->add_version(new_top_ref, new_file_size, new_version);
623,310✔
2594

2595
            // REALM_ASSERT(m_alloc.matches_section_boundary(new_file_size));
2596
            REALM_ASSERT(new_top_ref < new_file_size);
623,310✔
2597
        }
623,310✔
2598
        // At this point, the VersionList has been succesfully updated, and the next writer
2599
        // can safely proceed once the writemutex has been lifted.
2600
        info->commit_in_critical_phase = 0;
623,310✔
2601
    }
623,310✔
2602
    {
623,310✔
2603
        // protect against concurrent updates to the .lock file.
2604
        // must release m_mutex before this point to obey lock order
2605
        std::lock_guard<InterprocessMutex> lock(m_controlmutex);
623,310✔
2606

2607
        info->number_of_versions = live_versions + 1;
623,310✔
2608
        info->latest_version_number = new_version;
623,310✔
2609

2610
        m_new_commit_available.notify_all();
623,310✔
2611
    }
623,310✔
2612
    auto t2 = std::chrono::steady_clock::now();
623,310✔
2613
    if (m_logger) {
623,310✔
2614
        std::string to_disk_str = commit_to_disk ? util::format(" ref %1", new_top_ref) : " (no commit to disk)";
263,736✔
2615
        m_logger->log(util::LogCategory::transaction, util::Logger::Level::debug, "Commit of size %1 done in %2 us%3",
263,736✔
2616
                      commit_size, std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count(),
263,736✔
2617
                      to_disk_str);
263,736✔
2618
    }
263,736✔
2619
}
623,310✔
2620

2621
#ifdef REALM_DEBUG
2622
void DB::reserve(size_t size)
2623
{
36✔
2624
    REALM_ASSERT(is_attached());
36✔
2625
    m_alloc.reserve_disk_space(size); // Throws
36✔
2626
}
36✔
2627
#endif
2628

2629
bool DB::call_with_lock(const std::string& realm_path, CallbackWithLock&& callback)
2630
{
189✔
2631
    auto lockfile_path = get_core_file(realm_path, CoreFileType::Lock);
189✔
2632

2633
    File lockfile;
189✔
2634
    lockfile.open(lockfile_path, File::access_ReadWrite, File::create_Auto, 0); // Throws
189✔
2635
    File::CloseGuard fcg(lockfile);
189✔
2636
    lockfile.set_fifo_path(realm_path + ".management", "lock.fifo");
189✔
2637
    if (lockfile.try_rw_lock_exclusive()) { // Throws
189✔
2638
        callback(realm_path);
147✔
2639
        return true;
147✔
2640
    }
147✔
2641
    return false;
42✔
2642
}
189✔
2643

2644
std::string DB::get_core_file(const std::string& base_path, CoreFileType type)
2645
{
221,349✔
2646
    switch (type) {
221,349✔
2647
        case CoreFileType::Lock:
100,050✔
2648
            return base_path + ".lock";
100,050✔
2649
        case CoreFileType::Storage:
894✔
2650
            return base_path;
894✔
2651
        case CoreFileType::Management:
99,894✔
2652
            return base_path + ".management";
99,894✔
2653
        case CoreFileType::Note:
19,626✔
2654
            return base_path + ".note";
19,626✔
2655
        case CoreFileType::Log:
885✔
2656
            return base_path + ".log";
885✔
2657
    }
221,349✔
2658
    REALM_UNREACHABLE();
2659
}
×
2660

2661
void DB::delete_files(const std::string& base_path, bool* did_delete, bool delete_lockfile)
2662
{
888✔
2663
    if (File::try_remove(get_core_file(base_path, CoreFileType::Storage)) && did_delete) {
888✔
2664
        *did_delete = true;
99✔
2665
    }
99✔
2666

2667
    File::try_remove(get_core_file(base_path, CoreFileType::Note));
888✔
2668
    File::try_remove(get_core_file(base_path, CoreFileType::Log));
888✔
2669
    util::try_remove_dir_recursive(get_core_file(base_path, CoreFileType::Management));
888✔
2670

2671
    if (delete_lockfile) {
888✔
2672
        File::try_remove(get_core_file(base_path, CoreFileType::Lock));
843✔
2673
    }
843✔
2674
}
888✔
2675

2676
TransactionRef DB::start_read(VersionID version_id)
2677
{
1,473,168✔
2678
    if (!is_attached())
1,473,168✔
2679
        throw StaleAccessor("Stale transaction");
6✔
2680
    TransactionRef tr;
1,473,162✔
2681
    if (m_fake_read_lock_if_immutable) {
1,473,162✔
2682
        tr = make_transaction_ref(shared_from_this(), &m_alloc, *m_fake_read_lock_if_immutable, DB::transact_Reading);
372✔
2683
    }
372✔
2684
    else {
1,472,790✔
2685
        ReadLockInfo read_lock = grab_read_lock(ReadLockInfo::Live, version_id);
1,472,790✔
2686
        ReadLockGuard g(*this, read_lock);
1,472,790✔
2687
        read_lock.check();
1,472,790✔
2688
        tr = make_transaction_ref(shared_from_this(), &m_alloc, read_lock, DB::transact_Reading);
1,472,790✔
2689
        g.release();
1,472,790✔
2690
    }
1,472,790✔
2691
    tr->set_file_format_version(get_file_format_version());
1,473,162✔
2692
    return tr;
1,473,162✔
2693
}
1,473,168✔
2694

2695
TransactionRef DB::start_frozen(VersionID version_id)
2696
{
39,678✔
2697
    if (!is_attached())
39,678✔
2698
        throw StaleAccessor("Stale transaction");
×
2699
    TransactionRef tr;
39,678✔
2700
    if (m_fake_read_lock_if_immutable) {
39,678✔
2701
        tr = make_transaction_ref(shared_from_this(), &m_alloc, *m_fake_read_lock_if_immutable, DB::transact_Frozen);
12✔
2702
    }
12✔
2703
    else {
39,666✔
2704
        ReadLockInfo read_lock = grab_read_lock(ReadLockInfo::Frozen, version_id);
39,666✔
2705
        ReadLockGuard g(*this, read_lock);
39,666✔
2706
        read_lock.check();
39,666✔
2707
        tr = make_transaction_ref(shared_from_this(), &m_alloc, read_lock, DB::transact_Frozen);
39,666✔
2708
        g.release();
39,666✔
2709
    }
39,666✔
2710
    tr->set_file_format_version(get_file_format_version());
39,678✔
2711
    return tr;
39,678✔
2712
}
39,678✔
2713

2714
TransactionRef DB::start_write(bool nonblocking)
2715
{
281,214✔
2716
    if (m_fake_read_lock_if_immutable) {
281,214✔
2717
        REALM_ASSERT(false && "Can't write an immutable DB");
×
2718
    }
×
2719
    if (nonblocking) {
281,214✔
2720
        bool success = do_try_begin_write();
84✔
2721
        if (!success) {
84✔
2722
            return TransactionRef();
12✔
2723
        }
12✔
2724
    }
84✔
2725
    else {
281,130✔
2726
        do_begin_write();
281,130✔
2727
    }
281,130✔
2728
    {
281,202✔
2729
        CheckedUniqueLock local_lock(m_mutex);
281,202✔
2730
        if (!is_attached()) {
281,202✔
2731
            local_lock.unlock();
×
2732
            end_write_on_correct_thread();
×
2733
            throw StaleAccessor("Stale transaction");
×
2734
        }
×
2735
        m_write_transaction_open = true;
281,202✔
2736
    }
281,202✔
2737
    TransactionRef tr;
×
2738
    try {
281,202✔
2739
        ReadLockInfo read_lock = grab_read_lock(ReadLockInfo::Live, VersionID());
281,202✔
2740
        ReadLockGuard g(*this, read_lock);
281,202✔
2741
        read_lock.check();
281,202✔
2742

2743
        tr = make_transaction_ref(shared_from_this(), &m_alloc, read_lock, DB::transact_Writing);
281,202✔
2744
        tr->set_file_format_version(get_file_format_version());
281,202✔
2745
        version_type current_version = read_lock.m_version;
281,202✔
2746
        m_alloc.init_mapping_management(current_version);
281,202✔
2747
        if (Replication* repl = get_replication()) {
281,202✔
2748
            bool history_updated = false;
256,662✔
2749
            repl->initiate_transact(*tr, current_version, history_updated); // Throws
256,662✔
2750
        }
256,662✔
2751
        g.release();
281,202✔
2752
    }
281,202✔
2753
    catch (...) {
281,202✔
2754
        end_write_on_correct_thread();
×
2755
        throw;
×
2756
    }
×
2757

2758
    return tr;
281,163✔
2759
}
281,202✔
2760

2761
void DB::async_request_write_mutex(TransactionRef& tr, util::UniqueFunction<void()>&& when_acquired)
2762
{
1,614✔
2763
    {
1,614✔
2764
        util::CheckedLockGuard lck(tr->m_async_mutex);
1,614✔
2765
        REALM_ASSERT(tr->m_async_stage == Transaction::AsyncState::Idle);
1,614✔
2766
        tr->m_async_stage = Transaction::AsyncState::Requesting;
1,614✔
2767
        tr->m_request_time_point = std::chrono::steady_clock::now();
1,614✔
2768
        if (tr->db->m_logger) {
1,614✔
2769
            tr->db->m_logger->log(util::LogCategory::transaction, util::Logger::Level::trace,
1,614✔
2770
                                  "Tr %1: Async request write lock", tr->m_log_id);
1,614✔
2771
        }
1,614✔
2772
    }
1,614✔
2773
    std::weak_ptr<Transaction> weak_tr = tr;
1,614✔
2774
    async_begin_write([weak_tr, cb = std::move(when_acquired)]() {
1,614✔
2775
        if (auto tr = weak_tr.lock()) {
1,614✔
2776
            util::CheckedLockGuard lck(tr->m_async_mutex);
1,614✔
2777
            // If a synchronous transaction happened while we were pending
2778
            // we may be in HasCommits
2779
            if (tr->m_async_stage == Transaction::AsyncState::Requesting) {
1,614✔
2780
                tr->m_async_stage = Transaction::AsyncState::HasLock;
1,614✔
2781
            }
1,614✔
2782
            if (tr->db->m_logger) {
1,614✔
2783
                auto t2 = std::chrono::steady_clock::now();
1,614✔
2784
                tr->db->m_logger->log(
1,614✔
2785
                    util::LogCategory::transaction, util::Logger::Level::trace, "Tr %1, Got write lock in %2 us",
1,614✔
2786
                    tr->m_log_id,
1,614✔
2787
                    std::chrono::duration_cast<std::chrono::microseconds>(t2 - tr->m_request_time_point).count());
1,614✔
2788
            }
1,614✔
2789
            if (tr->m_waiting_for_write_lock) {
1,614✔
2790
                tr->m_waiting_for_write_lock = false;
132✔
2791
                tr->m_async_cv.notify_one();
132✔
2792
            }
132✔
2793
            else if (cb) {
1,482✔
2794
                cb();
1,482✔
2795
            }
1,482✔
2796
            tr.reset(); // Release pointer while lock is held
1,614✔
2797
        }
1,614✔
2798
    });
1,614✔
2799
}
1,614✔
2800

2801
inline DB::DB(Private, const DBOptions& options)
2802
    : m_upgrade_callback(std::move(options.upgrade_callback))
61,440✔
2803
    , m_log_id(util::gen_log_id(this))
61,440✔
2804
{
124,689✔
2805
    if (options.enable_async_writes) {
124,689✔
2806
        m_commit_helper = std::make_unique<AsyncCommitHelper>(this);
82,221✔
2807
    }
82,221✔
2808
}
124,689✔
2809

2810
DBRef DB::create(const std::string& file, const DBOptions& options) NO_THREAD_SAFETY_ANALYSIS
2811
{
27,279✔
2812
    DBRef retval = std::make_shared<DB>(Private(), options);
27,279✔
2813
    retval->open(file, options);
27,279✔
2814
    return retval;
27,279✔
2815
}
27,279✔
2816

2817
DBRef DB::create(Replication& repl, const std::string& file, const DBOptions& options) NO_THREAD_SAFETY_ANALYSIS
2818
{
11,103✔
2819
    DBRef retval = std::make_shared<DB>(Private(), options);
11,103✔
2820
    retval->open(repl, file, options);
11,103✔
2821
    return retval;
11,103✔
2822
}
11,103✔
2823

2824
DBRef DB::create(std::unique_ptr<Replication> repl, const std::string& file,
2825
                 const DBOptions& options) NO_THREAD_SAFETY_ANALYSIS
2826
{
60,813✔
2827
    REALM_ASSERT(repl);
60,813✔
2828
    DBRef retval = std::make_shared<DB>(Private(), options);
60,813✔
2829
    retval->m_history = std::move(repl);
60,813✔
2830
    retval->open(*retval->m_history, file, options);
60,813✔
2831
    return retval;
60,813✔
2832
}
60,813✔
2833

2834
DBRef DB::create(std::unique_ptr<Replication> repl, const DBOptions& options) NO_THREAD_SAFETY_ANALYSIS
2835
{
25,494✔
2836
    REALM_ASSERT(repl);
25,494✔
2837
    DBRef retval = std::make_shared<DB>(Private(), options);
25,494✔
2838
    retval->m_history = std::move(repl);
25,494✔
2839
    retval->open(*retval->m_history, options);
25,494✔
2840
    return retval;
25,494✔
2841
}
25,494✔
2842

2843
DBRef DB::create_in_memory(std::unique_ptr<Replication> repl, const std::string& in_memory_path,
2844
                           const DBOptions& options) NO_THREAD_SAFETY_ANALYSIS
2845
{
×
2846
    DBRef db = create(std::move(repl), options);
×
2847
    db->m_db_path = in_memory_path;
×
2848
    return db;
×
2849
}
×
2850

2851
DBRef DB::create(BinaryData buffer, bool take_ownership) NO_THREAD_SAFETY_ANALYSIS
2852
{
6✔
2853
    DBOptions options;
6✔
2854
    options.is_immutable = true;
6✔
2855
    DBRef retval = std::make_shared<DB>(Private(), options);
6✔
2856
    retval->open(buffer, take_ownership);
6✔
2857
    return retval;
6✔
2858
}
6✔
2859

2860
void DB::claim_sync_agent()
2861
{
16,614✔
2862
    REALM_ASSERT(is_attached());
16,614✔
2863
    std::unique_lock<InterprocessMutex> lock(m_controlmutex);
16,614✔
2864
    if (m_info->sync_agent_present)
16,614✔
2865
        throw MultipleSyncAgents{};
6✔
2866
    m_info->sync_agent_present = 1; // Set to true
16,608✔
2867
    m_is_sync_agent = true;
16,608✔
2868
}
16,608✔
2869

2870
void DB::release_sync_agent()
2871
{
15,138✔
2872
    REALM_ASSERT(is_attached());
15,138✔
2873
    std::unique_lock<InterprocessMutex> lock(m_controlmutex);
15,138✔
2874
    if (!m_is_sync_agent)
15,138✔
2875
        return;
105✔
2876
    REALM_ASSERT(m_info->sync_agent_present);
15,033✔
2877
    m_info->sync_agent_present = 0;
15,033✔
2878
    m_is_sync_agent = false;
15,033✔
2879
}
15,033✔
2880

2881
void DB::do_begin_possibly_async_write()
2882
{
335,427✔
2883
    if (m_commit_helper) {
335,427✔
2884
        m_commit_helper->blocking_begin_write();
206,895✔
2885
    }
206,895✔
2886
    else {
128,532✔
2887
        do_begin_write();
128,532✔
2888
    }
128,532✔
2889
}
335,427✔
2890

2891
void DB::end_write_on_correct_thread() noexcept
2892
{
616,833✔
2893
    //    m_local_write_mutex.unlock();
2894
    if (!m_commit_helper || !m_commit_helper->blocking_end_write()) {
616,833✔
2895
        do_end_write();
409,737✔
2896
    }
409,737✔
2897
}
616,833✔
2898

2899
void DB::add_commit_listener(CommitListener* listener)
2900
{
97,290✔
2901
    std::lock_guard lock(m_commit_listener_mutex);
97,290✔
2902
    m_commit_listeners.push_back(listener);
97,290✔
2903
}
97,290✔
2904

2905
void DB::remove_commit_listener(CommitListener* listener)
2906
{
97,341✔
2907
    std::lock_guard lock(m_commit_listener_mutex);
97,341✔
2908
    m_commit_listeners.erase(std::remove(m_commit_listeners.begin(), m_commit_listeners.end(), listener),
97,341✔
2909
                             m_commit_listeners.end());
97,341✔
2910
}
97,341✔
2911

2912
DisableReplication::DisableReplication(Transaction& t)
2913
    : m_tr(t)
2914
    , m_owner(t.get_db())
2915
    , m_repl(m_owner->get_replication())
2916
    , m_version(t.get_version())
UNCOV
2917
{
×
UNCOV
2918
    m_owner->set_replication(nullptr);
×
UNCOV
2919
    t.m_history = nullptr;
×
UNCOV
2920
}
×
2921

2922
DisableReplication::~DisableReplication()
UNCOV
2923
{
×
UNCOV
2924
    m_owner->set_replication(m_repl);
×
UNCOV
2925
    if (m_version != m_tr.get_version())
×
2926
        m_tr.initialize_replication();
×
UNCOV
2927
}
×
2928

2929
} // 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