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

realm / realm-core / github_pull_request_281750

30 Oct 2023 03:37PM UTC coverage: 90.528% (-1.0%) from 91.571%
github_pull_request_281750

Pull #6073

Evergreen

jedelbo
Log free space and history sizes when opening file
Pull Request #6073: Merge next-major

95488 of 175952 branches covered (0.0%)

8973 of 12277 new or added lines in 149 files covered. (73.09%)

622 existing lines in 51 files now uncovered.

233503 of 257934 relevant lines covered (90.53%)

6533720.56 hits per line

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

93.22
/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
        {
150,385,245✔
98
            return version != 0;
150,385,245✔
99
        }
150,385,245✔
100
        void deactivate()
101
        {
10,135,098✔
102
            version = 0;
10,135,098✔
103
            count_live = count_frozen = count_full = 0;
10,135,098✔
104
        }
10,135,098✔
105
        void activate(uint64_t v)
106
        {
1,502,340✔
107
            version = v;
1,502,340✔
108
        }
1,502,340✔
109
    };
110

111
    void reserve(uint32_t size) noexcept
112
    {
277,680✔
113
        for (auto i = entries; i < size; ++i)
9,163,401✔
114
            data()[i].deactivate();
8,885,721✔
115
        if (size > entries) {
277,680✔
116
            // Fence preventing downward motion of above writes
136,833✔
117
            std::atomic_signal_fence(std::memory_order_release);
277,680✔
118
            entries = size;
277,680✔
119
        }
277,680✔
120
    }
277,680✔
121

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

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

137
    unsigned int capacity() const noexcept
138
    {
2,724,405✔
139
        return entries;
2,724,405✔
140
    }
2,724,405✔
141

142
    ReadCount& get(uint_fast32_t idx) noexcept
143
    {
6,337,470✔
144
        return data()[idx];
6,337,470✔
145
    }
6,337,470✔
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
    {
1,502,340✔
154
        auto i = allocating.load();
1,502,340✔
155
        if (i == newest.load()) {
1,502,340✔
156
            // if newest != allocating we are recovering from a crash and MUST complete the earlier allocation
687,003✔
157
            // but if not, find lowest free entry by linear search.
687,003✔
158
            uint32_t k = 0;
1,362,297✔
159
            while (k < entries && data()[k].is_active()) {
2,482,335✔
160
                ++k;
1,120,038✔
161
            }
1,120,038✔
162
            if (k == entries)
1,362,297✔
163
                return nullptr;     // no free entries
18✔
164
            allocating.exchange(k); // barrier: prevent upward movement of instructions below
1,362,279✔
165
            i = k;
1,362,279✔
166
        }
1,362,279✔
167
        auto& rc = data()[i];
1,502,331✔
168
        REALM_ASSERT(rc.count_frozen == 0);
1,502,322✔
169
        REALM_ASSERT(rc.count_live == 0);
1,502,322✔
170
        REALM_ASSERT(rc.count_full == 0);
1,502,322✔
171
        rc.current_top = top;
1,502,322✔
172
        rc.filesize = size;
1,502,322✔
173
        rc.activate(version);
1,502,322✔
174
        newest.store(i); // barrier: prevent downward movement of instructions above
1,502,322✔
175
        return &rc;
1,502,322✔
176
    }
1,502,340✔
177

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

183
    void free_entry(ReadCount* rc) noexcept
184
    {
1,249,389✔
185
        rc->current_top = rc->filesize = -1ULL; // easy to recognize in debugger
1,249,389✔
186
        rc->deactivate();
1,249,389✔
187
    }
1,249,389✔
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
    {
140,037✔
198
        newest = nil;
140,037✔
199
        allocating = 0;
140,037✔
200
        auto t_free = entries;
140,037✔
201
        entries = 0;
140,037✔
202
        reserve(t_free);
140,037✔
203
        return *try_allocate_entry(top, filesize, version);
140,037✔
204
    }
140,037✔
205

206
    void purge_versions(uint64_t& oldest_live_v, TopRefMap& top_refs, bool& any_new_unreachables)
207
    {
1,362,246✔
208
        oldest_live_v = std::numeric_limits<uint64_t>::max();
1,362,246✔
209
        auto oldest_full_v = std::numeric_limits<uint64_t>::max();
1,362,246✔
210
        any_new_unreachables = false;
1,362,246✔
211
        // correct case where an earlier crash may have left the entry at 'allocating' partially initialized:
686,937✔
212
        const auto index_of_newest = newest.load();
1,362,246✔
213
        if (auto a = allocating.load(); a != index_of_newest) {
1,362,246✔
214
            data()[a].deactivate();
×
215
        }
×
216
        // determine fully locked versions - after one of those all versions are considered live.
686,937✔
217
        for (auto* rc = data(); rc < data() + entries; ++rc) {
45,432,447✔
218
            if (!rc->is_active())
44,070,201✔
219
                continue;
40,709,547✔
220
            if (rc->count_full) {
3,360,654✔
221
                if (rc->version < oldest_full_v)
×
222
                    oldest_full_v = rc->version;
×
223
            }
×
224
        }
3,360,654✔
225
        // collect reachable versions and determine oldest live reachable version
686,937✔
226
        // (oldest reachable version is the first entry in the top_refs map, so no need to find it explicitly)
686,937✔
227
        for (auto* rc = data(); rc < data() + entries; ++rc) {
45,433,815✔
228
            if (!rc->is_active())
44,071,569✔
229
                continue;
40,711,101✔
230
            if (rc->count_frozen || rc->count_live || rc->version >= oldest_full_v) {
3,360,468✔
231
                // entry is still reachable
1,075,074✔
232
                top_refs.emplace(rc->version, VersionInfo{to_ref(rc->current_top), to_ref(rc->filesize)});
2,111,454✔
233
            }
2,111,454✔
234
            if (rc->count_live || rc->version >= oldest_full_v) {
3,360,468✔
235
                if (rc->version < oldest_live_v)
1,560,003✔
236
                    oldest_live_v = rc->version;
1,424,685✔
237
            }
1,560,003✔
238
        }
3,360,468✔
239
        // we must have found at least one reachable version
686,937✔
240
        REALM_ASSERT(top_refs.size());
1,362,246✔
241
        // free unreachable entries and determine if we want to trigger backdating
686,937✔
242
        uint64_t oldest_v = top_refs.begin()->first;
1,362,246✔
243
        for (auto* rc = data(); rc < data() + entries; ++rc) {
45,432,630✔
244
            if (!rc->is_active())
44,070,384✔
245
                continue;
40,710,099✔
246
            if (rc->count_frozen == 0 && rc->count_live == 0 && rc->version < oldest_full_v) {
3,360,285✔
247
                // entry is becoming unreachable.
631,398✔
248
                // if it is also younger than a reachable version, then set 'any_new_unreachables' to trigger
631,398✔
249
                // backdating
631,398✔
250
                if (rc->version > oldest_v) {
1,249,389✔
251
                    any_new_unreachables = true;
63,993✔
252
                }
63,993✔
253
                REALM_ASSERT(index_of(*rc) != index_of_newest);
1,249,389✔
254
                free_entry(rc);
1,249,389✔
255
            }
1,249,389✔
256
        }
3,360,285✔
257
        REALM_ASSERT(oldest_v != std::numeric_limits<uint64_t>::max());
1,362,246✔
258
        REALM_ASSERT(oldest_live_v != std::numeric_limits<uint64_t>::max());
1,362,246✔
259
    }
1,362,246✔
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
    {
160,805,415✔
289
        return m_data;
160,805,415✔
290
    }
160,805,415✔
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) {
3,077,805✔
299
    t->close();
3,077,805✔
300
    delete t;
3,077,805✔
301
};
3,077,805✔
302

303
template <typename... Args>
304
TransactionRef make_transaction_ref(Args&&... args)
305
{
3,086,535✔
306
    return TransactionRef(new Transaction(std::forward<Args>(args)...), TransactionDeleter);
3,086,535✔
307
}
3,086,535✔
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,368✔
447

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

455

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

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

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

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

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

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

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

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

570
    void release_read_lock(const ReadLockInfo& read_lock) REQUIRES(!m_local_readers_mutex, !m_info_mutex)
571
    {
10,188,516✔
572
        {
10,188,516✔
573
            util::CheckedLockGuard lock(m_local_readers_mutex);
10,188,516✔
574
            REALM_ASSERT(read_lock.m_reader_idx < m_local_readers.size());
10,188,516✔
575
            auto& r = m_local_readers[read_lock.m_reader_idx];
10,188,516✔
576
            auto& f = field_for_type(r, read_lock.m_type);
10,188,516✔
577
            REALM_ASSERT(f > 0);
10,188,516✔
578
            if (--f > 0)
10,188,516✔
579
                return;
7,064,901✔
580
            if (r.count_live == 0 && r.count_full == 0 && r.count_frozen == 0)
3,123,615✔
581
                r.version = 0;
3,098,274✔
582
        }
3,123,615✔
583

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

595
    ReadLockInfo grab_read_lock(ReadLockInfo::Type type, VersionID version_id = {})
596
        REQUIRES(!m_local_readers_mutex, !m_info_mutex)
597
    {
10,188,480✔
598
        ReadLockInfo read_lock;
10,188,480✔
599
        if (try_grab_local_read_lock(read_lock, type, version_id))
10,188,480✔
600
            return read_lock;
7,064,940✔
601

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

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

1,566,849✔
637
        return read_lock;
3,123,408✔
638
    }
3,123,408✔
639

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

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

665

666
private:
667
    void grow_local_cache(size_t new_size) REQUIRES(m_local_readers_mutex)
668
    {
3,123,864✔
669
        if (new_size > m_local_readers.size())
3,123,864✔
670
            m_local_readers.resize(new_size, VersionList::ReadCount{});
279,714✔
671
    }
3,123,864✔
672

673
    void populate_read_lock(ReadLockInfo& read_lock, VersionList::ReadCount& r, ReadLockInfo::Type type)
674
    {
10,188,591✔
675
        ++field_for_type(r, type);
10,188,591✔
676
        read_lock.m_type = type;
10,188,591✔
677
        read_lock.m_version = r.version;
10,188,591✔
678
        read_lock.m_top_ref = static_cast<ref_type>(r.current_top);
10,188,591✔
679
        read_lock.m_file_size = static_cast<size_t>(r.filesize);
10,188,591✔
680
    }
10,188,591✔
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
    {
10,188,345✔
685
        const bool pick_specific = version_id.version != VersionID().version;
10,188,345✔
686
        auto index = version_id.index;
10,188,345✔
687
        if (!pick_specific) {
10,188,345✔
688
            util::CheckedLockGuard lock(m_info_mutex);
9,901,284✔
689
            index = m_info->readers.newest.load();
9,901,284✔
690
        }
9,901,284✔
691
        util::CheckedLockGuard local_lock(m_local_readers_mutex);
10,188,345✔
692
        if (index >= m_local_readers.size())
10,188,345✔
693
            return false;
279,717✔
694

7,797,936✔
695
        auto& r = m_local_readers[index];
9,908,628✔
696
        if (!r.is_active())
9,908,628✔
697
            return false;
2,818,647✔
698
        if (pick_specific && r.version != version_id.version)
7,089,981✔
699
            return false;
×
700
        if (field_for_type(r, type) == 0)
7,089,981✔
701
            return false;
25,605✔
702

6,368,403✔
703
        read_lock.m_reader_idx = index;
7,064,376✔
704
        populate_read_lock(read_lock, r, type);
7,064,376✔
705
        return true;
7,064,376✔
706
    }
7,064,376✔
707

708
    static uint32_t& field_for_type(VersionList::ReadCount& r, ReadLockInfo::Type type)
709
    {
36,835,374✔
710
        switch (type) {
36,835,374✔
711
            case ReadLockInfo::Frozen:
173,427✔
712
                return r.count_frozen;
173,427✔
713
            case ReadLockInfo::Live:
36,661,854✔
714
                return r.count_live;
36,661,854✔
715
            case ReadLockInfo::Full:
✔
716
                return r.count_full;
×
717
            default:
✔
718
                REALM_UNREACHABLE(); // silence a warning
×
719
        }
36,835,374✔
720
    }
36,835,374✔
721

722
    void mark_page_for_writing(uint64_t page_offset) REQUIRES(!m_info_mutex)
723
    {
2,724✔
724
        util::CheckedLockGuard info_lock(m_info_mutex);
2,724✔
725
        m_info->writing_page_offset = page_offset + 1;
2,724✔
726
        m_info->write_counter++;
2,724✔
727
    }
2,724✔
728
    void clear_writing_marker() REQUIRES(!m_info_mutex)
729
    {
2,724✔
730
        util::CheckedLockGuard info_lock(m_info_mutex);
2,724✔
731
        m_info->write_counter++;
2,724✔
732
        m_info->writing_page_offset = 0;
2,724✔
733
    }
2,724✔
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
    {
90✔
739
        util::CheckedLockGuard info_lock(m_info_mutex);
90✔
740
        if (write_counter) {
90✔
741
            *write_counter = m_info->write_counter;
90✔
742
        }
90✔
743
        uint64_t marked = m_info->writing_page_offset;
90✔
744
        if (marked && page_offset) {
90!
745
            *page_offset = marked - 1;
×
746
        }
×
747
        return marked != 0;
90✔
748
    }
90✔
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)
768
        , m_file(file)
769
    {
138,222✔
770
        size_t size = 0, required_size = sizeof(SharedInfo);
138,222✔
771
        while (size < required_size) {
276,444✔
772
            // Map the file without the lock held. This could result in the
67,941✔
773
            // mapping being too small and having to remap if the file is grown
67,941✔
774
            // concurrently, but if this is the case we should always see a bigger
67,941✔
775
            // size the next time.
67,941✔
776
            auto new_size = static_cast<size_t>(m_file.get_size());
138,222✔
777
            REALM_ASSERT(new_size > size);
138,222✔
778
            size = new_size;
138,222✔
779
            m_reader_map.remap(m_file, File::access_ReadWrite, size, File::map_NoSync);
138,222✔
780
            m_info = m_reader_map.get_addr();
138,222✔
781

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

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

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

2,818,557✔
803
        if (required < m_local_max_entry)
5,604,084✔
804
            return;
3,043,266✔
805

1,292,136✔
806
        auto new_max_entry = m_info->readers.capacity();
2,560,818✔
807
        if (new_max_entry > m_local_max_entry) {
2,560,818✔
808
            // handle mapping expansion if required
809
            size_t info_size = sizeof(DB::SharedInfo) + m_info->readers.compute_required_space(new_max_entry);
×
810
            m_reader_map.remap(m_file, util::File::access_ReadWrite, info_size); // Throws
×
811
            m_local_max_entry = new_max_entry;
×
812
            m_info = m_reader_map.get_addr();
×
813
        }
×
814
    }
2,560,818✔
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)
827
    {
138,222✔
828
    }
138,222✔
829
    bool no_concurrent_writer_seen() override
830
    {
90✔
831
        uint64_t tmp_write_count;
90✔
832
        auto page_may_have_been_written = vm.observe_writer(nullptr, &tmp_write_count);
90✔
833
        if (tmp_write_count != last_seen_count) {
90✔
834
            page_may_have_been_written = true;
×
835
            last_seen_count = tmp_write_count;
×
836
        }
×
837
        if (page_may_have_been_written) {
90✔
838
            calls_since_last_writer_observed = 0;
×
839
            return false;
×
840
        }
×
841
        ++calls_since_last_writer_observed;
90✔
842
        constexpr size_t max_calls = 5; // an arbitrary handful, > 1
90✔
843
        return (calls_since_last_writer_observed >= max_calls);
90✔
844
    }
90✔
845
    void mark(uint64_t pos) override
846
    {
2,724✔
847
        vm.mark_page_for_writing(pos);
2,724✔
848
    }
2,724✔
849
    void unmark() override
850
    {
2,724✔
851
        vm.clear_writing_marker();
2,724✔
852
    }
2,724✔
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)
864
    {
25,368✔
865
        m_info = info;
25,368✔
866
        m_local_max_entry = m_info->readers.capacity();
25,368✔
867
    }
25,368✔
868
    void expand_version_list(unsigned) override
869
    {
×
870
        REALM_ASSERT(false);
×
871
    }
×
872

873
private:
874
    void ensure_reader_mapping(unsigned int) override {}
334,338✔
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, bool no_create_file, const DBOptions& options)
902
{
138,153✔
903
    // Exception safety: Since do_open() is called from constructors, if it
67,920✔
904
    // throws, it must leave the file closed.
67,920✔
905
    using util::format;
138,153✔
906

67,920✔
907
    REALM_ASSERT(!is_attached());
138,153✔
908
    REALM_ASSERT(path.size());
138,153✔
909

67,920✔
910
    m_db_path = path;
138,153✔
911

67,920✔
912
    set_logger(options.logger);
138,153✔
913
    if (m_replication) {
138,153✔
914
        m_replication->set_logger(m_logger.get());
113,322✔
915
    }
113,322✔
916
    if (m_logger) {
138,153✔
917
        m_logger->log(util::Logger::Level::detail, "Open file: %1", path);
123,909✔
918
    }
123,909✔
919
    SlabAlloc& alloc = m_alloc;
138,153✔
920
    ref_type top_ref = 0;
138,153✔
921

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

67,830✔
939
    Replication::HistoryType openers_hist_type = Replication::hist_None;
137,973✔
940
    int openers_hist_schema_version = 0;
137,973✔
941
    if (Replication* repl = get_replication()) {
137,973✔
942
        openers_hist_type = repl->get_history_type();
113,316✔
943
        openers_hist_schema_version = repl->get_history_schema_version();
113,316✔
944
    }
113,316✔
945

67,830✔
946
    int current_file_format_version;
137,973✔
947
    int target_file_format_version;
137,973✔
948
    int stored_hist_schema_version = -1; // Signals undetermined
137,973✔
949

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

104,475✔
957
        // if we're retrying, we first wait a random time
104,475✔
958
        if (retries_left < 10) {
211,830✔
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

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

104,475✔
972
        if (m_file.try_rw_lock_exclusive()) { // Throws
211,830✔
973
            File::UnlockGuard ulg(m_file);
112,257✔
974

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

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

55,167✔
992
            new (info) SharedInfo{options.durability, openers_hist_type, openers_hist_schema_version}; // Throws
112,257✔
993

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

104,475✔
999
// We hold the shared lock from here until we close the file!
104,475✔
1000
#if REALM_PLATFORM_APPLE
107,355✔
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()) {
107,700✔
1005
            sched_yield();
345✔
1006
        }
345✔
1007
#else
1008
        m_file.rw_lock_shared(); // Throws
104,475✔
1009
#endif
104,475✔
1010
        File::UnlockGuard ulg(m_file);
211,830✔
1011

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

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

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

104,475✔
1038
        // An empty file is (and was) never a successfully initialized file.
104,475✔
1039
        size_t info_size = sizeof(SharedInfo);
211,830✔
1040
        {
211,830✔
1041
            auto file_size = m_file.get_size();
211,830✔
1042
            if (util::int_less_than(file_size, info_size)) {
211,830✔
1043
                if (file_size == 0)
73,416✔
1044
                    continue; // Retry
48,159✔
1045
                info_size = size_t(file_size);
25,257✔
1046
            }
25,257✔
1047
        }
211,830✔
1048

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

73,236✔
1057
#ifndef _WIN32
163,671✔
1058
#pragma GCC diagnostic push
163,671✔
1059
#pragma GCC diagnostic ignored "-Winvalid-offsetof"
163,671✔
1060
#endif
163,671✔
1061
        static_assert(offsetof(SharedInfo, init_complete) + sizeof SharedInfo::init_complete <= 1,
163,671✔
1062
                      "Unexpected position or size of SharedInfo::init_complete");
163,671✔
1063
#ifndef _WIN32
163,671✔
1064
#pragma GCC diagnostic pop
163,671✔
1065
#endif
163,671✔
1066
        if (info->init_complete == 0)
163,671✔
1067
            continue;
25,191✔
1068
        REALM_ASSERT(info->init_complete == 1);
138,480✔
1069

68,073✔
1070
        // At this time, we know that the file was completely initialized, but
68,073✔
1071
        // we still need to verify that is was initialized with the memory
68,073✔
1072
        // layout expected by this session participant. We could find that it is
68,073✔
1073
        // initializaed with a different memory layout if other concurrent
68,073✔
1074
        // session participants use different versions of the core library.
68,073✔
1075
        if (info_size < sizeof(SharedInfo)) {
138,480✔
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
        }
6✔
1083
        if (info->shared_info_version != g_shared_info_version) {
138,414✔
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
        }
6✔
1091
        // Validate compatible sizes of mutex and condvar types. Sizes of all
68,007✔
1092
        // other fields are architecture independent, so if condvar and mutex
68,007✔
1093
        // sizes match, the entire struct matches. The offsets of
68,007✔
1094
        // `size_of_mutex` and `size_of_condvar` are known to be as expected due
68,007✔
1095
        // to the preceeding check in `shared_info_version`.
68,007✔
1096
        if (info->size_of_mutex != sizeof info->shared_controlmutex) {
138,348✔
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
        }
6✔
1104

67,974✔
1105
        if (info->size_of_condvar != sizeof info->room_to_write) {
138,282✔
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
        }
6✔
1114
        m_writemutex.set_shared_part(info->shared_writemutex, lockfile_prefix, "write");
138,216✔
1115
        m_controlmutex.set_shared_part(info->shared_controlmutex, lockfile_prefix, "control");
138,216✔
1116
        m_versionlist_mutex.set_shared_part(info->shared_versionlist_mutex, lockfile_prefix, "versions");
138,216✔
1117

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

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

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

67,941✔
1148
            // only the session initiator is allowed to create the database, all other
67,941✔
1149
            // must assume that it already exists.
67,941✔
1150
            cfg.no_create = (begin_new_session ? no_create_file : true);
126,450✔
1151

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

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

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

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

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

67,896✔
1231
            if (REALM_UNLIKELY(!file_format_ok)) {
138,132✔
1232
                throw UnsupportedFileFormatVersion(current_file_format_version);
12✔
1233
            }
12✔
1234

67,890✔
1235
            if (begin_new_session) {
138,120✔
1236
                // Determine version (snapshot number) and check history
56,349✔
1237
                // compatibility
56,349✔
1238
                version_type version = 0;
114,816✔
1239
                int stored_hist_type = 0;
114,816✔
1240
                gf::get_version_and_history_info(alloc, top_ref, version, stored_hist_type,
114,816✔
1241
                                                 stored_hist_schema_version);
114,816✔
1242
                bool good_history_type = false;
114,816✔
1243
                switch (openers_hist_type) {
114,816✔
1244
                    case Replication::hist_None:
7,848✔
1245
                        good_history_type = (stored_hist_type == Replication::hist_None);
7,848✔
1246
                        if (!good_history_type)
7,848✔
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;
7,842✔
1253
                    case Replication::hist_OutOfRealm:
3,882✔
1254
                        REALM_ASSERT(false); // No longer in use
×
1255
                        break;
×
1256
                    case Replication::hist_InRealm:
79,050✔
1257
                        good_history_type = (stored_hist_type == Replication::hist_InRealm ||
79,050✔
1258
                                             stored_hist_type == Replication::hist_None);
48,246✔
1259
                        if (!good_history_type)
79,050✔
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;
79,044✔
1266
                    case Replication::hist_SyncClient:
52,329✔
1267
                        good_history_type = ((stored_hist_type == Replication::hist_SyncClient) || (top_ref == 0));
26,232✔
1268
                        if (!good_history_type)
26,232✔
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;
26,226✔
1275
                    case Replication::hist_SyncServer:
13,839✔
1276
                        good_history_type = ((stored_hist_type == Replication::hist_SyncServer) || (top_ref == 0));
1,686✔
1277
                        if (!good_history_type)
1,686✔
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,686✔
1284
                }
114,798✔
1285

56,340✔
1286
                REALM_ASSERT(stored_hist_schema_version >= 0);
114,798✔
1287
                if (stored_hist_schema_version > openers_hist_schema_version)
114,798✔
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 =
114,798✔
1293
                    (stored_hist_schema_version < openers_hist_schema_version && top_ref != 0);
114,798✔
1294
                if (need_hist_schema_upgrade) {
114,798✔
1295
                    Replication* repl = get_replication();
348✔
1296
                    if (!repl->is_upgradable_history_schema(stored_hist_schema_version))
348✔
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
                }
114,798✔
1302

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

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

56,217✔
1332
                info->file_format_version = uint_fast8_t(target_file_format_version);
114,525✔
1333

56,217✔
1334
                // Initially there is a single version in the file
56,217✔
1335
                info->number_of_versions = 1;
114,525✔
1336

56,217✔
1337
                info->latest_version_number = version;
114,525✔
1338
                alloc.init_mapping_management(version);
114,525✔
1339

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

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

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

11,535✔
1371
                // We need per session agreement among all participants on the
11,535✔
1372
                // target Realm file format. From a technical perspective, the
11,535✔
1373
                // best way to ensure that, would be to require a bumping of the
11,535✔
1374
                // SharedInfo file format version on any change that could lead
11,535✔
1375
                // to a different result from
11,535✔
1376
                // get_target_file_format_for_session() given the same current
11,535✔
1377
                // Realm file format version and the same history type, as that
11,535✔
1378
                // would prevent the outcome of the Realm opening process from
11,535✔
1379
                // depending on race conditions. However, for practical reasons,
11,535✔
1380
                // we shall instead simply check that there is agreement, and
11,535✔
1381
                // throw the same kind of exception, as would have been thrown
11,535✔
1382
                // with a bumped SharedInfo file format version, if there isn't.
11,535✔
1383
                if (info->file_format_version != target_file_format_version) {
23,292✔
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

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

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

67,890✔
1401
            m_new_commit_available.set_shared_part(info->new_commit_available, lockfile_prefix, "new_commit",
137,955✔
1402
                                                   options.temp_dir);
137,817✔
1403
            m_pick_next_writer.set_shared_part(info->pick_next_writer, lockfile_prefix, "pick_writer",
137,817✔
1404
                                               options.temp_dir);
137,817✔
1405

67,752✔
1406
            // make our presence noted:
67,752✔
1407
            ++info->num_participants;
137,817✔
1408
            m_info = info;
137,817✔
1409

67,752✔
1410
            // Keep the mappings and file open:
67,752✔
1411
            m_version_manager = std::move(version_manager);
137,817✔
1412
            alloc_detach_guard.release();
137,817✔
1413
            fug_1.release(); // Do not unmap
137,817✔
1414
            fcg.release();   // Do not close
137,817✔
1415
        }
137,817✔
1416
        ulg.release(); // Do not release shared lock
137,817✔
1417
        break;
137,817✔
1418
    }
138,120✔
1419

67,830✔
1420
    if (m_logger) {
137,904✔
1421
        m_logger->log(util::Logger::Level::debug, "   Number of participants: %1", m_info->num_participants);
123,699✔
1422
        m_logger->log(util::Logger::Level::debug, "   Durability: %1", [&] {
123,699✔
1423
            switch (options.durability) {
123,699✔
1424
                case DBOptions::Durability::Full:
103,653✔
1425
                    return "Full";
103,653✔
1426
                case DBOptions::Durability::MemOnly:
20,046✔
1427
                    return "MemOnly";
20,046✔
NEW
1428
                case realm::DBOptions::Durability::Unsafe:
✔
NEW
1429
                    return "Unsafe";
×
NEW
1430
            }
×
NEW
1431
            return "";
×
NEW
1432
        }());
×
1433
        m_logger->log(util::Logger::Level::debug, "   EncryptionKey: %1", options.encryption_key ? "yes" : "no");
123,669✔
1434
        if (m_logger->would_log(util::Logger::Level::debug)) {
123,699✔
1435
            if (top_ref) {
24,018✔
1436
                Array top(alloc);
24,006✔
1437
                top.init_from_ref(top_ref);
24,006✔
1438
                auto file_size = Group::get_logical_file_size(top);
24,006✔
1439
                auto history_size = Group::get_history_size(top);
24,006✔
1440
                auto freee_space_size = Group::get_free_space_size(top);
24,006✔
1441
                m_logger->log(util::Logger::Level::debug, "   File size: %1", file_size);
24,006✔
1442
                m_logger->log(util::Logger::Level::debug, "   User data size: %1",
24,006✔
1443
                              file_size - (freee_space_size + history_size));
24,006✔
1444
                m_logger->log(util::Logger::Level::debug, "   Free space size: %1", freee_space_size);
24,006✔
1445
                m_logger->log(util::Logger::Level::debug, "   History size: %1", history_size);
24,006✔
1446
            }
24,006✔
1447
            else {
12✔
1448
                m_logger->log(util::Logger::Level::debug, "   Empty file");
12✔
1449
            }
12✔
1450
        }
24,018✔
1451
    }
123,699✔
1452

67,755✔
1453
    // Upgrade file format and/or history schema
67,755✔
1454
    try {
137,829✔
1455
        if (stored_hist_schema_version == -1) {
137,829✔
1456
            // current_hist_schema_version has not been read. Read it now
11,535✔
1457
            stored_hist_schema_version = start_read()->get_history_schema_version();
23,292✔
1458
        }
23,292✔
1459
        if (current_file_format_version == 0) {
137,829✔
1460
            // If the current file format is still undecided, no upgrade is
24,597✔
1461
            // necessary, but we still need to make the chosen file format
24,597✔
1462
            // visible to the rest of the core library by updating the value
24,597✔
1463
            // that will be subsequently returned by
24,597✔
1464
            // Group::get_file_format_version(). For this to work, all session
24,597✔
1465
            // participants must adopt the chosen target Realm file format when
24,597✔
1466
            // the stored file format version is zero regardless of the version
24,597✔
1467
            // of the core library used.
24,597✔
1468
            m_file_format_version = target_file_format_version;
50,514✔
1469
        }
50,514✔
1470
        else {
87,315✔
1471
            m_file_format_version = current_file_format_version;
87,315✔
1472
            upgrade_file_format(options.allow_file_format_upgrade, target_file_format_version,
87,315✔
1473
                                stored_hist_schema_version, openers_hist_schema_version); // Throws
87,315✔
1474
        }
87,315✔
1475
    }
137,829✔
1476
    catch (...) {
67,758✔
1477
        close();
6✔
1478
        throw;
6✔
1479
    }
6✔
1480
    m_alloc.set_read_only(true);
137,811✔
1481
}
137,811✔
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
{
113,313✔
1493
    // Exception safety: Since open() is called from constructors, if it throws,
55,503✔
1494
    // it must leave the file closed.
55,503✔
1495

55,503✔
1496
    REALM_ASSERT(!is_attached());
113,313✔
1497

55,503✔
1498
    repl.initialize(*this); // Throws
113,313✔
1499

55,503✔
1500
    set_replication(&repl);
113,313✔
1501

55,503✔
1502
    bool no_create = false;
113,313✔
1503
    open(file, no_create, options); // Throws
113,313✔
1504
}
113,313✔
1505

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

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

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

1529
void DB::set_logger(const std::shared_ptr<util::Logger>& logger) noexcept
1530
{
163,524✔
1531
    if (logger)
163,524✔
1532
        m_logger = std::make_shared<DBLogger>(logger, m_log_id);
149,262✔
1533
}
163,524✔
1534

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

12,684✔
1541
    m_alloc.init_in_memory_buffer();
25,368✔
1542

12,684✔
1543
    set_logger(options.logger);
25,368✔
1544
    m_replication->set_logger(m_logger.get());
25,368✔
1545
    if (m_logger)
25,368✔
1546
        m_logger->detail("Open memory-only realm");
25,356✔
1547

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

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

12,684✔
1565
    m_version_manager = std::make_unique<InMemoryVersionManager>(info, m_versionlist_mutex);
25,368✔
1566

12,684✔
1567
    m_file_format_version = target_file_format_version;
25,368✔
1568

12,684✔
1569
    m_info = info;
25,368✔
1570
    m_alloc.set_read_only(true);
25,368✔
1571
}
25,368✔
1572

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

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

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

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

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

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

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

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

75✔
1648
        // Holding the controlmutex prevents any other DB from attaching to the file.
75✔
1649

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

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

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

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

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

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

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

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

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

42✔
1754
    File file;
84✔
1755
    file.open(path, File::access_ReadWrite, File::create_Must, 0);
84✔
1756
    file.resize(0);
84✔
1757

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

1767
uint_fast64_t DB::get_number_of_versions()
1768
{
378,924✔
1769
    if (m_fake_read_lock_if_immutable)
378,924✔
1770
        return 1;
6✔
1771
    return m_info->number_of_versions;
378,918✔
1772
}
378,918✔
1773

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

1779
DB::~DB() noexcept
1780
{
163,533✔
1781
    close();
163,533✔
1782
}
163,533✔
1783

1784
void DB::release_all_read_locks() noexcept
1785
{
163,185✔
1786
    REALM_ASSERT(!m_fake_read_lock_if_immutable);
163,185✔
1787
    CheckedLockGuard local_lock(m_mutex); // mx on m_local_locks_held
163,185✔
1788
    for (auto& read_lock : m_local_locks_held) {
80,439✔
1789
        --m_transaction_count;
6✔
1790
        m_version_manager->release_read_lock(read_lock);
6✔
1791
    }
6✔
1792
    m_local_locks_held.clear();
163,185✔
1793
    REALM_ASSERT(m_transaction_count == 0);
163,185✔
1794
}
163,185✔
1795

1796
// Note: close() and close_internal() may be called from the DB::~DB().
1797
// in that case, they will not throw. Throwing can only happen if called
1798
// directly.
1799
void DB::close(bool allow_open_read_transactions)
1800
{
163,830✔
1801
    // make helper thread(s) terminate
80,763✔
1802
    m_commit_helper.reset();
163,830✔
1803

80,763✔
1804
    if (m_fake_read_lock_if_immutable) {
163,830✔
1805
        if (!is_attached())
186✔
1806
            return;
×
1807
        {
186✔
1808
            CheckedLockGuard local_lock(m_mutex);
186✔
1809
            if (!allow_open_read_transactions && m_transaction_count)
186✔
1810
                throw WrongTransactionState("Closing with open read transactions");
×
1811
        }
186✔
1812
        if (m_alloc.is_attached())
186✔
1813
            m_alloc.detach();
186✔
1814
        m_fake_read_lock_if_immutable.reset();
186✔
1815
    }
186✔
1816
    else {
163,644✔
1817
        close_internal(std::unique_lock<InterprocessMutex>(m_controlmutex, std::defer_lock),
163,644✔
1818
                       allow_open_read_transactions);
163,644✔
1819
    }
163,644✔
1820
}
163,830✔
1821

1822
void DB::close_internal(std::unique_lock<InterprocessMutex> lock, bool allow_open_read_transactions)
1823
{
163,638✔
1824
    if (!is_attached())
163,638✔
1825
        return;
447✔
1826

80,442✔
1827
    {
163,191✔
1828
        CheckedLockGuard local_lock(m_mutex);
163,191✔
1829
        if (m_write_transaction_open)
163,191✔
1830
            throw WrongTransactionState("Closing with open write transactions");
6✔
1831
        if (!allow_open_read_transactions && m_transaction_count)
163,185✔
1832
            throw WrongTransactionState("Closing with open read transactions");
6✔
1833
    }
163,179✔
1834
    SharedInfo* info = m_info;
163,179✔
1835
    {
163,179✔
1836
        if (!lock.owns_lock())
163,179✔
1837
            lock.lock();
163,185✔
1838

80,436✔
1839
        if (m_alloc.is_attached())
163,179✔
1840
            m_alloc.detach();
163,185✔
1841

80,436✔
1842
        if (m_is_sync_agent) {
163,179✔
1843
            REALM_ASSERT(info->sync_agent_present);
1,530✔
1844
            info->sync_agent_present = 0; // Set to false
1,530✔
1845
        }
1,530✔
1846
        release_all_read_locks();
163,179✔
1847
        --info->num_participants;
163,179✔
1848
        bool end_of_session = info->num_participants == 0;
163,179✔
1849
        // std::cerr << "closing" << std::endl;
80,436✔
1850
        if (end_of_session) {
163,179✔
1851

68,892✔
1852
            // If the db file is just backing for a transient data structure,
68,892✔
1853
            // we can delete it when done.
68,892✔
1854
            if (Durability(info->durability) == Durability::MemOnly && !m_in_memory_info) {
139,872✔
1855
                try {
20,094✔
1856
                    util::File::remove(m_db_path.c_str());
20,094✔
1857
                }
20,094✔
1858
                catch (...) {
10,053✔
1859
                } // ignored on purpose.
12✔
1860
            }
20,094✔
1861
        }
139,872✔
1862
        lock.unlock();
163,179✔
1863
    }
163,179✔
1864
    {
163,179✔
1865
        CheckedLockGuard local_lock(m_mutex);
163,179✔
1866

80,436✔
1867
        m_new_commit_available.close();
163,179✔
1868
        m_pick_next_writer.close();
163,179✔
1869

80,436✔
1870
        if (m_in_memory_info) {
163,179✔
1871
            m_in_memory_info.reset();
25,368✔
1872
        }
25,368✔
1873
        else {
137,811✔
1874
            // On Windows it is important that we unmap before unlocking, else a SetEndOfFile() call from another
67,752✔
1875
            // thread may interleave which is not permitted on Windows. It is permitted on *nix.
67,752✔
1876
            m_file_map.unmap();
137,811✔
1877
            m_version_manager.reset();
137,811✔
1878
            m_file.rw_unlock();
137,811✔
1879
            // info->~SharedInfo(); // DO NOT Call destructor
67,752✔
1880
            m_file.close();
137,811✔
1881
        }
137,811✔
1882
        m_info = nullptr;
163,179✔
1883
        if (m_logger)
163,179✔
1884
            m_logger->log(util::Logger::Level::detail, "DB closed");
149,028✔
1885
    }
163,179✔
1886
}
163,179✔
1887

1888
bool DB::other_writers_waiting_for_lock() const
1889
{
64,887✔
1890
    SharedInfo* info = m_info;
64,887✔
1891

34,134✔
1892
    uint32_t next_ticket = info->next_ticket.load(std::memory_order_relaxed);
64,887✔
1893
    uint32_t next_served = info->next_served.load(std::memory_order_relaxed);
64,887✔
1894
    // When holding the write lock, next_ticket = next_served + 1, hence, if the diference between 'next_ticket' and
34,134✔
1895
    // 'next_served' is greater than 1, there is at least one thread waiting to acquire the write lock.
34,134✔
1896
    return next_ticket > next_served + 1;
64,887✔
1897
}
64,887✔
1898

1899
class DB::AsyncCommitHelper {
1900
public:
1901
    AsyncCommitHelper(DB* db)
1902
        : m_db(db)
1903
    {
125,109✔
1904
    }
125,109✔
1905
    ~AsyncCommitHelper()
1906
    {
125,109✔
1907
        {
125,109✔
1908
            std::unique_lock lg(m_mutex);
125,109✔
1909
            if (!m_running) {
125,109✔
1910
                return;
77,058✔
1911
            }
77,058✔
1912
            m_running = false;
48,051✔
1913
            m_cv_worker.notify_one();
48,051✔
1914
        }
48,051✔
1915
        m_thread.join();
48,051✔
1916
    }
48,051✔
1917

1918
    void begin_write(util::UniqueFunction<void()> fn)
1919
    {
1,614✔
1920
        std::unique_lock lg(m_mutex);
1,614✔
1921
        start_thread();
1,614✔
1922
        m_pending_writes.emplace_back(std::move(fn));
1,614✔
1923
        m_cv_worker.notify_one();
1,614✔
1924
    }
1,614✔
1925

1926
    void blocking_begin_write()
1927
    {
257,694✔
1928
        std::unique_lock lg(m_mutex);
257,694✔
1929

126,834✔
1930
        // If we support unlocking InterprocessMutex from a different thread
126,834✔
1931
        // than it was locked on, we can sometimes just begin the write on
126,834✔
1932
        // the current thread. This requires that no one is currently waiting
126,834✔
1933
        // for the worker thread to acquire the write lock, as we'll deadlock
126,834✔
1934
        // if we try to async commit while the worker is waiting for the lock.
126,834✔
1935
        bool can_lock_on_caller =
257,694✔
1936
            !InterprocessMutex::is_thread_confined && (!m_owns_write_mutex && m_pending_writes.empty() &&
257,694✔
1937
                                                       m_write_lock_claim_ticket == m_write_lock_claim_fulfilled);
130,800✔
1938

126,834✔
1939
        // If we support cross-thread unlocking and m_running is false,
126,834✔
1940
        // can_lock_on_caller should always be true or we forgot to launch the thread
126,834✔
1941
        REALM_ASSERT(can_lock_on_caller || m_running || InterprocessMutex::is_thread_confined);
257,694✔
1942

126,834✔
1943
        // If possible, just begin the write on the current thread
126,834✔
1944
        if (can_lock_on_caller) {
257,694✔
1945
            m_waiting_for_write_mutex = true;
130,800✔
1946
            lg.unlock();
130,800✔
1947
            m_db->do_begin_write();
130,800✔
1948
            lg.lock();
130,800✔
1949
            m_waiting_for_write_mutex = false;
130,800✔
1950
            m_has_write_mutex = true;
130,800✔
1951
            m_owns_write_mutex = false;
130,800✔
1952
            return;
130,800✔
1953
        }
130,800✔
1954

126,834✔
1955
        // Otherwise we have to ask the worker thread to acquire it and wait
126,834✔
1956
        // for that
126,834✔
1957
        start_thread();
126,894✔
1958
        size_t ticket = ++m_write_lock_claim_ticket;
126,894✔
1959
        m_cv_worker.notify_one();
126,894✔
1960
        m_cv_callers.wait(lg, [this, ticket] {
254,637✔
1961
            return ticket == m_write_lock_claim_fulfilled;
254,637✔
1962
        });
254,637✔
1963
    }
126,894✔
1964

1965
    void end_write()
1966
    {
54✔
1967
        std::unique_lock lg(m_mutex);
54✔
1968
        REALM_ASSERT(m_has_write_mutex);
54✔
1969
        REALM_ASSERT(m_owns_write_mutex || !InterprocessMutex::is_thread_confined);
54✔
1970

27✔
1971
        // If we acquired the write lock on the worker thread, also release it
27✔
1972
        // there even if our mutex supports unlocking cross-thread as it simplifies things.
27✔
1973
        if (m_owns_write_mutex) {
54✔
1974
            m_pending_mx_release = true;
51✔
1975
            m_cv_worker.notify_one();
51✔
1976
        }
51✔
1977
        else {
3✔
1978
            m_db->do_end_write();
3✔
1979
            m_has_write_mutex = false;
3✔
1980
        }
3✔
1981
    }
54✔
1982

1983
    bool blocking_end_write()
1984
    {
303,819✔
1985
        std::unique_lock lg(m_mutex);
303,819✔
1986
        if (!m_has_write_mutex) {
303,819✔
1987
            return false;
45,921✔
1988
        }
45,921✔
1989
        REALM_ASSERT(m_owns_write_mutex || !InterprocessMutex::is_thread_confined);
257,898✔
1990

126,894✔
1991
        // If we acquired the write lock on the worker thread, also release it
126,894✔
1992
        // there even if our mutex supports unlocking cross-thread as it simplifies things.
126,894✔
1993
        if (m_owns_write_mutex) {
257,898✔
1994
            m_pending_mx_release = true;
127,419✔
1995
            m_cv_worker.notify_one();
127,419✔
1996
            m_cv_callers.wait(lg, [this] {
254,838✔
1997
                return !m_pending_mx_release;
254,838✔
1998
            });
254,838✔
1999
        }
127,419✔
2000
        else {
130,479✔
2001
            m_db->do_end_write();
130,479✔
2002
            m_has_write_mutex = false;
130,479✔
2003

2004
            // The worker thread may have ignored a request for the write mutex
2005
            // while we were acquiring it, so we need to wake up the thread
2006
            if (has_pending_write_requests()) {
130,479✔
2007
                lg.unlock();
×
2008
                m_cv_worker.notify_one();
×
2009
            }
×
2010
        }
130,479✔
2011
        return true;
257,898✔
2012
    }
257,898✔
2013

2014

2015
    void sync_to_disk(util::UniqueFunction<void()> fn)
2016
    {
1,356✔
2017
        REALM_ASSERT(fn);
1,356✔
2018
        std::unique_lock lg(m_mutex);
1,356✔
2019
        REALM_ASSERT(!m_pending_sync);
1,356✔
2020
        start_thread();
1,356✔
2021
        m_pending_sync = std::move(fn);
1,356✔
2022
        m_cv_worker.notify_one();
1,356✔
2023
    }
1,356✔
2024

2025
private:
2026
    DB* m_db;
2027
    std::thread m_thread;
2028
    std::mutex m_mutex;
2029
    std::condition_variable m_cv_worker;
2030
    std::condition_variable m_cv_callers;
2031
    std::deque<util::UniqueFunction<void()>> m_pending_writes;
2032
    util::UniqueFunction<void()> m_pending_sync;
2033
    size_t m_write_lock_claim_ticket = 0;
2034
    size_t m_write_lock_claim_fulfilled = 0;
2035
    bool m_pending_mx_release = false;
2036
    bool m_running = false;
2037
    bool m_has_write_mutex = false;
2038
    bool m_owns_write_mutex = false;
2039
    bool m_waiting_for_write_mutex = false;
2040

2041
    void main();
2042

2043
    void start_thread()
2044
    {
129,864✔
2045
        if (m_running) {
129,864✔
2046
            return;
81,813✔
2047
        }
81,813✔
2048
        m_running = true;
48,051✔
2049
        m_thread = std::thread([this]() {
48,051✔
2050
            main();
48,051✔
2051
        });
48,051✔
2052
    }
48,051✔
2053

2054
    bool has_pending_write_requests()
2055
    {
380,280✔
2056
        return m_write_lock_claim_fulfilled < m_write_lock_claim_ticket || !m_pending_writes.empty();
380,280✔
2057
    }
380,280✔
2058
};
2059

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

127,227✔
2086
                lg.unlock();
128,826✔
2087
                m_cv_callers.notify_all();
128,826✔
2088
                lg.lock();
128,826✔
2089
                continue;
128,826✔
2090
            }
128,826✔
2091
        }
249,951✔
2092
        else {
249,951✔
2093
            REALM_ASSERT(!m_pending_sync && !m_pending_mx_release);
249,951✔
2094

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

127,227✔
2104
                REALM_ASSERT(!m_has_write_mutex);
128,508✔
2105
                m_has_write_mutex = true;
128,508✔
2106
                m_owns_write_mutex = true;
128,508✔
2107

127,227✔
2108
                // Synchronous transaction requests get priority over async
127,227✔
2109
                if (m_write_lock_claim_fulfilled < m_write_lock_claim_ticket) {
128,508✔
2110
                    ++m_write_lock_claim_fulfilled;
126,894✔
2111
                    m_cv_callers.notify_all();
126,894✔
2112
                    continue;
126,894✔
2113
                }
126,894✔
2114

393✔
2115
                REALM_ASSERT(!m_pending_writes.empty());
1,614✔
2116
                auto callback = std::move(m_pending_writes.front());
1,614✔
2117
                m_pending_writes.pop_front();
1,614✔
2118
                lg.unlock();
1,614✔
2119
                callback();
1,614✔
2120
                // Release things captured by the callback before reacquiring the lock
393✔
2121
                callback = nullptr;
1,614✔
2122
                lg.lock();
1,614✔
2123
                continue;
1,614✔
2124
            }
1,614✔
2125
        }
249,951✔
2126
        m_cv_worker.wait(lg);
257,013✔
2127
    }
257,013✔
2128
    if (m_has_write_mutex && m_owns_write_mutex) {
48,051!
2129
        m_db->do_end_write();
×
2130
    }
×
2131
}
48,051✔
2132

2133

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

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

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

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

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

2170

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

2180

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

2188
void DB::upgrade_file_format(bool allow_file_format_upgrade, int target_file_format_version,
2189
                             int current_hist_schema_version, int target_hist_schema_version)
2190
{
87,303✔
2191
    // In a multithreaded scenario multiple threads may initially see a need to
43,155✔
2192
    // upgrade (maybe_upgrade == true) even though one onw thread is supposed to
43,155✔
2193
    // perform the upgrade, but that is ok, because the condition is rechecked
43,155✔
2194
    // in a fully reliable way inside a transaction.
43,155✔
2195

43,155✔
2196
    // First a non-threadsafe but fast check
43,155✔
2197
    int current_file_format_version = m_file_format_version;
87,303✔
2198
    REALM_ASSERT(current_file_format_version <= target_file_format_version);
87,303✔
2199
    REALM_ASSERT(current_hist_schema_version <= target_hist_schema_version);
87,303✔
2200
    bool maybe_upgrade_file_format = (current_file_format_version < target_file_format_version);
87,303✔
2201
    bool maybe_upgrade_hist_schema = (current_hist_schema_version < target_hist_schema_version);
87,303✔
2202
    bool maybe_upgrade = maybe_upgrade_file_format || maybe_upgrade_hist_schema;
87,303✔
2203
    if (maybe_upgrade) {
87,303✔
2204

141✔
2205
#ifdef REALM_DEBUG
279✔
2206
// This sleep() only exists in order to increase the quality of the
141✔
2207
// TEST(Upgrade_Database_2_3_Writes_New_File_Format_new) unit test.
141✔
2208
// The unit test creates multiple threads that all call
141✔
2209
// upgrade_file_format() simultaneously. This sleep() then acts like
141✔
2210
// a simple thread barrier that makes sure the threads meet here, to
141✔
2211
// increase the likelyhood of detecting any potential race problems.
141✔
2212
// See the unit test for details.
141✔
2213
//
141✔
2214
// NOTE: This sleep has been disabled because no problems have been found with
141✔
2215
// this code in a long while, and it was dramatically slowing down a unit test
141✔
2216
// in realm-sync.
141✔
2217

141✔
2218
// millisleep(200);
141✔
2219
#endif
279✔
2220

141✔
2221
        // WriteTransaction wt(*this);
141✔
2222
        auto wt = start_write();
279✔
2223
        bool dirty = false;
279✔
2224

141✔
2225
        // We need to upgrade history first. We may need to access it during migration
141✔
2226
        // when processing the !OID columns
141✔
2227
        int current_hist_schema_version_2 = wt->get_history_schema_version();
279✔
2228
        // The history must either still be using its initial schema or have
141✔
2229
        // been upgraded already to the chosen target schema version via a
141✔
2230
        // concurrent DB object.
141✔
2231
        REALM_ASSERT(current_hist_schema_version_2 == current_hist_schema_version ||
279!
2232
                     current_hist_schema_version_2 == target_hist_schema_version);
279✔
2233
        bool need_hist_schema_upgrade = (current_hist_schema_version_2 < target_hist_schema_version);
279✔
2234
        if (need_hist_schema_upgrade) {
279✔
2235
            if (!allow_file_format_upgrade)
192✔
2236
                throw FileFormatUpgradeRequired(this->m_db_path);
×
2237

96✔
2238
            Replication* repl = get_replication();
192✔
2239
            repl->upgrade_history_schema(current_hist_schema_version_2); // Throws
192✔
2240
            wt->set_history_schema_version(target_hist_schema_version);  // Throws
192✔
2241
            dirty = true;
192✔
2242
        }
192✔
2243

141✔
2244
        // File format upgrade
141✔
2245
        int current_file_format_version_2 = m_alloc.get_committed_file_format_version();
279✔
2246
        // The file must either still be using its initial file_format or have
141✔
2247
        // been upgraded already to the chosen target file format via a
141✔
2248
        // concurrent DB object.
141✔
2249
        REALM_ASSERT(current_file_format_version_2 == current_file_format_version ||
279!
2250
                     current_file_format_version_2 == target_file_format_version);
279✔
2251
        bool need_file_format_upgrade = (current_file_format_version_2 < target_file_format_version);
279✔
2252
        if (need_file_format_upgrade) {
279✔
2253
            if (!allow_file_format_upgrade)
156✔
2254
                throw FileFormatUpgradeRequired(this->m_db_path);
×
2255
            wt->upgrade_file_format(target_file_format_version); // Throws
156✔
2256
            // Note: The file format version stored in the Realm file will be
78✔
2257
            // updated to the new file format version as part of the following
78✔
2258
            // commit operation. This happens in GroupWriter::commit().
78✔
2259
            if (m_upgrade_callback)
156✔
2260
                m_upgrade_callback(current_file_format_version_2, target_file_format_version); // Throws
18✔
2261
            dirty = true;
156✔
2262
        }
156✔
2263
        wt->set_file_format_version(target_file_format_version);
279✔
2264
        m_file_format_version = target_file_format_version;
279✔
2265

141✔
2266
        if (dirty)
279✔
2267
            wt->commit(); // Throws
270✔
2268
    }
279✔
2269
}
87,303✔
2270

2271
void DB::release_read_lock(ReadLockInfo& read_lock) noexcept
2272
{
9,582,021✔
2273
    // ignore if opened with immutable file (then we have no lockfile)
7,329,261✔
2274
    if (m_fake_read_lock_if_immutable)
9,582,021✔
2275
        return;
366✔
2276
    CheckedLockGuard lock(m_mutex); // mx on m_local_locks_held
9,581,655✔
2277
    do_release_read_lock(read_lock);
9,581,655✔
2278
}
9,581,655✔
2279

2280
// this is called with m_mutex locked
2281
void DB::do_release_read_lock(ReadLockInfo& read_lock) noexcept
2282
{
10,188,723✔
2283
    REALM_ASSERT(!m_fake_read_lock_if_immutable);
10,188,723✔
2284
    bool found_match = false;
10,188,723✔
2285
    // simple linear search and move-last-over if a match is found.
7,936,071✔
2286
    // common case should have only a modest number of transactions in play..
7,936,071✔
2287
    for (size_t j = 0; j < m_local_locks_held.size(); ++j) {
19,417,722✔
2288
        if (m_local_locks_held[j].m_version == read_lock.m_version) {
19,417,488✔
2289
            m_local_locks_held[j] = m_local_locks_held.back();
10,188,519✔
2290
            m_local_locks_held.pop_back();
10,188,519✔
2291
            found_match = true;
10,188,519✔
2292
            break;
10,188,519✔
2293
        }
10,188,519✔
2294
    }
19,417,488✔
2295
    if (!found_match) {
10,188,723✔
2296
        REALM_ASSERT(!is_attached());
6✔
2297
        // it's OK, someone called close() and all locks where released
3✔
2298
        return;
6✔
2299
    }
6✔
2300
    --m_transaction_count;
10,188,717✔
2301
    m_version_manager->release_read_lock(read_lock);
10,188,717✔
2302
}
10,188,717✔
2303

2304

2305
DB::ReadLockInfo DB::grab_read_lock(ReadLockInfo::Type type, VersionID version_id)
2306
{
10,175,961✔
2307
    CheckedLockGuard lock(m_mutex); // mx on m_local_locks_held
10,175,961✔
2308
    REALM_ASSERT_RELEASE(is_attached());
10,175,961✔
2309
    auto read_lock = m_version_manager->grab_read_lock(type, version_id);
10,175,961✔
2310

7,923,519✔
2311
    m_local_locks_held.emplace_back(read_lock);
10,175,961✔
2312
    ++m_transaction_count;
10,175,961✔
2313
    REALM_ASSERT(read_lock.m_file_size > read_lock.m_top_ref);
10,175,961✔
2314
    return read_lock;
10,175,961✔
2315
}
10,175,961✔
2316

2317
void DB::leak_read_lock(ReadLockInfo& read_lock) noexcept
2318
{
6✔
2319
    CheckedLockGuard lock(m_mutex); // mx on m_local_locks_held
6✔
2320
    // simple linear search and move-last-over if a match is found.
3✔
2321
    // common case should have only a modest number of transactions in play..
3✔
2322
    for (size_t j = 0; j < m_local_locks_held.size(); ++j) {
6✔
2323
        if (m_local_locks_held[j].m_version == read_lock.m_version) {
6✔
2324
            m_local_locks_held[j] = m_local_locks_held.back();
6✔
2325
            m_local_locks_held.pop_back();
6✔
2326
            --m_transaction_count;
6✔
2327
            return;
6✔
2328
        }
6✔
2329
    }
6✔
2330
}
6✔
2331

2332
bool DB::do_try_begin_write()
2333
{
84✔
2334
    // In the non-blocking case, we will only succeed if there is no contention for
42✔
2335
    // the write mutex. For this case we are trivially fair and can ignore the
42✔
2336
    // fairness machinery.
42✔
2337
    bool got_the_lock = m_writemutex.try_lock();
84✔
2338
    if (got_the_lock) {
84✔
2339
        finish_begin_write();
72✔
2340
    }
72✔
2341
    return got_the_lock;
84✔
2342
}
84✔
2343

2344
void DB::do_begin_write()
2345
{
1,385,589✔
2346
    if (m_logger) {
1,385,589✔
2347
        m_logger->log(util::LogCategory::transaction, util::Logger::Level::trace, "acquire writemutex");
305,559✔
2348
    }
305,559✔
2349

698,610✔
2350
    SharedInfo* info = m_info;
1,385,589✔
2351

698,610✔
2352
    // Get write lock - the write lock is held until do_end_write().
698,610✔
2353
    //
698,610✔
2354
    // We use a ticketing scheme to ensure fairness wrt performing write transactions.
698,610✔
2355
    // (But cannot do that on Windows until we have interprocess condition variables there)
698,610✔
2356
    uint32_t my_ticket = info->next_ticket.fetch_add(1, std::memory_order_relaxed);
1,385,589✔
2357
    m_writemutex.lock(); // Throws
1,385,589✔
2358

698,610✔
2359
    // allow for comparison even after wrap around of ticket numbering:
698,610✔
2360
    int32_t diff = int32_t(my_ticket - info->next_served.load(std::memory_order_relaxed));
1,385,589✔
2361
    bool should_yield = diff > 0; // ticket is in the future
1,385,589✔
2362
    // a) the above comparison is only guaranteed to be correct, if the distance
698,610✔
2363
    //    between my_ticket and info->next_served is less than 2^30. This will
698,610✔
2364
    //    be the case since the distance will be bounded by the number of threads
698,610✔
2365
    //    and each thread cannot ever hold more than one ticket.
698,610✔
2366
    // b) we could use 64 bit counters instead, but it is unclear if all platforms
698,610✔
2367
    //    have support for interprocess atomics for 64 bit values.
698,610✔
2368

698,610✔
2369
    timespec time_limit; // only compute the time limit if we're going to use it:
1,385,589✔
2370
    if (should_yield) {
1,385,589✔
2371
        // This clock is not monotonic, so time can move backwards. This can lead
20,328✔
2372
        // to a wrong time limit, but the only effect of a wrong time limit is that
20,328✔
2373
        // we momentarily lose fairness, so we accept it.
20,328✔
2374
        timeval tv;
21,354✔
2375
        gettimeofday(&tv, nullptr);
21,354✔
2376
        time_limit.tv_sec = tv.tv_sec;
21,354✔
2377
        time_limit.tv_nsec = tv.tv_usec * 1000;
21,354✔
2378
        time_limit.tv_nsec += 500000000;        // 500 msec wait
21,354✔
2379
        if (time_limit.tv_nsec >= 1000000000) { // overflow
21,354✔
2380
            time_limit.tv_nsec -= 1000000000;
11,421✔
2381
            time_limit.tv_sec += 1;
11,421✔
2382
        }
11,421✔
2383
    }
21,354✔
2384

698,610✔
2385
    while (should_yield) {
1,512,684✔
2386

125,460✔
2387
        m_pick_next_writer.wait(m_writemutex, &time_limit);
127,755✔
2388
        timeval tv;
127,755✔
2389
        gettimeofday(&tv, nullptr);
127,755✔
2390
        if (time_limit.tv_sec < tv.tv_sec ||
127,755✔
2391
            (time_limit.tv_sec == tv.tv_sec && time_limit.tv_nsec < tv.tv_usec * 1000)) {
127,755!
2392
            // Timeout!
660✔
2393
            break;
660✔
2394
        }
660✔
2395
        diff = int32_t(my_ticket - info->next_served);
127,095✔
2396
        should_yield = diff > 0; // ticket is in the future, so yield to someone else
127,095✔
2397
    }
127,095✔
2398

698,610✔
2399
    // we may get here because a) it's our turn, b) we timed out
698,610✔
2400
    // we don't distinguish, satisfied that event b) should be rare.
698,610✔
2401
    // In case b), we have to *make* it our turn. Failure to do so could leave us
698,610✔
2402
    // with 'next_served' permanently trailing 'next_ticket'.
698,610✔
2403
    //
698,610✔
2404
    // In doing so, we may bypass other waiters, hence the condition for yielding
698,610✔
2405
    // should take this situation into account by comparing with '>' instead of '!='
698,610✔
2406
    info->next_served = my_ticket;
1,385,589✔
2407
    finish_begin_write();
1,385,589✔
2408
    if (m_logger) {
1,385,589✔
2409
        m_logger->log(util::LogCategory::transaction, util::Logger::Level::trace, "writemutex acquired");
305,559✔
2410
    }
305,559✔
2411
}
1,385,589✔
2412

2413
void DB::finish_begin_write()
2414
{
1,385,646✔
2415
    if (m_info->commit_in_critical_phase) {
1,385,646✔
2416
        m_writemutex.unlock();
×
2417
        throw RuntimeError(ErrorCodes::BrokenInvariant, "Crash of other process detected, session restart required");
×
2418
    }
×
2419

698,664✔
2420

698,664✔
2421
    {
1,385,646✔
2422
        CheckedLockGuard local_lock(m_mutex);
1,385,646✔
2423
        m_write_transaction_open = true;
1,385,646✔
2424
    }
1,385,646✔
2425
    m_alloc.set_read_only(false);
1,385,646✔
2426
}
1,385,646✔
2427

2428
void DB::do_end_write() noexcept
2429
{
1,385,673✔
2430
    m_info->next_served.fetch_add(1, std::memory_order_relaxed);
1,385,673✔
2431

698,673✔
2432
    CheckedLockGuard local_lock(m_mutex);
1,385,673✔
2433
    REALM_ASSERT(m_write_transaction_open);
1,385,673✔
2434
    m_alloc.set_read_only(true);
1,385,673✔
2435
    m_write_transaction_open = false;
1,385,673✔
2436
    m_pick_next_writer.notify_all();
1,385,673✔
2437
    m_writemutex.unlock();
1,385,673✔
2438
    if (m_logger) {
1,385,673✔
2439
        m_logger->log(util::LogCategory::transaction, util::Logger::Level::trace, "writemutex released");
305,607✔
2440
    }
305,607✔
2441
}
1,385,673✔
2442

2443

2444
Replication::version_type DB::do_commit(Transaction& transaction, bool commit_to_disk)
2445
{
1,362,243✔
2446
    version_type current_version;
1,362,243✔
2447
    {
1,362,243✔
2448
        current_version = m_version_manager->get_newest_version();
1,362,243✔
2449
    }
1,362,243✔
2450
    version_type new_version = current_version + 1;
1,362,243✔
2451

686,928✔
2452
    if (!transaction.m_tables_to_clear.empty()) {
1,362,243✔
2453
        for (auto table_key : transaction.m_tables_to_clear) {
678✔
2454
            transaction.get_table_unchecked(table_key)->clear();
678✔
2455
        }
678✔
2456
        transaction.m_tables_to_clear.clear();
678✔
2457
    }
678✔
2458
    if (Replication* repl = get_replication()) {
1,362,243✔
2459
        // If Replication::prepare_commit() fails, then the entire transaction
678,234✔
2460
        // fails. The application then has the option of terminating the
678,234✔
2461
        // transaction with a call to Transaction::Rollback(), which in turn
678,234✔
2462
        // must call Replication::abort_transact().
678,234✔
2463
        new_version = repl->prepare_commit(current_version);        // Throws
1,344,789✔
2464
        low_level_commit(new_version, transaction, commit_to_disk); // Throws
1,344,789✔
2465
        repl->finalize_commit();
1,344,789✔
2466
    }
1,344,789✔
2467
    else {
17,454✔
2468
        low_level_commit(new_version, transaction); // Throws
17,454✔
2469
    }
17,454✔
2470

686,928✔
2471
    {
1,362,243✔
2472
        std::lock_guard lock(m_commit_listener_mutex);
1,362,243✔
2473
        for (auto listener : m_commit_listeners) {
896,088✔
2474
            listener->on_commit(new_version);
415,359✔
2475
        }
415,359✔
2476
    }
1,362,243✔
2477

686,928✔
2478
    return new_version;
1,362,243✔
2479
}
1,362,243✔
2480

2481
VersionID DB::get_version_id_of_latest_snapshot()
2482
{
1,331,403✔
2483
    if (m_fake_read_lock_if_immutable)
1,331,403✔
2484
        return {m_fake_read_lock_if_immutable->m_version, 0};
12✔
2485
    return m_version_manager->get_version_id_of_latest_snapshot();
1,331,391✔
2486
}
1,331,391✔
2487

2488

2489
DB::version_type DB::get_version_of_latest_snapshot()
2490
{
1,330,854✔
2491
    return get_version_id_of_latest_snapshot().version;
1,330,854✔
2492
}
1,330,854✔
2493

2494

2495
void DB::low_level_commit(uint_fast64_t new_version, Transaction& transaction, bool commit_to_disk)
2496
{
1,362,294✔
2497
    SharedInfo* info = m_info;
1,362,294✔
2498

686,976✔
2499
    // Version of oldest snapshot currently (or recently) bound in a transaction
686,976✔
2500
    // of the current session.
686,976✔
2501
    uint64_t oldest_version = 0, oldest_live_version = 0;
1,362,294✔
2502
    TopRefMap top_refs;
1,362,294✔
2503
    bool any_new_unreachables;
1,362,294✔
2504
    {
1,362,294✔
2505
        CheckedLockGuard lock(m_mutex);
1,362,294✔
2506
        m_version_manager->cleanup_versions(oldest_live_version, top_refs, any_new_unreachables);
1,362,294✔
2507
        oldest_version = top_refs.begin()->first;
1,362,294✔
2508
        // Allow for trimming of the history. Some types of histories do not
686,976✔
2509
        // need store changesets prior to the oldest *live* bound snapshot.
686,976✔
2510
        if (auto hist = transaction.get_history()) {
1,362,294✔
2511
            hist->set_oldest_bound_version(oldest_live_version); // Throws
1,344,780✔
2512
        }
1,344,780✔
2513
        // Cleanup any stale mappings
686,976✔
2514
        m_alloc.purge_old_mappings(oldest_version, new_version);
1,362,294✔
2515
    }
1,362,294✔
2516
    // save number of live versions for later:
686,976✔
2517
    // (top_refs is std::moved into GroupWriter so we'll loose it in the call to set_versions below)
686,976✔
2518
    auto live_versions = top_refs.size();
1,362,294✔
2519
    // Do the actual commit
686,976✔
2520
    REALM_ASSERT(oldest_version <= new_version);
1,362,294✔
2521

686,976✔
2522
    GroupWriter out(transaction, Durability(info->durability), m_marker_observer.get()); // Throws
1,362,294✔
2523
    out.set_versions(new_version, top_refs, any_new_unreachables);
1,362,294✔
2524
    out.prepare_evacuation();
1,362,294✔
2525
    auto t1 = std::chrono::steady_clock::now();
1,362,294✔
2526
    auto commit_size = m_alloc.get_commit_size();
1,362,294✔
2527
    if (m_logger) {
1,362,294✔
2528
        m_logger->log(util::LogCategory::transaction, util::Logger::Level::debug, "Initiate commit version: %1",
284,391✔
2529
                      new_version);
284,391✔
2530
    }
284,391✔
2531
    if (auto limit = out.get_evacuation_limit()) {
1,362,294✔
2532
        // Get a work limit based on the size of the transaction we're about to commit
2,643✔
2533
        // Add 4k to ensure progress on small commits
2,643✔
2534
        size_t work_limit = commit_size / 2 + out.get_free_list_size() + 0x1000;
5,325✔
2535
        transaction.cow_outliers(out.get_evacuation_progress(), limit, work_limit);
5,325✔
2536
    }
5,325✔
2537

686,976✔
2538
    ref_type new_top_ref;
1,362,294✔
2539
    // Recursively write all changed arrays to end of file
686,976✔
2540
    {
1,362,294✔
2541
        // protect against race with any other DB trying to attach to the file
686,976✔
2542
        std::lock_guard<InterprocessMutex> lock(m_controlmutex); // Throws
1,362,294✔
2543
        new_top_ref = out.write_group();                         // Throws
1,362,294✔
2544
    }
1,362,294✔
2545
    {
1,362,294✔
2546
        // protect access to shared variables and m_reader_mapping from here
686,976✔
2547
        CheckedLockGuard lock_guard(m_mutex);
1,362,294✔
2548
        m_free_space = out.get_free_space_size();
1,362,294✔
2549
        m_locked_space = out.get_locked_space_size();
1,362,294✔
2550
        m_used_space = out.get_logical_size() - m_free_space;
1,362,294✔
2551
        m_evac_stage.store(EvacStage(out.get_evacuation_stage()));
1,362,294✔
2552
        out.sync_according_to_durability();
1,362,294✔
2553
        if (Durability(info->durability) == Durability::Full || Durability(info->durability) == Durability::Unsafe) {
1,362,294✔
2554
            if (commit_to_disk) {
1,200,441✔
2555
                GroupCommitter cm(transaction, Durability(info->durability), m_marker_observer.get());
1,192,908✔
2556
                cm.commit(new_top_ref);
1,192,908✔
2557
            }
1,192,908✔
2558
        }
1,200,441✔
2559
        size_t new_file_size = out.get_logical_size();
1,362,294✔
2560
        // We must reset the allocators free space tracking before communicating the new
686,976✔
2561
        // version through the ring buffer. If not, a reader may start updating the allocators
686,976✔
2562
        // mappings while the allocator is in dirty state.
686,976✔
2563
        reset_free_space_tracking();
1,362,294✔
2564
        // Add the new version. If this fails in any way, the VersionList may be corrupted.
686,976✔
2565
        // This can lead to readers seing invalid data which is likely to cause them
686,976✔
2566
        // to crash. Other writers *must* be prevented from writing any further updates
686,976✔
2567
        // to the database. The flag "commit_in_critical_phase" is used to prevent such updates.
686,976✔
2568
        info->commit_in_critical_phase = 1;
1,362,294✔
2569
        {
1,362,294✔
2570
            m_version_manager->add_version(new_top_ref, new_file_size, new_version);
1,362,294✔
2571

686,976✔
2572
            // REALM_ASSERT(m_alloc.matches_section_boundary(new_file_size));
686,976✔
2573
            REALM_ASSERT(new_top_ref < new_file_size);
1,362,294✔
2574
        }
1,362,294✔
2575
        // At this point, the VersionList has been succesfully updated, and the next writer
686,976✔
2576
        // can safely proceed once the writemutex has been lifted.
686,976✔
2577
        info->commit_in_critical_phase = 0;
1,362,294✔
2578
    }
1,362,294✔
2579
    {
1,362,294✔
2580
        // protect against concurrent updates to the .lock file.
686,976✔
2581
        // must release m_mutex before this point to obey lock order
686,976✔
2582
        std::lock_guard<InterprocessMutex> lock(m_controlmutex);
1,362,294✔
2583

686,976✔
2584
        info->number_of_versions = live_versions + 1;
1,362,294✔
2585
        info->latest_version_number = new_version;
1,362,294✔
2586

686,976✔
2587
        m_new_commit_available.notify_all();
1,362,294✔
2588
    }
1,362,294✔
2589
    auto t2 = std::chrono::steady_clock::now();
1,362,294✔
2590
    if (m_logger) {
1,362,294✔
2591
        std::string to_disk_str = commit_to_disk ? util::format(" ref %1", new_top_ref) : " (no commit to disk)";
280,254✔
2592
        m_logger->log(util::LogCategory::transaction, util::Logger::Level::debug, "Commit of size %1 done in %2 us%3",
284,391✔
2593
                      commit_size, std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count(),
284,391✔
2594
                      to_disk_str);
284,391✔
2595
    }
284,391✔
2596
}
1,362,294✔
2597

2598
#ifdef REALM_DEBUG
2599
void DB::reserve(size_t size)
2600
{
36✔
2601
    REALM_ASSERT(is_attached());
36✔
2602
    m_alloc.reserve_disk_space(size); // Throws
36✔
2603
}
36✔
2604
#endif
2605

2606
bool DB::call_with_lock(const std::string& realm_path, CallbackWithLock&& callback)
2607
{
693✔
2608
    auto lockfile_path = get_core_file(realm_path, CoreFileType::Lock);
693✔
2609

306✔
2610
    File lockfile;
693✔
2611
    lockfile.open(lockfile_path, File::access_ReadWrite, File::create_Auto, 0); // Throws
693✔
2612
    File::CloseGuard fcg(lockfile);
693✔
2613
    lockfile.set_fifo_path(realm_path + ".management", "lock.fifo");
693✔
2614
    if (lockfile.try_rw_lock_exclusive()) { // Throws
693✔
2615
        callback(realm_path);
651✔
2616
        return true;
651✔
2617
    }
651✔
2618
    return false;
42✔
2619
}
42✔
2620

2621
std::string DB::get_core_file(const std::string& base_path, CoreFileType type)
2622
{
296,979✔
2623
    switch (type) {
296,979✔
2624
        case CoreFileType::Lock:
138,864✔
2625
            return base_path + ".lock";
138,864✔
2626
        case CoreFileType::Storage:
738✔
2627
            return base_path;
738✔
2628
        case CoreFileType::Management:
138,717✔
2629
            return base_path + ".management";
138,717✔
2630
        case CoreFileType::Note:
17,922✔
2631
            return base_path + ".note";
17,922✔
2632
        case CoreFileType::Log:
738✔
2633
            return base_path + ".log";
738✔
2634
    }
×
2635
    REALM_UNREACHABLE();
×
2636
}
×
2637

2638
void DB::delete_files(const std::string& base_path, bool* did_delete, bool delete_lockfile)
2639
{
732✔
2640
    if (File::try_remove(get_core_file(base_path, CoreFileType::Storage)) && did_delete) {
732✔
2641
        *did_delete = true;
174✔
2642
    }
174✔
2643

366✔
2644
    File::try_remove(get_core_file(base_path, CoreFileType::Note));
732✔
2645
    File::try_remove(get_core_file(base_path, CoreFileType::Log));
732✔
2646
    util::try_remove_dir_recursive(get_core_file(base_path, CoreFileType::Management));
732✔
2647

366✔
2648
    if (delete_lockfile) {
732✔
2649
        File::try_remove(get_core_file(base_path, CoreFileType::Lock));
186✔
2650
    }
186✔
2651
}
732✔
2652

2653
TransactionRef DB::start_read(VersionID version_id)
2654
{
2,048,088✔
2655
    if (!is_attached())
2,048,088✔
2656
        throw StaleAccessor("Stale transaction");
6✔
2657
    TransactionRef tr;
2,048,082✔
2658
    if (m_fake_read_lock_if_immutable) {
2,048,082✔
2659
        tr = make_transaction_ref(shared_from_this(), &m_alloc, *m_fake_read_lock_if_immutable, DB::transact_Reading);
354✔
2660
    }
354✔
2661
    else {
2,047,728✔
2662
        ReadLockInfo read_lock = grab_read_lock(ReadLockInfo::Live, version_id);
2,047,728✔
2663
        ReadLockGuard g(*this, read_lock);
2,047,728✔
2664
        read_lock.check();
2,047,728✔
2665
        tr = make_transaction_ref(shared_from_this(), &m_alloc, read_lock, DB::transact_Reading);
2,047,728✔
2666
        g.release();
2,047,728✔
2667
    }
2,047,728✔
2668
    tr->set_file_format_version(get_file_format_version());
2,048,082✔
2669
    return tr;
2,048,082✔
2670
}
2,048,082✔
2671

2672
TransactionRef DB::start_frozen(VersionID version_id)
2673
{
30,108✔
2674
    if (!is_attached())
30,108✔
2675
        throw StaleAccessor("Stale transaction");
×
2676
    TransactionRef tr;
30,108✔
2677
    if (m_fake_read_lock_if_immutable) {
30,108✔
2678
        tr = make_transaction_ref(shared_from_this(), &m_alloc, *m_fake_read_lock_if_immutable, DB::transact_Frozen);
12✔
2679
    }
12✔
2680
    else {
30,096✔
2681
        ReadLockInfo read_lock = grab_read_lock(ReadLockInfo::Frozen, version_id);
30,096✔
2682
        ReadLockGuard g(*this, read_lock);
30,096✔
2683
        read_lock.check();
30,096✔
2684
        tr = make_transaction_ref(shared_from_this(), &m_alloc, read_lock, DB::transact_Frozen);
30,096✔
2685
        g.release();
30,096✔
2686
    }
30,096✔
2687
    tr->set_file_format_version(get_file_format_version());
30,108✔
2688
    return tr;
30,108✔
2689
}
30,108✔
2690

2691
TransactionRef DB::start_write(bool nonblocking)
2692
{
1,000,890✔
2693
    if (m_fake_read_lock_if_immutable) {
1,000,890✔
2694
        REALM_ASSERT(false && "Can't write an immutable DB");
×
2695
    }
×
2696
    if (nonblocking) {
1,000,890✔
2697
        bool success = do_try_begin_write();
84✔
2698
        if (!success) {
84✔
2699
            return TransactionRef();
12✔
2700
        }
12✔
2701
    }
1,000,806✔
2702
    else {
1,000,806✔
2703
        do_begin_write();
1,000,806✔
2704
    }
1,000,806✔
2705
    {
1,000,884✔
2706
        CheckedUniqueLock local_lock(m_mutex);
1,000,878✔
2707
        if (!is_attached()) {
1,000,878✔
2708
            local_lock.unlock();
×
2709
            end_write_on_correct_thread();
×
2710
            throw StaleAccessor("Stale transaction");
×
2711
        }
×
2712
        m_write_transaction_open = true;
1,000,878✔
2713
    }
1,000,878✔
2714
    TransactionRef tr;
1,000,878✔
2715
    try {
1,000,878✔
2716
        ReadLockInfo read_lock = grab_read_lock(ReadLockInfo::Live, VersionID());
1,000,878✔
2717
        ReadLockGuard g(*this, read_lock);
1,000,878✔
2718
        read_lock.check();
1,000,878✔
2719

507,102✔
2720
        tr = make_transaction_ref(shared_from_this(), &m_alloc, read_lock, DB::transact_Writing);
1,000,878✔
2721
        tr->set_file_format_version(get_file_format_version());
1,000,878✔
2722
        version_type current_version = read_lock.m_version;
1,000,878✔
2723
        m_alloc.init_mapping_management(current_version);
1,000,878✔
2724
        if (Replication* repl = get_replication()) {
1,000,878✔
2725
            bool history_updated = false;
983,250✔
2726
            repl->initiate_transact(*tr, current_version, history_updated); // Throws
983,250✔
2727
        }
983,250✔
2728
        g.release();
1,000,878✔
2729
    }
1,000,878✔
2730
    catch (...) {
507,102✔
2731
        end_write_on_correct_thread();
×
2732
        throw;
×
2733
    }
×
2734

507,033✔
2735
    return tr;
1,000,770✔
2736
}
1,000,770✔
2737

2738
void DB::async_request_write_mutex(TransactionRef& tr, util::UniqueFunction<void()>&& when_acquired)
2739
{
1,614✔
2740
    {
1,614✔
2741
        util::CheckedLockGuard lck(tr->m_async_mutex);
1,614✔
2742
        REALM_ASSERT(tr->m_async_stage == Transaction::AsyncState::Idle);
1,614✔
2743
        tr->m_async_stage = Transaction::AsyncState::Requesting;
1,614✔
2744
        tr->m_request_time_point = std::chrono::steady_clock::now();
1,614✔
2745
        if (tr->db->m_logger) {
1,614✔
2746
            tr->db->m_logger->log(util::LogCategory::transaction, util::Logger::Level::trace,
1,614✔
2747
                                  "Tr %1: Async request write lock", tr->m_log_id);
1,614✔
2748
        }
1,614✔
2749
    }
1,614✔
2750
    std::weak_ptr<Transaction> weak_tr = tr;
1,614✔
2751
    async_begin_write([weak_tr, cb = std::move(when_acquired)]() {
1,614✔
2752
        if (auto tr = weak_tr.lock()) {
1,614✔
2753
            util::CheckedLockGuard lck(tr->m_async_mutex);
1,614✔
2754
            // If a synchronous transaction happened while we were pending
393✔
2755
            // we may be in HasCommits
393✔
2756
            if (tr->m_async_stage == Transaction::AsyncState::Requesting) {
1,614✔
2757
                tr->m_async_stage = Transaction::AsyncState::HasLock;
1,614✔
2758
            }
1,614✔
2759
            if (tr->db->m_logger) {
1,614✔
2760
                auto t2 = std::chrono::steady_clock::now();
1,614✔
2761
                tr->db->m_logger->log(
1,614✔
2762
                    util::LogCategory::transaction, util::Logger::Level::trace, "Tr %1, Got write lock in %2 us",
1,614✔
2763
                    tr->m_log_id,
1,614✔
2764
                    std::chrono::duration_cast<std::chrono::microseconds>(t2 - tr->m_request_time_point).count());
1,614✔
2765
            }
1,614✔
2766
            if (tr->m_waiting_for_write_lock) {
1,614✔
2767
                tr->m_waiting_for_write_lock = false;
129✔
2768
                tr->m_async_cv.notify_one();
129✔
2769
            }
129✔
2770
            else if (cb) {
1,485✔
2771
                cb();
1,485✔
2772
            }
1,485✔
2773
            tr.reset(); // Release pointer while lock is held
1,614✔
2774
        }
1,614✔
2775
    });
1,614✔
2776
}
1,614✔
2777

2778
inline DB::DB(const DBOptions& options)
2779
    : m_upgrade_callback(std::move(options.upgrade_callback))
2780
    , m_log_id(util::gen_log_id(this))
2781
{
163,530✔
2782
    if (options.enable_async_writes) {
163,530✔
2783
        m_commit_helper = std::make_unique<AsyncCommitHelper>(this);
125,109✔
2784
    }
125,109✔
2785
}
163,530✔
2786

2787
namespace {
2788
class DBInit : public DB {
2789
public:
2790
    explicit DBInit(const DBOptions& options)
2791
        : DB(options)
2792
    {
163,527✔
2793
    }
163,527✔
2794
};
2795
} // namespace
2796

2797
DBRef DB::create(const std::string& file, bool no_create, const DBOptions& options) NO_THREAD_SAFETY_ANALYSIS
2798
{
24,834✔
2799
    DBRef retval = std::make_shared<DBInit>(options);
24,834✔
2800
    retval->open(file, no_create, options);
24,834✔
2801
    return retval;
24,834✔
2802
}
24,834✔
2803

2804
DBRef DB::create(Replication& repl, const std::string& file, const DBOptions& options) NO_THREAD_SAFETY_ANALYSIS
2805
{
10,287✔
2806
    DBRef retval = std::make_shared<DBInit>(options);
10,287✔
2807
    retval->open(repl, file, options);
10,287✔
2808
    return retval;
10,287✔
2809
}
10,287✔
2810

2811
DBRef DB::create(std::unique_ptr<Replication> repl, const std::string& file,
2812
                 const DBOptions& options) NO_THREAD_SAFETY_ANALYSIS
2813
{
103,035✔
2814
    REALM_ASSERT(repl);
103,035✔
2815
    DBRef retval = std::make_shared<DBInit>(options);
103,035✔
2816
    retval->m_history = std::move(repl);
103,035✔
2817
    retval->open(*retval->m_history, file, options);
103,035✔
2818
    return retval;
103,035✔
2819
}
103,035✔
2820

2821
DBRef DB::create(std::unique_ptr<Replication> repl, const DBOptions& options) NO_THREAD_SAFETY_ANALYSIS
2822
{
25,368✔
2823
    REALM_ASSERT(repl);
25,368✔
2824
    DBRef retval = std::make_shared<DBInit>(options);
25,368✔
2825
    retval->m_history = std::move(repl);
25,368✔
2826
    retval->open(*retval->m_history, options);
25,368✔
2827
    return retval;
25,368✔
2828
}
25,368✔
2829

2830
DBRef DB::create_in_memory(std::unique_ptr<Replication> repl, const std::string& in_memory_path,
2831
                           const DBOptions& options) NO_THREAD_SAFETY_ANALYSIS
2832
{
×
2833
    DBRef db = create(std::move(repl), options);
×
2834
    db->m_db_path = in_memory_path;
×
2835
    return db;
×
2836
}
×
2837

2838
DBRef DB::create(BinaryData buffer, bool take_ownership) NO_THREAD_SAFETY_ANALYSIS
2839
{
6✔
2840
    DBOptions options;
6✔
2841
    options.is_immutable = true;
6✔
2842
    DBRef retval = std::make_shared<DBInit>(options);
6✔
2843
    retval->open(buffer, take_ownership);
6✔
2844
    return retval;
6✔
2845
}
6✔
2846

2847
void DB::claim_sync_agent()
2848
{
15,945✔
2849
    REALM_ASSERT(is_attached());
15,945✔
2850
    std::unique_lock<InterprocessMutex> lock(m_controlmutex);
15,945✔
2851
    if (m_info->sync_agent_present)
15,945✔
2852
        throw MultipleSyncAgents{};
6✔
2853
    m_info->sync_agent_present = 1; // Set to true
15,939✔
2854
    m_is_sync_agent = true;
15,939✔
2855
}
15,939✔
2856

2857
void DB::release_sync_agent()
2858
{
14,670✔
2859
    REALM_ASSERT(is_attached());
14,670✔
2860
    std::unique_lock<InterprocessMutex> lock(m_controlmutex);
14,670✔
2861
    if (!m_is_sync_agent)
14,670✔
2862
        return;
261✔
2863
    REALM_ASSERT(m_info->sync_agent_present);
14,409✔
2864
    m_info->sync_agent_present = 0;
14,409✔
2865
    m_is_sync_agent = false;
14,409✔
2866
}
14,409✔
2867

2868
void DB::do_begin_possibly_async_write()
2869
{
383,187✔
2870
    if (m_commit_helper) {
383,187✔
2871
        m_commit_helper->blocking_begin_write();
257,694✔
2872
    }
257,694✔
2873
    else {
125,493✔
2874
        do_begin_write();
125,493✔
2875
    }
125,493✔
2876
}
383,187✔
2877

2878
void DB::end_write_on_correct_thread() noexcept
2879
{
1,384,269✔
2880
    //    m_local_write_mutex.unlock();
698,340✔
2881
    if (!m_commit_helper || !m_commit_helper->blocking_end_write()) {
1,384,269✔
2882
        do_end_write();
1,126,371✔
2883
    }
1,126,371✔
2884
}
1,384,269✔
2885

2886
void DB::add_commit_listener(CommitListener* listener)
2887
{
139,824✔
2888
    std::lock_guard lock(m_commit_listener_mutex);
139,824✔
2889
    m_commit_listeners.push_back(listener);
139,824✔
2890
}
139,824✔
2891

2892
void DB::remove_commit_listener(CommitListener* listener)
2893
{
139,779✔
2894
    std::lock_guard lock(m_commit_listener_mutex);
139,779✔
2895
    m_commit_listeners.erase(std::remove(m_commit_listeners.begin(), m_commit_listeners.end(), listener),
139,779✔
2896
                             m_commit_listeners.end());
139,779✔
2897
}
139,779✔
2898

2899
DisableReplication::DisableReplication(Transaction& t)
2900
    : m_tr(t)
2901
    , m_owner(t.get_db())
2902
    , m_repl(m_owner->get_replication())
2903
    , m_version(t.get_version())
UNCOV
2904
{
×
UNCOV
2905
    m_owner->set_replication(nullptr);
×
UNCOV
2906
    t.m_history = nullptr;
×
UNCOV
2907
}
×
2908

2909
DisableReplication::~DisableReplication()
UNCOV
2910
{
×
UNCOV
2911
    m_owner->set_replication(m_repl);
×
UNCOV
2912
    if (m_version != m_tr.get_version())
×
UNCOV
2913
        m_tr.initialize_replication();
×
UNCOV
2914
}
×
2915

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