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

realm / realm-core / jorgen.edelbo_391

13 Aug 2024 07:57AM UTC coverage: 91.091% (-0.02%) from 91.107%
jorgen.edelbo_391

Pull #7826

Evergreen

web-flow
Merge pull request #7979 from realm/test-upgrade-files

Create test file in file-format 24
Pull Request #7826: Merge Next major

103486 of 182216 branches covered (56.79%)

3157 of 3519 new or added lines in 54 files covered. (89.71%)

191 existing lines in 22 files now uncovered.

219971 of 241486 relevant lines covered (91.09%)

6652643.8 hits per line

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

89.6
/src/realm/group.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 <new>
20
#include <algorithm>
21
#include <fstream>
22

23
#ifdef REALM_DEBUG
24
#include <iostream>
25
#include <iomanip>
26
#endif
27

28
#include <realm/util/file_mapper.hpp>
29
#include <realm/util/memory_stream.hpp>
30
#include <realm/util/thread.hpp>
31
#include <realm/impl/destroy_guard.hpp>
32
#include <realm/utilities.hpp>
33
#include <realm/exceptions.hpp>
34
#include <realm/group_writer.hpp>
35
#include <realm/transaction.hpp>
36
#include <realm/replication.hpp>
37

38
using namespace realm;
39
using namespace realm::util;
40

41
namespace {
42

43
class Initialization {
44
public:
45
    Initialization()
46
    {
24✔
47
        realm::cpuid_init();
24✔
48
    }
24✔
49
};
50

51
Initialization initialization;
52

53
} // anonymous namespace
54

55
Group::Group()
56
    : m_local_alloc(new SlabAlloc)
2,187✔
57
    , m_alloc(*m_local_alloc) // Throws
2,187✔
58
    , m_top(m_alloc)
2,187✔
59
    , m_tables(m_alloc)
2,187✔
60
    , m_table_names(m_alloc)
2,187✔
61
{
4,374✔
62
    init_array_parents();
4,374✔
63
    m_alloc.attach_empty(); // Throws
4,374✔
64
    m_file_format_version = get_target_file_format_version_for_session(0, Replication::hist_None);
4,374✔
65
    ref_type top_ref = 0; // Instantiate a new empty group
4,374✔
66
    bool create_group_when_missing = true;
4,374✔
67
    bool writable = create_group_when_missing;
4,374✔
68
    attach(top_ref, writable, create_group_when_missing); // Throws
4,374✔
69
}
4,374✔
70

71

72
Group::Group(const std::string& file_path, const char* encryption_key)
73
    : m_local_alloc(new SlabAlloc) // Throws
339✔
74
    , m_alloc(*m_local_alloc)
339✔
75
    , m_top(m_alloc)
339✔
76
    , m_tables(m_alloc)
339✔
77
    , m_table_names(m_alloc)
339✔
78
{
870✔
79
    init_array_parents();
870✔
80

81
    SlabAlloc::Config cfg;
870✔
82
    cfg.read_only = true;
870✔
83
    cfg.no_create = true;
870✔
84
    cfg.encryption_key = encryption_key;
870✔
85
    ref_type top_ref = m_alloc.attach_file(file_path, cfg); // Throws
870✔
86
    // Non-Transaction Groups always allow writing and simply don't allow
87
    // committing when opened in read-only mode
88
    m_alloc.set_read_only(false);
870✔
89

90
    open(top_ref, file_path);
870✔
91
}
870✔
92

93

94
Group::Group(BinaryData buffer, bool take_ownership)
95
    : m_local_alloc(new SlabAlloc) // Throws
24✔
96
    , m_alloc(*m_local_alloc)
24✔
97
    , m_top(m_alloc)
24✔
98
    , m_tables(m_alloc)
24✔
99
    , m_table_names(m_alloc)
24✔
100
{
48✔
101
    REALM_ASSERT(buffer.data());
48✔
102

103
    init_array_parents();
48✔
104
    ref_type top_ref = m_alloc.attach_buffer(buffer.data(), buffer.size()); // Throws
48✔
105

106
    open(top_ref, {});
48✔
107

108
    if (take_ownership)
48✔
109
        m_alloc.own_buffer();
36✔
110
}
48✔
111

112
Group::Group(SlabAlloc* alloc) noexcept
113
    : m_alloc(*alloc)
1,011,744✔
114
    , // Throws
115
    m_top(m_alloc)
1,011,744✔
116
    , m_tables(m_alloc)
1,011,744✔
117
    , m_table_names(m_alloc)
1,011,744✔
118
{
1,703,883✔
119
    init_array_parents();
1,703,883✔
120
}
1,703,883✔
121

122
namespace {
123

124
class TableRecycler : public std::vector<Table*> {
125
public:
126
    ~TableRecycler()
127
    {
×
128
        REALM_UNREACHABLE();
129
        // if ever enabled, remember to release Tables:
×
130
        // for (auto t : *this) {
×
131
        //    delete t;
×
132
        //}
×
133
    }
×
134
};
135

136
// We use the classic approach to construct a FIFO from two LIFO's,
137
// insertion is done into recycler_1, removal is done from recycler_2,
138
// and when recycler_2 is empty, recycler_1 is reversed into recycler_2.
139
// this i O(1) for each entry.
140
auto& g_table_recycler_1 = *new TableRecycler;
141
auto& g_table_recycler_2 = *new TableRecycler;
142
// number of tables held back before being recycled. We hold back recycling
143
// the latest to increase the probability of detecting race conditions
144
// without crashing.
145
const static int g_table_recycling_delay = 100;
146
auto& g_table_recycler_mutex = *new std::mutex;
147

148
} // namespace
149

150
TableKeyIterator& TableKeyIterator::operator++()
151
{
1,176,819✔
152
    m_pos++;
1,176,819✔
153
    m_index_in_group++;
1,176,819✔
154
    load_key();
1,176,819✔
155
    return *this;
1,176,819✔
156
}
1,176,819✔
157

158
TableKey TableKeyIterator::operator*()
159
{
1,182,954✔
160
    if (!bool(m_table_key)) {
1,182,954✔
161
        load_key();
389,334✔
162
    }
389,334✔
163
    return m_table_key;
1,182,954✔
164
}
1,182,954✔
165

166
void TableKeyIterator::load_key()
167
{
1,566,156✔
168
    const Group& g = *m_group;
1,566,156✔
169
    size_t max_index_in_group = g.m_table_names.size();
1,566,156✔
170
    while (m_index_in_group < max_index_in_group) {
1,585,383✔
171
        RefOrTagged rot = g.m_tables.get_as_ref_or_tagged(m_index_in_group);
1,202,241✔
172
        if (rot.is_ref()) {
1,202,241✔
173
            Table* t;
1,183,014✔
174
            if (m_index_in_group < g.m_table_accessors.size() &&
1,183,014✔
175
                (t = load_atomic(g.m_table_accessors[m_index_in_group], std::memory_order_acquire))) {
1,183,017✔
176
                m_table_key = t->get_key();
804,078✔
177
            }
804,078✔
178
            else {
378,936✔
179
                m_table_key = Table::get_key_direct(g.m_tables.get_alloc(), rot.get_as_ref());
378,936✔
180
            }
378,936✔
181
            return;
1,183,014✔
182
        }
1,183,014✔
183
        m_index_in_group++;
19,227✔
184
    }
19,227✔
185
    m_table_key = TableKey();
383,142✔
186
}
383,142✔
187

188
TableKey TableKeys::operator[](size_t p) const
189
{
936✔
190
    if (p < m_iter.m_pos) {
936✔
191
        m_iter = TableKeyIterator(m_iter.m_group, 0);
×
192
    }
×
193
    while (m_iter.m_pos < p) {
1,188✔
194
        ++m_iter;
252✔
195
    }
252✔
196
    return *m_iter;
936✔
197
}
936✔
198

199
size_t Group::size() const noexcept
200
{
776,445✔
201
    return m_num_tables;
776,445✔
202
}
776,445✔
203

204

205
void Group::set_size() const noexcept
206
{
1,955,766✔
207
    int retval = 0;
1,955,766✔
208
    if (is_attached() && m_table_names.is_attached()) {
1,956,126✔
209
        size_t max_index = m_tables.size();
1,824,543✔
210
        REALM_ASSERT_EX(max_index < (1 << 16), max_index);
1,824,543✔
211
        for (size_t j = 0; j < max_index; ++j) {
6,342,435✔
212
            RefOrTagged rot = m_tables.get_as_ref_or_tagged(j);
4,517,892✔
213
            if (rot.is_ref() && rot.get_as_ref()) {
4,517,892✔
214
                ++retval;
4,486,179✔
215
            }
4,486,179✔
216
        }
4,517,892✔
217
    }
1,824,543✔
218
    m_num_tables = retval;
1,955,766✔
219
}
1,955,766✔
220

221
std::map<TableRef, ColKey> Group::get_primary_key_columns_from_pk_table(TableRef pk_table)
222
{
×
223
    std::map<TableRef, ColKey> ret;
×
224
    REALM_ASSERT(pk_table);
×
225
    ColKey col_table = pk_table->get_column_key("pk_table");
×
226
    ColKey col_prop = pk_table->get_column_key("pk_property");
×
227
    for (auto pk_obj : *pk_table) {
×
228
        auto object_type = pk_obj.get<String>(col_table);
×
229
        auto name = std::string(g_class_name_prefix) + std::string(object_type);
×
230
        auto table = get_table(name);
×
231
        auto pk_col_name = pk_obj.get<String>(col_prop);
×
232
        auto pk_col = table->get_column_key(pk_col_name);
×
233
        ret.emplace(table, pk_col);
×
234
    }
×
235

236
    return ret;
×
237
}
×
238

239
TableKey Group::ndx2key(size_t ndx) const
240
{
537✔
241
    REALM_ASSERT(is_attached());
537✔
242
    Table* accessor = load_atomic(m_table_accessors[ndx], std::memory_order_acquire);
537✔
243
    if (accessor)
537✔
244
        return accessor->get_key(); // fast path
255✔
245

246
    // slow path:
247
    RefOrTagged rot = m_tables.get_as_ref_or_tagged(ndx);
282✔
248
    if (rot.is_tagged())
282✔
249
        throw NoSuchTable();
×
250
    ref_type ref = rot.get_as_ref();
282✔
251
    REALM_ASSERT(ref);
282✔
252
    return Table::get_key_direct(m_tables.get_alloc(), ref);
282✔
253
}
282✔
254

255
size_t Group::key2ndx_checked(TableKey key) const
256
{
29,406,822✔
257
    size_t idx = key2ndx(key);
29,406,822✔
258
    // early out
259
    // note: don't lock when accessing m_table_accessors, because if we miss a concurrently introduced table
260
    // accessor, we'll just fall through to the slow path. Table accessors can be introduced concurrently,
261
    // but never removed. The following is only safe because 'm_table_accessors' will not be relocated
262
    // concurrently. (We aim to be safe in face of concurrent access to a frozen transaction, where tables
263
    // cannot be added or removed. All other races are undefined behaviour)
264
    if (idx < m_table_accessors.size()) {
29,406,822✔
265
        Table* tbl = load_atomic(m_table_accessors[idx], std::memory_order_acquire);
29,314,614✔
266
        if (tbl && tbl->get_key() == key)
29,314,614✔
267
            return idx;
28,349,760✔
268
    }
29,314,614✔
269
    // The notion of a const group as it is now, is not really
270
    // useful. It is linked to a distinction between a read
271
    // and a write transaction. This distinction is no longer
272
    // a compile time aspect (it's not const anymore)
273
    Allocator* alloc = const_cast<SlabAlloc*>(&m_alloc);
1,057,062✔
274
    if (m_tables.is_attached() && idx < m_tables.size()) {
1,220,769✔
275
        RefOrTagged rot = m_tables.get_as_ref_or_tagged(idx);
1,220,337✔
276
        if (rot.is_ref() && rot.get_as_ref() && (Table::get_key_direct(*alloc, rot.get_as_ref()) == key)) {
1,220,442✔
277

278
            return idx;
1,220,175✔
279
        }
1,220,175✔
280
    }
1,220,337✔
281
    throw NoSuchTable();
4,294,967,294✔
282
}
1,057,062✔
283

284

285
int Group::get_file_format_version() const noexcept
286
{
418,578✔
287
    return m_file_format_version;
418,578✔
288
}
418,578✔
289

290

291
void Group::set_file_format_version(int file_format) noexcept
292
{
1,703,388✔
293
    m_file_format_version = file_format;
1,703,388✔
294
}
1,703,388✔
295

296

297
int Group::get_committed_file_format_version() const noexcept
298
{
×
299
    return m_alloc.get_committed_file_format_version();
×
300
}
×
301

302
std::optional<int> Group::fake_target_file_format;
303

304
void _impl::GroupFriend::fake_target_file_format(const std::optional<int> format) noexcept
305
{
72✔
306
    Group::fake_target_file_format = format;
72✔
307
}
72✔
308

309
int Group::get_target_file_format_version_for_session(int current_file_format_version,
310
                                                      int requested_history_type) noexcept
311
{
104,739✔
312
    if (Group::fake_target_file_format) {
104,739✔
313
        return *Group::fake_target_file_format;
72✔
314
    }
72✔
315
    // Note: This function is responsible for choosing the target file format
316
    // for a sessions. If it selects a file format that is different from
317
    // `current_file_format_version`, it will trigger a file format upgrade
318
    // process.
319

320
    // Note: `current_file_format_version` may be zero at this time, which means
321
    // that the file format it is not yet decided (only possible for empty
322
    // Realms where top-ref is zero).
323

324
    // Please see Group::get_file_format_version() for information about the
325
    // individual file format versions.
326

327
    if (requested_history_type == Replication::hist_None) {
104,667✔
328
        if (current_file_format_version == 24) {
35,232✔
329
            // We are able to open these file formats in RO mode
UNCOV
330
            return current_file_format_version;
×
UNCOV
331
        }
×
332
    }
35,232✔
333

334
    return g_current_file_format_version;
104,667✔
335
}
104,667✔
336

337
void Group::get_version_and_history_info(const Array& top, _impl::History::version_type& version, int& history_type,
338
                                         int& history_schema_version) noexcept
339
{
117,567✔
340
    using version_type = _impl::History::version_type;
117,567✔
341
    version_type version_2 = 0;
117,567✔
342
    int history_type_2 = 0;
117,567✔
343
    int history_schema_version_2 = 0;
117,567✔
344
    if (top.is_attached()) {
117,567✔
345
        if (top.size() > s_version_ndx) {
76,848✔
346
            version_2 = version_type(top.get_as_ref_or_tagged(s_version_ndx).get_as_int());
76,497✔
347
        }
76,497✔
348
        if (top.size() > s_hist_type_ndx) {
76,848✔
349
            history_type_2 = int(top.get_as_ref_or_tagged(s_hist_type_ndx).get_as_int());
73,914✔
350
        }
73,914✔
351
        if (top.size() > s_hist_version_ndx) {
76,848✔
352
            history_schema_version_2 = int(top.get_as_ref_or_tagged(s_hist_version_ndx).get_as_int());
73,914✔
353
        }
73,914✔
354
    }
76,848✔
355
    // Version 0 is not a legal initial version, so it has to be set to 1
356
    // instead.
357
    if (version_2 == 0)
117,567✔
358
        version_2 = 1;
42,843✔
359
    version = version_2;
117,567✔
360
    history_type = history_type_2;
117,567✔
361
    history_schema_version = history_schema_version_2;
117,567✔
362
}
117,567✔
363

364
int Group::get_history_schema_version() noexcept
365
{
26,541✔
366
    bool history_schema_version = (m_top.is_attached() && m_top.size() > s_hist_version_ndx);
26,541✔
367
    if (history_schema_version) {
26,541✔
368
        return int(m_top.get_as_ref_or_tagged(s_hist_version_ndx).get_as_int());
936✔
369
    }
936✔
370
    return 0;
25,605✔
371
}
26,541✔
372

373
uint64_t Group::get_sync_file_id() const noexcept
374
{
13,705,398✔
375
    if (m_top.is_attached() && m_top.size() > s_sync_file_id_ndx) {
13,705,398✔
376
        return uint64_t(m_top.get_as_ref_or_tagged(s_sync_file_id_ndx).get_as_int());
6,097,281✔
377
    }
6,097,281✔
378
    auto repl = get_replication();
7,608,117✔
379
    if (repl && repl->get_history_type() == Replication::hist_SyncServer) {
7,608,117✔
380
        return 1;
2,847✔
381
    }
2,847✔
382
    return 0;
7,605,270✔
383
}
7,608,117✔
384

385
size_t Group::get_free_space_size(const Array& top) noexcept
386
{
24,186✔
387
    if (top.is_attached() && top.size() > s_free_size_ndx) {
24,186✔
388
        auto ref = top.get_as_ref(s_free_size_ndx);
24,156✔
389
        Array free_list_sizes(top.get_alloc());
24,156✔
390
        free_list_sizes.init_from_ref(ref);
24,156✔
391
        return size_t(free_list_sizes.get_sum());
24,156✔
392
    }
24,156✔
393
    return 0;
30✔
394
}
24,186✔
395

396
size_t Group::get_history_size(const Array& top) noexcept
397
{
24,186✔
398
    if (top.is_attached() && top.size() > s_hist_ref_ndx) {
24,186✔
399
        auto ref = top.get_as_ref(s_hist_ref_ndx);
156✔
400
        Array hist(top.get_alloc());
156✔
401
        hist.init_from_ref(ref);
156✔
402
        return hist.get_byte_size_deep();
156✔
403
    }
156✔
404
    return 0;
24,030✔
405
}
24,186✔
406

407
int Group::read_only_version_check(SlabAlloc& alloc, ref_type top_ref, const std::string& path)
408
{
1,056✔
409
    // Select file format if it is still undecided.
410
    auto file_format_version = alloc.get_committed_file_format_version();
1,056✔
411

412
    bool file_format_ok = false;
1,056✔
413
    // It is not possible to open prior file format versions without an upgrade.
414
    // Since a Realm file cannot be upgraded when opened in this mode
415
    // (we may be unable to write to the file), no earlier versions can be opened.
416
    // Please see Group::get_file_format_version() for information about the
417
    // individual file format versions.
418
    switch (file_format_version) {
1,056✔
419
        case 0:
6✔
420
            file_format_ok = (top_ref == 0);
6✔
421
            break;
6✔
NEW
422
        case 24:
✔
423
        case g_current_file_format_version:
1,014✔
424
            file_format_ok = true;
1,014✔
425
            break;
1,014✔
426
    }
1,056✔
427
    if (REALM_UNLIKELY(!file_format_ok))
1,056✔
428
        throw FileAccessError(ErrorCodes::FileFormatUpgradeRequired,
36✔
429
                              util::format("Realm file at path '%1' cannot be opened in read-only mode because it "
36✔
430
                                           "has a file format version (%2) which requires an upgrade",
36✔
431
                                           path, file_format_version),
36✔
432
                              path);
36✔
433
    return file_format_version;
1,020✔
434
}
1,056✔
435

436
void Group::open(ref_type top_ref, const std::string& file_path)
437
{
870✔
438
    SlabAlloc::DetachGuard dg(m_alloc);
870✔
439
    m_file_format_version = read_only_version_check(m_alloc, top_ref, file_path);
870✔
440

441
    Replication::HistoryType history_type = Replication::hist_None;
870✔
442
    int target_file_format_version = get_target_file_format_version_for_session(m_file_format_version, history_type);
870✔
443
    if (m_file_format_version == 0) {
870✔
444
        set_file_format_version(target_file_format_version);
6✔
445
    }
6✔
446
    else {
864✔
447
        // From a technical point of view, we could upgrade the Realm file
448
        // format in memory here, but since upgrading can be expensive, it is
449
        // currently disallowed.
450
        REALM_ASSERT(target_file_format_version == m_file_format_version);
864✔
451
    }
864✔
452

453
    // Make all dynamically allocated memory (space beyond the attached file) as
454
    // available free-space.
455
    reset_free_space_tracking(); // Throws
870✔
456

457
    bool create_group_when_missing = true;
870✔
458
    bool writable = create_group_when_missing;
870✔
459
    attach(top_ref, writable, create_group_when_missing); // Throws
870✔
460
    dg.release();                                         // Do not detach after all
870✔
461
}
870✔
462

463
Group::~Group() noexcept
464
{
1,709,166✔
465
    // If this group accessor is detached at this point in time, it is either
466
    // because it is DB::m_group (m_is_shared), or it is a free-stading
467
    // group accessor that was never successfully opened.
468
    if (!m_top.is_attached())
1,709,166✔
469
        return;
1,703,904✔
470

471
    // Free-standing group accessor
472
    detach();
5,262✔
473

474
    // if a local allocator is set in m_local_alloc, then the destruction
475
    // of m_local_alloc will trigger destruction of the allocator, which will
476
    // verify that the allocator has been detached, so....
477
    if (m_local_alloc)
5,262✔
478
        m_local_alloc->detach();
5,208✔
479
}
5,262✔
480

481
void Group::remap_and_update_refs(ref_type new_top_ref, size_t new_file_size, bool writable)
482
{
355,794✔
483
    m_alloc.update_reader_view(new_file_size); // Throws
355,794✔
484
    update_allocator_wrappers(writable);
355,794✔
485

486
    // force update of all ref->ptr translations if the mapping has changed
487
    auto mapping_version = m_alloc.get_mapping_version();
355,794✔
488
    if (mapping_version != m_last_seen_mapping_version) {
355,794✔
489
        m_last_seen_mapping_version = mapping_version;
178,857✔
490
    }
178,857✔
491
    update_refs(new_top_ref);
355,794✔
492
}
355,794✔
493

494
void Group::update_table_accessors()
495
{
5,358✔
496
    for (unsigned j = 0; j < m_table_accessors.size(); ++j) {
15,996✔
497
        Table* table = m_table_accessors[j];
10,638✔
498
        // this should be filtered further as an optimization
499
        if (table) {
10,638✔
500
            table->refresh_allocator_wrapper();
10,614✔
501
            table->update_from_parent();
10,614✔
502
        }
10,614✔
503
    }
10,638✔
504
}
5,358✔
505

506

507
void Group::validate_top_array(const Array& arr, const SlabAlloc& alloc, std::optional<size_t> read_lock_file_size,
508
                               std::optional<uint_fast64_t> read_lock_version)
509
{
1,842,009✔
510
    size_t top_size = arr.size();
1,842,009✔
511
    ref_type top_ref = arr.get_ref();
1,842,009✔
512

513
    switch (top_size) {
1,842,009✔
514
        // These are the valid sizes
515
        case 3:
618✔
516
        case 5:
618✔
517
        case 7:
112,866✔
518
        case 9:
112,866✔
519
        case 10:
112,866✔
520
        case 11:
1,831,137✔
521
        case 12: {
1,841,628✔
522
            ref_type table_names_ref = arr.get_as_ref_or_tagged(s_table_name_ndx).get_as_ref();
1,841,628✔
523
            ref_type tables_ref = arr.get_as_ref_or_tagged(s_table_refs_ndx).get_as_ref();
1,841,628✔
524
            auto logical_file_size = arr.get_as_ref_or_tagged(s_file_size_ndx).get_as_int();
1,841,628✔
525

526
            // Logical file size must never exceed actual file size.
527
            auto file_size = alloc.get_baseline();
1,841,628✔
528
            if (logical_file_size > file_size) {
1,841,628✔
529
                std::string err = util::format("Invalid logical file size: %1, actual file size: %2, read lock file "
×
530
                                               "size: %3, read lock version: %4",
×
531
                                               logical_file_size, file_size, read_lock_file_size, read_lock_version);
×
532
                throw InvalidDatabase(err, "");
×
533
            }
×
534
            // First two entries must be valid refs pointing inside the file
535
            auto invalid_ref = [logical_file_size](ref_type ref) {
3,681,654✔
536
                return ref == 0 || (ref & 7) || ref > logical_file_size;
3,681,831✔
537
            };
3,681,654✔
538
            if (invalid_ref(table_names_ref) || invalid_ref(tables_ref)) {
1,841,628✔
539
                std::string err = util::format(
×
540
                    "Invalid top array (top_ref, [0], [1]): %1, %2, %3, read lock size: %4, read lock version: %5",
×
541
                    top_ref, table_names_ref, tables_ref, read_lock_file_size, read_lock_version);
×
542
                throw InvalidDatabase(err, "");
×
543
            }
×
544
            break;
1,841,628✔
545
        }
1,841,628✔
546
        default: {
1,841,628✔
547
            auto logical_file_size = arr.get_as_ref_or_tagged(s_file_size_ndx).get_as_int();
×
548
            std::string err =
×
549
                util::format("Invalid top array size (ref: %1, array size: %2) file size: %3, read "
×
550
                             "lock size: %4, read lock version: %5",
×
551
                             top_ref, top_size, logical_file_size, read_lock_file_size, read_lock_version);
×
552
            throw InvalidDatabase(err, "");
×
553
            break;
×
554
        }
1,841,628✔
555
    }
1,842,009✔
556
}
1,842,009✔
557

558
void Group::attach(ref_type top_ref, bool writable, bool create_group_when_missing, size_t file_size,
559
                   uint_fast64_t version)
560
{
1,958,727✔
561
    REALM_ASSERT(!m_top.is_attached());
1,958,727✔
562
    if (create_group_when_missing)
1,958,727✔
563
        REALM_ASSERT(writable);
1,958,727✔
564

565
    // If this function throws, it must leave the group accesor in a the
566
    // unattached state.
567

568
    m_tables.detach();
1,958,727✔
569
    m_table_names.detach();
1,958,727✔
570
    m_is_writable = writable;
1,958,727✔
571

572
    if (top_ref != 0) {
1,958,727✔
573
        m_top.init_from_ref(top_ref);
1,813,245✔
574
        validate_top_array(m_top, m_alloc, file_size, version);
1,813,245✔
575
        m_table_names.init_from_parent();
1,813,245✔
576
        m_tables.init_from_parent();
1,813,245✔
577
    }
1,813,245✔
578
    else if (create_group_when_missing) {
145,482✔
579
        create_empty_group(); // Throws
13,614✔
580
    }
13,614✔
581
    m_attached = true;
1,958,727✔
582
    set_size();
1,958,727✔
583

584
    size_t sz = m_tables.is_attached() ? m_tables.size() : 0;
1,958,727✔
585
    while (m_table_accessors.size() > sz) {
1,958,811✔
586
        if (Table* t = m_table_accessors.back()) {
84✔
587
            t->detach(Table::cookie_void);
84✔
588
            recycle_table_accessor(t);
84✔
589
        }
84✔
590
        m_table_accessors.pop_back();
84✔
591
    }
84✔
592
    while (m_table_accessors.size() < sz) {
5,999,562✔
593
        m_table_accessors.emplace_back();
4,040,835✔
594
    }
4,040,835✔
595
}
1,958,727✔
596

597

598
void Group::detach() noexcept
599
{
1,708,791✔
600
    detach_table_accessors();
1,708,791✔
601
    m_table_accessors.clear();
1,708,791✔
602

603
    m_table_names.detach();
1,708,791✔
604
    m_tables.detach();
1,708,791✔
605
    m_top.detach();
1,708,791✔
606

607
    m_attached = false;
1,708,791✔
608
}
1,708,791✔
609

610
void Group::attach_shared(ref_type new_top_ref, size_t new_file_size, bool writable, VersionID version)
611
{
1,703,625✔
612
    REALM_ASSERT_3(new_top_ref, <, new_file_size);
1,703,625✔
613
    REALM_ASSERT(!is_attached());
1,703,625✔
614

615
    // update readers view of memory
616
    m_alloc.update_reader_view(new_file_size); // Throws
1,703,625✔
617
    update_allocator_wrappers(writable);
1,703,625✔
618

619
    // When `new_top_ref` is null, ask attach() to create a new node structure
620
    // for an empty group, but only during the initiation of write
621
    // transactions. When the transaction being initiated is a read transaction,
622
    // we instead have to leave array accessors m_top, m_tables, and
623
    // m_table_names in their detached state, as there are no underlying array
624
    // nodes to attached them to. In the case of write transactions, the nodes
625
    // have to be created, as they have to be ready for being modified.
626
    bool create_group_when_missing = writable;
1,703,625✔
627
    attach(new_top_ref, writable, create_group_when_missing, new_file_size, version.version); // Throws
1,703,625✔
628
}
1,703,625✔
629

630

631
void Group::detach_table_accessors() noexcept
632
{
1,708,743✔
633
    for (auto& table_accessor : m_table_accessors) {
4,313,103✔
634
        if (Table* t = table_accessor) {
4,313,103✔
635
            t->detach(Table::cookie_transaction_ended);
1,898,688✔
636
            recycle_table_accessor(t);
1,898,688✔
637
            table_accessor = nullptr;
1,898,688✔
638
        }
1,898,688✔
639
    }
4,313,103✔
640
}
1,708,743✔
641

642

643
void Group::create_empty_group()
644
{
70,722✔
645
    m_top.create(Array::type_HasRefs); // Throws
70,722✔
646
    _impl::DeepArrayDestroyGuard dg_top(&m_top);
70,722✔
647
    {
70,722✔
648
        m_table_names.create(); // Throws
70,722✔
649
        _impl::DestroyGuard<ArrayStringShort> dg(&m_table_names);
70,722✔
650
        m_top.add(m_table_names.get_ref()); // Throws
70,722✔
651
        dg.release();
70,722✔
652
    }
70,722✔
653
    {
70,722✔
654
        m_tables.create(Array::type_HasRefs); // Throws
70,722✔
655
        _impl::DestroyGuard<Array> dg(&m_tables);
70,722✔
656
        m_top.add(m_tables.get_ref()); // Throws
70,722✔
657
        dg.release();
70,722✔
658
    }
70,722✔
659
    size_t initial_logical_file_size = sizeof(SlabAlloc::Header);
70,722✔
660
    m_top.add(RefOrTagged::make_tagged(initial_logical_file_size)); // Throws
70,722✔
661
    dg_top.release();
70,722✔
662
}
70,722✔
663

664

665
Table* Group::do_get_table(size_t table_ndx)
666
{
32,809,476✔
667
    REALM_ASSERT(m_table_accessors.size() == m_tables.size());
32,809,476✔
668
    // Get table accessor from cache if it exists, else create
669
    Table* table = load_atomic(m_table_accessors[table_ndx], std::memory_order_acquire);
32,809,476✔
670
    if (!table) {
32,809,476✔
671
        // double-checked locking idiom
672
        std::lock_guard<std::mutex> lock(m_accessor_mutex);
1,640,112✔
673
        table = m_table_accessors[table_ndx];
1,640,112✔
674
        if (!table)
1,640,112✔
675
            table = create_table_accessor(table_ndx); // Throws
1,629,267✔
676
    }
1,640,112✔
677
    return table;
32,809,476✔
678
}
32,809,476✔
679

680

681
Table* Group::do_get_table(StringData name)
682
{
11,777,970✔
683
    if (!m_table_names.is_attached())
11,777,970✔
684
        return 0;
509,580✔
685
    size_t table_ndx = m_table_names.find_first(name);
11,268,390✔
686
    if (table_ndx == not_found)
11,268,390✔
687
        return 0;
3,740,025✔
688

689
    Table* table = do_get_table(table_ndx); // Throws
7,528,365✔
690
    return table;
7,528,365✔
691
}
11,268,390✔
692

693
TableRef Group::add_table_with_primary_key(StringData name, DataType pk_type, StringData pk_name, bool nullable,
694
                                           Table::Type table_type)
695
{
87,717✔
696
    check_attached();
87,717✔
697
    check_table_name_uniqueness(name);
87,717✔
698

699
    auto table = do_add_table(name, table_type, false);
87,717✔
700

701
    // Add pk column - without replication
702
    ColumnAttrMask attr;
87,717✔
703
    if (nullable)
87,717✔
704
        attr.set(col_attr_Nullable);
15,825✔
705
    ColKey pk_col = table->generate_col_key(ColumnType(pk_type), attr);
87,717✔
706
    table->do_insert_root_column(pk_col, ColumnType(pk_type), pk_name);
87,717✔
707
    table->do_set_primary_key_column(pk_col);
87,717✔
708

709
    if (Replication* repl = *get_repl())
87,717✔
710
        repl->add_class_with_primary_key(table->get_key(), name, pk_type, pk_name, nullable, table_type);
86,757✔
711

712
    return TableRef(table, table->m_alloc.get_instance_version());
87,717✔
713
}
87,717✔
714

715
Table* Group::do_add_table(StringData name, Table::Type table_type, bool do_repl)
716
{
271,284✔
717
    if (!m_is_writable)
271,284✔
718
        throw LogicError(ErrorCodes::ReadOnlyDB, "Database not writable");
6✔
719

720
    // get new key and index
721
    // find first empty spot:
722
    uint32_t j;
271,278✔
723
    RefOrTagged rot = RefOrTagged::make_tagged(0);
271,278✔
724
    for (j = 0; j < m_tables.size(); ++j) {
52,555,359✔
725
        rot = m_tables.get_as_ref_or_tagged(j);
52,285,131✔
726
        if (!rot.is_ref())
52,285,131✔
727
            break;
1,050✔
728
    }
52,285,131✔
729
    bool gen_null_tag = (j == m_tables.size()); // new tags start at zero
271,278✔
730
    uint32_t tag = gen_null_tag ? 0 : uint32_t(rot.get_as_int());
271,278✔
731
    TableKey key = TableKey((tag << 16) | j);
271,278✔
732

733
    if (REALM_UNLIKELY(name.size() > max_table_name_length))
271,278✔
734
        throw InvalidArgument(ErrorCodes::InvalidName, util::format("Name too long: %1", name));
6✔
735

736
    using namespace _impl;
271,272✔
737
    size_t table_ndx = key2ndx(key);
271,272✔
738
    ref_type ref = Table::create_empty_table(m_alloc, key); // Throws
271,272✔
739
    REALM_ASSERT_3(m_tables.size(), ==, m_table_names.size());
271,272✔
740

741
    rot = RefOrTagged::make_ref(ref);
271,272✔
742
    REALM_ASSERT(m_table_accessors.size() == m_tables.size());
271,272✔
743

744
    if (table_ndx == m_tables.size()) {
271,272✔
745
        m_tables.add(rot);
270,207✔
746
        m_table_names.add(name);
270,207✔
747
        // Need new slot for table accessor
748
        m_table_accessors.push_back(nullptr);
270,207✔
749
    }
270,207✔
750
    else {
1,065✔
751
        m_tables.set(table_ndx, rot);       // Throws
1,065✔
752
        m_table_names.set(table_ndx, name); // Throws
1,065✔
753
    }
1,065✔
754

755
    Replication* repl = *get_repl();
271,272✔
756
    if (do_repl && repl)
271,272✔
757
        repl->add_class(key, name, table_type);
177,513✔
758

759
    ++m_num_tables;
271,272✔
760

761
    Table* table = create_table_accessor(j);
271,272✔
762
    table->do_set_table_type(table_type);
271,272✔
763

764
    return table;
271,272✔
765
}
271,278✔
766

767
Table* Group::create_table_accessor(size_t table_ndx)
768
{
1,900,569✔
769
    REALM_ASSERT(m_tables.size() == m_table_accessors.size());
1,900,569✔
770
    REALM_ASSERT(table_ndx < m_table_accessors.size());
1,900,569✔
771

772
    RefOrTagged rot = m_tables.get_as_ref_or_tagged(table_ndx);
1,900,569✔
773
    ref_type ref = rot.get_as_ref();
1,900,569✔
774
    if (ref == 0) {
1,900,569✔
775
        throw NoSuchTable();
×
776
    }
×
777
    Table* table = 0;
1,900,569✔
778
    {
1,900,569✔
779
        std::lock_guard<std::mutex> lg(g_table_recycler_mutex);
1,900,569✔
780
        if (g_table_recycler_2.empty()) {
1,900,569✔
781
            while (!g_table_recycler_1.empty()) {
1,901,226✔
782
                auto t = g_table_recycler_1.back();
1,889,574✔
783
                g_table_recycler_1.pop_back();
1,889,574✔
784
                g_table_recycler_2.push_back(t);
1,889,574✔
785
            }
1,889,574✔
786
        }
11,652✔
787
        if (g_table_recycler_2.size() + g_table_recycler_1.size() > g_table_recycling_delay) {
1,900,569✔
788
            table = g_table_recycler_2.back();
1,870,278✔
789
            table->fully_detach();
1,870,278✔
790
            g_table_recycler_2.pop_back();
1,870,278✔
791
        }
1,870,278✔
792
    }
1,900,569✔
793
    if (table) {
1,900,569✔
794
        table->revive(get_repl(), m_alloc, m_is_writable);
1,870,275✔
795
        table->init(ref, this, table_ndx, m_is_writable, is_frozen());
1,870,275✔
796
    }
1,870,275✔
797
    else {
30,294✔
798
        std::unique_ptr<Table> new_table(new Table(get_repl(), m_alloc));  // Throws
30,294✔
799
        new_table->init(ref, this, table_ndx, m_is_writable, is_frozen()); // Throws
30,294✔
800
        table = new_table.release();
30,294✔
801
    }
30,294✔
802
    table->refresh_index_accessors();
1,900,569✔
803
    // must be atomic to allow concurrent probing of the m_table_accessors vector.
804
    store_atomic(m_table_accessors[table_ndx], table, std::memory_order_release);
1,900,569✔
805
    return table;
1,900,569✔
806
}
1,900,569✔
807

808

809
void Group::recycle_table_accessor(Table* to_be_recycled)
810
{
1,900,518✔
811
    std::lock_guard<std::mutex> lg(g_table_recycler_mutex);
1,900,518✔
812
    g_table_recycler_1.push_back(to_be_recycled);
1,900,518✔
813
}
1,900,518✔
814

815
void Group::remove_table(StringData name)
816
{
519✔
817
    check_attached();
519✔
818
    size_t table_ndx = m_table_names.find_first(name);
519✔
819
    if (table_ndx == not_found)
519✔
820
        throw NoSuchTable();
6✔
821
    auto key = ndx2key(table_ndx);
513✔
822
    remove_table(table_ndx, key); // Throws
513✔
823
}
513✔
824

825

826
void Group::remove_table(TableKey key)
827
{
1,071✔
828
    check_attached();
1,071✔
829

830
    size_t table_ndx = key2ndx_checked(key);
1,071✔
831
    remove_table(table_ndx, key);
1,071✔
832
}
1,071✔
833

834

835
void Group::remove_table(size_t table_ndx, TableKey key)
836
{
1,584✔
837
    if (!m_is_writable)
1,584✔
838
        throw LogicError(ErrorCodes::ReadOnlyDB, "Database not writable");
×
839
    REALM_ASSERT_3(m_tables.size(), ==, m_table_names.size());
1,584✔
840
    REALM_ASSERT(table_ndx < m_tables.size());
1,584✔
841
    TableRef table = get_table(key);
1,584✔
842

843
    // In principle we could remove a table even if it is the target of link
844
    // columns of other tables, however, to do that, we would have to
845
    // automatically remove the "offending" link columns from those other
846
    // tables. Such a behaviour is deemed too obscure, and we shall therefore
847
    // require that a removed table does not contain foreign origin backlink
848
    // columns.
849
    if (table->is_cross_table_link_target())
1,584✔
850
        throw CrossTableLinkTarget(table->get_name());
18✔
851

852
    {
1,566✔
853
        // We don't want to replicate the individual column removals along the
854
        // way as they're covered by the table removal
855
        Table::DisableReplication dr(*table);
1,566✔
856
        table->remove_columns();
1,566✔
857
    }
1,566✔
858

859
    size_t prior_num_tables = m_tables.size();
1,566✔
860
    Replication* repl = *get_repl();
1,566✔
861
    if (repl)
1,566✔
862
        repl->erase_class(key, table->get_name(), prior_num_tables); // Throws
1,488✔
863

864
    int64_t ref_64 = m_tables.get(table_ndx);
1,566✔
865
    REALM_ASSERT(!int_cast_has_overflow<ref_type>(ref_64));
1,566✔
866
    ref_type ref = ref_type(ref_64);
1,566✔
867

868
    // Replace entry in m_tables with next tag to use:
869
    RefOrTagged rot = RefOrTagged::make_tagged((1 + (key.value >> 16)) & 0x7FFF);
1,566✔
870
    // Remove table
871
    m_tables.set(table_ndx, rot);     // Throws
1,566✔
872
    m_table_names.set(table_ndx, {}); // Throws
1,566✔
873
    m_table_accessors[table_ndx] = nullptr;
1,566✔
874
    --m_num_tables;
1,566✔
875

876
    table->detach(Table::cookie_removed);
1,566✔
877
    // Destroy underlying node structure
878
    Array::destroy_deep(ref, m_alloc);
1,566✔
879
    recycle_table_accessor(table.unchecked_ptr());
1,566✔
880
}
1,566✔
881

882

883
void Group::rename_table(StringData name, StringData new_name, bool require_unique_name)
884
{
24✔
885
    check_attached();
24✔
886
    size_t table_ndx = m_table_names.find_first(name);
24✔
887
    if (table_ndx == not_found)
24✔
888
        throw NoSuchTable();
6✔
889
    rename_table(ndx2key(table_ndx), new_name, require_unique_name); // Throws
18✔
890
}
18✔
891

892

893
void Group::rename_table(TableKey key, StringData new_name, bool require_unique_name)
894
{
24✔
895
    check_attached();
24✔
896
    if (!m_is_writable)
24✔
897
        throw LogicError(ErrorCodes::ReadOnlyDB, "Database not writable");
×
898
    REALM_ASSERT_3(m_tables.size(), ==, m_table_names.size());
24✔
899
    if (require_unique_name && has_table(new_name))
24✔
900
        throw TableNameInUse();
6✔
901
    size_t table_ndx = key2ndx_checked(key);
18✔
902
    m_table_names.set(table_ndx, new_name);
18✔
903
    if (Replication* repl = *get_repl())
18✔
904
        repl->rename_class(key, new_name); // Throws
×
905
}
18✔
906

907
Obj Group::get_object(ObjLink link)
908
{
430,785✔
909
    auto target_table = get_table(link.get_table_key());
430,785✔
910
    ObjKey key = link.get_obj_key();
430,785✔
911
    ClusterTree* ct = key.is_unresolved() ? target_table->m_tombstones.get() : &target_table->m_clusters;
430,785✔
912
    return ct->get(key);
430,785✔
913
}
430,785✔
914

915
Obj Group::try_get_object(ObjLink link) noexcept
916
{
×
917
    auto target_table = get_table(link.get_table_key());
×
918
    ObjKey key = link.get_obj_key();
×
919
    ClusterTree* ct = key.is_unresolved() ? target_table->m_tombstones.get() : &target_table->m_clusters;
×
920
    return ct->try_get_obj(key);
×
921
}
×
922

923
void Group::validate(ObjLink link) const
924
{
309,690✔
925
    if (auto tk = link.get_table_key()) {
309,690✔
926
        auto target_key = link.get_obj_key();
309,690✔
927
        auto target_table = get_table(tk);
309,690✔
928
        const ClusterTree* ct =
309,690✔
929
            target_key.is_unresolved() ? target_table->m_tombstones.get() : &target_table->m_clusters;
309,690✔
930
        if (!ct->is_valid(target_key)) {
309,690✔
931
            throw InvalidArgument(ErrorCodes::KeyNotFound, "Target object not found");
12✔
932
        }
12✔
933
        if (target_table->is_embedded()) {
309,678✔
934
            throw IllegalOperation("Cannot link to embedded object");
54✔
935
        }
54✔
936
        if (target_table->is_asymmetric()) {
309,624✔
937
            throw IllegalOperation("Cannot link to ephemeral object");
6✔
938
        }
6✔
939
    }
309,624✔
940
}
309,690✔
941

942
ref_type Group::typed_write_tables(_impl::ArrayWriterBase& out) const
943
{
615,561✔
944
    ref_type ref = m_top.get_as_ref(1);
615,561✔
945
    if (out.only_modified && m_alloc.is_read_only(ref))
615,561✔
946
        return ref;
129,951✔
947
    Array a(m_alloc);
485,610✔
948
    a.init_from_ref(ref);
485,610✔
949
    REALM_ASSERT_DEBUG(a.has_refs());
485,610✔
950
    TempArray dest(a.size());
485,610✔
951
    for (unsigned j = 0; j < a.size(); ++j) {
1,823,247✔
952
        RefOrTagged rot = a.get_as_ref_or_tagged(j);
1,337,637✔
953
        if (rot.is_tagged()) {
1,337,637✔
954
            dest.set(j, rot);
12,927✔
955
        }
12,927✔
956
        else {
1,324,710✔
957
            auto table = do_get_table(j);
1,324,710✔
958
            REALM_ASSERT_DEBUG(table);
1,324,710✔
959
            dest.set_as_ref(j, table->typed_write(rot.get_as_ref(), out));
1,324,710✔
960
        }
1,324,710✔
961
    }
1,337,637✔
962
    return dest.write(out);
485,610✔
963
}
615,561✔
964

965
ref_type Group::DefaultTableWriter::write_names(_impl::OutputStream& out)
966
{
678✔
967
    bool deep = true;                                                           // Deep
678✔
968
    bool only_if_modified = false;                                              // Always
678✔
969
    bool compress = false;                                                      // true;
678✔
970
    return m_group->m_table_names.write(out, deep, only_if_modified, compress); // Throws
678✔
971
}
678✔
972
ref_type Group::DefaultTableWriter::write_tables(_impl::OutputStream& out)
973
{
678✔
974
    return m_group->typed_write_tables(out);
678✔
975
}
678✔
976

977
auto Group::DefaultTableWriter::write_history(_impl::OutputStream& out) -> HistoryInfo
978
{
414✔
979
    bool deep = true;              // Deep
414✔
980
    bool only_if_modified = false; // Always
414✔
981
    bool compress = false;
414✔
982
    ref_type history_ref = _impl::GroupFriend::get_history_ref(*m_group);
414✔
983
    HistoryInfo info;
414✔
984
    if (history_ref) {
414✔
985
        _impl::History::version_type version;
366✔
986
        int history_type, history_schema_version;
366✔
987
        _impl::GroupFriend::get_version_and_history_info(_impl::GroupFriend::get_alloc(*m_group),
366✔
988
                                                         m_group->m_top.get_ref(), version, history_type,
366✔
989
                                                         history_schema_version);
366✔
990
        REALM_ASSERT(history_type != Replication::hist_None);
366✔
991
        if (!m_should_write_history || history_type == Replication::hist_None) {
366✔
992
            return info; // Only sync history should be preserved when writing to a new file
6✔
993
        }
6✔
994
        info.type = history_type;
360✔
995
        info.version = history_schema_version;
360✔
996
        Array history{const_cast<Allocator&>(_impl::GroupFriend::get_alloc(*m_group))};
360✔
997
        history.init_from_ref(history_ref);
360✔
998
        info.ref = history.write(out, deep, only_if_modified, compress); // Throws
360✔
999
    }
360✔
1000
    info.sync_file_id = m_group->get_sync_file_id();
408✔
1001
    return info;
408✔
1002
}
414✔
1003

1004
void Group::write(std::ostream& out, bool pad) const
1005
{
42✔
1006
    DefaultTableWriter table_writer;
42✔
1007
    write(out, pad, 0, table_writer);
42✔
1008
}
42✔
1009

1010
void Group::write(std::ostream& out, bool pad_for_encryption, uint_fast64_t version_number, TableWriter& writer) const
1011
{
690✔
1012
    REALM_ASSERT(is_attached());
690✔
1013
    writer.set_group(this);
690✔
1014
    bool no_top_array = !m_top.is_attached();
690✔
1015
    write(out, m_file_format_version, writer, no_top_array, pad_for_encryption, version_number); // Throws
690✔
1016
}
690✔
1017

1018
void Group::write(File& file, const char* encryption_key, uint_fast64_t version_number, TableWriter& writer) const
1019
{
648✔
1020
    REALM_ASSERT(file.get_size() == 0);
648✔
1021

1022
    file.set_encryption_key(encryption_key);
648✔
1023

1024
    // The aim is that the buffer size should be at least 1/256 of needed size but less than 64 Mb
1025
    constexpr size_t upper_bound = 64 * 1024 * 1024;
648✔
1026
    size_t min_space = std::min(get_used_space() >> 8, upper_bound);
648✔
1027
    size_t buffer_size = page_size();
648✔
1028
    while (buffer_size < min_space) {
699✔
1029
        buffer_size <<= 1;
51✔
1030
    }
51✔
1031
    File::Streambuf streambuf(&file, buffer_size);
648✔
1032

1033
    std::ostream out(&streambuf);
648✔
1034
    out.exceptions(std::ios_base::failbit | std::ios_base::badbit);
648✔
1035
    write(out, encryption_key != 0, version_number, writer);
648✔
1036
    int sync_status = streambuf.pubsync();
648✔
1037
    REALM_ASSERT(sync_status == 0);
648✔
1038
}
648✔
1039

1040
void Group::write(const std::string& path, const char* encryption_key, uint64_t version_number,
1041
                  bool write_history) const
1042
{
264✔
1043
    File file;
264✔
1044
    int flags = 0;
264✔
1045
    file.open(path, File::access_ReadWrite, File::create_Must, flags);
264✔
1046
    DefaultTableWriter table_writer(write_history);
264✔
1047
    write(file, encryption_key, version_number, table_writer);
264✔
1048
}
264✔
1049

1050

1051
BinaryData Group::write_to_mem() const
1052
{
42✔
1053
    REALM_ASSERT(is_attached());
42✔
1054

1055
    // Get max possible size of buffer
1056
    size_t max_size = m_alloc.get_total_size();
42✔
1057

1058
    auto buffer = std::unique_ptr<char[]>(new (std::nothrow) char[max_size]);
42✔
1059
    if (!buffer)
42✔
1060
        throw Exception(ErrorCodes::OutOfMemory, "Could not allocate memory while dumping to memory");
×
1061
    MemoryOutputStream out; // Throws
42✔
1062
    out.set_buffer(buffer.get(), buffer.get() + max_size);
42✔
1063
    write(out); // Throws
42✔
1064
    size_t buffer_size = out.size();
42✔
1065
    return BinaryData(buffer.release(), buffer_size);
42✔
1066
}
42✔
1067

1068

1069
void Group::write(std::ostream& out, int file_format_version, TableWriter& table_writer, bool no_top_array,
1070
                  bool pad_for_encryption, uint_fast64_t version_number)
1071
{
690✔
1072
    _impl::OutputStream out_2(out);
690✔
1073
    out_2.only_modified = false;
690✔
1074

1075
    // Write the file header
1076
    SlabAlloc::Header streaming_header;
690✔
1077
    if (no_top_array) {
690✔
1078
        file_format_version = 0;
12✔
1079
    }
12✔
1080
    else if (file_format_version == 0) {
678✔
1081
        // Use current file format version
1082
        file_format_version = get_target_file_format_version_for_session(0, Replication::hist_None);
×
1083
    }
×
1084
    SlabAlloc::init_streaming_header(&streaming_header, file_format_version);
690✔
1085
    out_2.write(reinterpret_cast<const char*>(&streaming_header), sizeof streaming_header);
690✔
1086

1087
    ref_type top_ref = 0;
690✔
1088
    size_t final_file_size = sizeof streaming_header;
690✔
1089
    if (no_top_array) {
690✔
1090
        // Accept version number 1 as that number is (unfortunately) also used
1091
        // to denote the empty initial state of a Realm file.
1092
        REALM_ASSERT(version_number == 0 || version_number == 1);
12✔
1093
    }
12✔
1094
    else {
678✔
1095
        // Because we need to include the total logical file size in the
1096
        // top-array, we have to start by writing everything except the
1097
        // top-array, and then finally compute and write a correct version of
1098
        // the top-array. The free-space information of the group will only be
1099
        // included if a non-zero version number is given as parameter,
1100
        // indicating that versioning info is to be saved. This is used from
1101
        // DB to compact the database by writing only the live data
1102
        // into a separate file.
1103
        ref_type names_ref = table_writer.write_names(out_2);   // Throws
678✔
1104
        ref_type tables_ref = table_writer.write_tables(out_2);
678✔
1105

1106
        SlabAlloc new_alloc;
678✔
1107
        new_alloc.attach_empty(); // Throws
678✔
1108
        Array top(new_alloc);
678✔
1109
        top.create(Array::type_HasRefs); // Throws
678✔
1110
        _impl::ShallowArrayDestroyGuard dg_top(&top);
678✔
1111
        int_fast64_t value_1 = from_ref(names_ref);
678✔
1112
        int_fast64_t value_2 = from_ref(tables_ref);
678✔
1113
        top.add(value_1); // Throws
678✔
1114
        top.add(value_2); // Throws
678✔
1115
        top.add(0);       // Throws
678✔
1116

1117
        int top_size = 3;
678✔
1118
        if (version_number) {
678✔
1119
            TableWriter::HistoryInfo history_info = table_writer.write_history(out_2); // Throws
414✔
1120

1121
            Array free_list(new_alloc);
414✔
1122
            Array size_list(new_alloc);
414✔
1123
            Array version_list(new_alloc);
414✔
1124
            free_list.create(Array::type_Normal); // Throws
414✔
1125
            _impl::DeepArrayDestroyGuard dg_1(&free_list);
414✔
1126
            size_list.create(Array::type_Normal); // Throws
414✔
1127
            _impl::DeepArrayDestroyGuard dg_2(&size_list);
414✔
1128
            version_list.create(Array::type_Normal); // Throws
414✔
1129
            _impl::DeepArrayDestroyGuard dg_3(&version_list);
414✔
1130
            bool deep = true;              // Deep
414✔
1131
            bool only_if_modified = false; // Always
414✔
1132
            bool compress = false;
414✔
1133
            ref_type free_list_ref = free_list.write(out_2, deep, only_if_modified, compress);
414✔
1134
            ref_type size_list_ref = size_list.write(out_2, deep, only_if_modified, compress);
414✔
1135
            ref_type version_list_ref = version_list.write(out_2, deep, only_if_modified, compress);
414✔
1136
            top.add(RefOrTagged::make_ref(free_list_ref));     // Throws
414✔
1137
            top.add(RefOrTagged::make_ref(size_list_ref));     // Throws
414✔
1138
            top.add(RefOrTagged::make_ref(version_list_ref));  // Throws
414✔
1139
            top.add(RefOrTagged::make_tagged(version_number)); // Throws
414✔
1140
            top_size = 7;
414✔
1141

1142
            if (history_info.type != Replication::hist_None) {
414✔
1143
                top.add(RefOrTagged::make_tagged(history_info.type));
360✔
1144
                top.add(RefOrTagged::make_ref(history_info.ref));
360✔
1145
                top.add(RefOrTagged::make_tagged(history_info.version));
360✔
1146
                top.add(RefOrTagged::make_tagged(history_info.sync_file_id));
360✔
1147
                top_size = s_group_max_size;
360✔
1148
                // ^ this is too large, since the evacuation point entry is not there:
1149
                // (but the code below is self correcting)
1150
            }
360✔
1151
        }
414✔
1152
        top_ref = out_2.get_ref_of_next_array();
678✔
1153

1154
        // Produce a preliminary version of the top array whose
1155
        // representation is guaranteed to be able to hold the final file
1156
        // size
1157
        size_t max_top_byte_size = Array::get_max_byte_size(top_size);
678✔
1158
        size_t max_final_file_size = size_t(top_ref) + max_top_byte_size;
678✔
1159
        top.ensure_minimum_width(RefOrTagged::make_tagged(max_final_file_size)); // Throws
678✔
1160

1161
        // Finalize the top array by adding the projected final file size
1162
        // to it
1163
        size_t top_byte_size = top.get_byte_size();
678✔
1164
        final_file_size = size_t(top_ref) + top_byte_size;
678✔
1165
        top.set(2, RefOrTagged::make_tagged(final_file_size)); // Throws
678✔
1166

1167
        // Write the top array
1168
        bool deep = false;             // Shallow
678✔
1169
        bool only_if_modified = false; // Always
678✔
1170
        bool compress = false;
678✔
1171
        top.write(out_2, deep, only_if_modified, compress); // Throws
678✔
1172
        REALM_ASSERT_3(size_t(out_2.get_ref_of_next_array()), ==, final_file_size);
678✔
1173

1174
        dg_top.reset(nullptr); // Destroy now
678✔
1175
    }
678✔
1176

1177
    // encryption will pad the file to a multiple of the page, so ensure the
1178
    // footer is aligned to the end of a page
1179
    if (pad_for_encryption) {
690✔
1180
#if REALM_ENABLE_ENCRYPTION
30✔
1181
        size_t unrounded_size = final_file_size + sizeof(SlabAlloc::StreamingFooter);
30✔
1182
        size_t rounded_size = round_up_to_page_size(unrounded_size);
30✔
1183
        if (rounded_size != unrounded_size) {
30✔
1184
            std::unique_ptr<char[]> buffer(new char[rounded_size - unrounded_size]());
30✔
1185
            out_2.write(buffer.get(), rounded_size - unrounded_size);
30✔
1186
        }
30✔
1187
#endif
30✔
1188
    }
30✔
1189

1190
    // Write streaming footer
1191
    SlabAlloc::StreamingFooter footer;
690✔
1192
    footer.m_top_ref = top_ref;
690✔
1193
    footer.m_magic_cookie = SlabAlloc::footer_magic_cookie;
690✔
1194
    out_2.write(reinterpret_cast<const char*>(&footer), sizeof footer);
690✔
1195
}
690✔
1196

1197

1198
void Group::update_refs(ref_type top_ref) noexcept
1199
{
355,794✔
1200
    // After Group::commit() we will always have free space tracking
1201
    // info.
1202
    REALM_ASSERT_3(m_top.size(), >=, 5);
355,794✔
1203

1204
    m_top.init_from_ref(top_ref);
355,794✔
1205

1206
    // Now we can update it's child arrays
1207
    m_table_names.update_from_parent();
355,794✔
1208
    m_tables.update_from_parent();
355,794✔
1209

1210
    // Update all attached table accessors.
1211
    for (auto& table_accessor : m_table_accessors) {
1,050,279✔
1212
        if (table_accessor) {
1,050,279✔
1213
            table_accessor->update_from_parent();
1,019,928✔
1214
        }
1,019,928✔
1215
    }
1,050,279✔
1216
}
355,794✔
1217

1218
bool Group::operator==(const Group& g) const
1219
{
66✔
1220
    for (auto tk : get_table_keys()) {
138✔
1221
        const StringData& table_name = get_table_name(tk);
138✔
1222

1223
        ConstTableRef table_1 = get_table(tk);
138✔
1224
        ConstTableRef table_2 = g.get_table(table_name);
138✔
1225
        if (!table_2)
138✔
1226
            return false;
12✔
1227
        if (table_1->get_primary_key_column().get_type() != table_2->get_primary_key_column().get_type()) {
126✔
1228
            return false;
×
1229
        }
×
1230
        if (table_1->is_embedded() != table_2->is_embedded())
126✔
1231
            return false;
×
1232
        if (table_1->is_embedded())
126✔
1233
            continue;
60✔
1234

1235
        if (*table_1 != *table_2)
66✔
1236
            return false;
18✔
1237
    }
66✔
1238
    return true;
36✔
1239
}
66✔
1240
size_t Group::get_used_space() const noexcept
1241
{
666✔
1242
    if (!m_top.is_attached())
666✔
1243
        return 0;
12✔
1244

1245
    size_t used_space = (size_t(m_top.get(2)) >> 1);
654✔
1246

1247
    if (m_top.size() > 4) {
654✔
1248
        Array free_lengths(const_cast<SlabAlloc&>(m_alloc));
504✔
1249
        free_lengths.init_from_ref(ref_type(m_top.get(4)));
504✔
1250
        used_space -= size_t(free_lengths.get_sum());
504✔
1251
    }
504✔
1252

1253
    return used_space;
654✔
1254
}
666✔
1255

1256

1257
namespace {
1258
class TransactAdvancer : public _impl::NullInstructionObserver {
1259
public:
1260
    TransactAdvancer(Group&, bool& schema_changed)
1261
        : m_schema_changed(schema_changed)
19,866✔
1262
    {
43,797✔
1263
    }
43,797✔
1264

1265
    bool insert_group_level_table(TableKey) noexcept
1266
    {
13,308✔
1267
        m_schema_changed = true;
13,308✔
1268
        return true;
13,308✔
1269
    }
13,308✔
1270

1271
    bool erase_class(TableKey) noexcept
1272
    {
×
1273
        m_schema_changed = true;
×
1274
        return true;
×
1275
    }
×
1276

1277
    bool rename_class(TableKey) noexcept
1278
    {
×
1279
        m_schema_changed = true;
×
1280
        return true;
×
1281
    }
×
1282

1283
    bool insert_column(ColKey)
1284
    {
76,554✔
1285
        m_schema_changed = true;
76,554✔
1286
        return true;
76,554✔
1287
    }
76,554✔
1288

1289
    bool erase_column(ColKey)
1290
    {
×
1291
        m_schema_changed = true;
×
1292
        return true;
×
1293
    }
×
1294

1295
    bool rename_column(ColKey) noexcept
1296
    {
×
1297
        m_schema_changed = true;
×
1298
        return true; // No-op
×
1299
    }
×
1300

1301
private:
1302
    bool& m_schema_changed;
1303
};
1304
} // anonymous namespace
1305

1306

1307
void Group::update_allocator_wrappers(bool writable)
1308
{
4,761,720✔
1309
    m_is_writable = writable;
4,761,720✔
1310
    // This is tempting:
1311
    // m_alloc.set_read_only(!writable);
1312
    // - but m_alloc may refer to the "global" allocator in the DB object.
1313
    // Setting it here would cause different transactions to raze for
1314
    // changing the shared allocator setting. This is somewhat of a mess.
1315
    for (size_t i = 0; i < m_table_accessors.size(); ++i) {
10,243,632✔
1316
        auto table_accessor = m_table_accessors[i];
5,481,912✔
1317
        if (table_accessor) {
5,481,912✔
1318
            table_accessor->update_allocator_wrapper(writable);
4,076,277✔
1319
        }
4,076,277✔
1320
    }
5,481,912✔
1321
}
4,761,720✔
1322

1323
void Group::flush_accessors_for_commit()
1324
{
614,874✔
1325
    for (auto& acc : m_table_accessors)
614,874✔
1326
        if (acc)
1,651,446✔
1327
            acc->flush_for_commit();
1,149,636✔
1328
}
614,874✔
1329

1330
void Group::refresh_dirty_accessors()
1331
{
249,330✔
1332
    if (!m_tables.is_attached()) {
249,330✔
1333
        m_table_accessors.clear();
51✔
1334
        return;
51✔
1335
    }
51✔
1336

1337
    // The array of Tables cannot have shrunk:
1338
    REALM_ASSERT(m_tables.size() >= m_table_accessors.size());
249,279✔
1339

1340
    // but it may have grown - and if so, we must resize the accessor array to match
1341
    if (m_tables.size() > m_table_accessors.size()) {
249,279✔
1342
        m_table_accessors.resize(m_tables.size());
×
1343
    }
×
1344

1345
    // Update all attached table accessors.
1346
    for (size_t i = 0; i < m_table_accessors.size(); ++i) {
770,490✔
1347
        auto& table_accessor = m_table_accessors[i];
521,211✔
1348
        if (table_accessor) {
521,211✔
1349
            // If the table has changed it's key in the file, it's a
1350
            // new table. This will detach the old accessor and remove it.
1351
            RefOrTagged rot = m_tables.get_as_ref_or_tagged(i);
393,381✔
1352
            bool same_table = false;
393,381✔
1353
            if (rot.is_ref()) {
393,498✔
1354
                auto ref = rot.get_as_ref();
393,459✔
1355
                TableKey new_key = Table::get_key_direct(m_alloc, ref);
393,459✔
1356
                if (new_key == table_accessor->get_key())
393,459✔
1357
                    same_table = true;
393,408✔
1358
            }
393,459✔
1359
            if (same_table) {
393,423✔
1360
                table_accessor->refresh_accessor_tree();
393,408✔
1361
            }
393,408✔
1362
            else {
2,147,483,662✔
1363
                table_accessor->detach(Table::cookie_removed);
2,147,483,662✔
1364
                recycle_table_accessor(table_accessor);
2,147,483,662✔
1365
                m_table_accessors[i] = nullptr;
2,147,483,662✔
1366
            }
2,147,483,662✔
1367
        }
393,381✔
1368
    }
521,211✔
1369
}
249,279✔
1370

1371

1372
void Group::advance_transact(ref_type new_top_ref, util::InputStream* in, bool writable)
1373
{
249,738✔
1374
    REALM_ASSERT(is_attached());
249,738✔
1375
    // Exception safety: If this function throws, the group accessor and all of
1376
    // its subordinate accessors are left in a state that may not be fully
1377
    // consistent. Only minimal consistency is guaranteed (see
1378
    // AccessorConsistencyLevels). In this case, the application is required to
1379
    // either destroy the Group object, forcing all subordinate accessors to
1380
    // become detached, or take some other equivalent action that involves a
1381
    // call to Group::detach(), such as terminating the transaction in progress.
1382
    // such actions will also lead to the detachment of all subordinate
1383
    // accessors. Until then it is an error, and unsafe if the application
1384
    // attempts to access the group one of its subordinate accessors.
1385
    //
1386
    // The purpose of this function is to refresh all attached accessors after
1387
    // the underlying node structure has undergone arbitrary change, such as
1388
    // when a read transaction has been advanced to a later snapshot of the
1389
    // database.
1390
    //
1391
    // Initially, when this function is invoked, we cannot assume any
1392
    // correspondence between the accessor state and the underlying node
1393
    // structure. We can assume that the hierarchy is in a state of minimal
1394
    // consistency, and that it can be brought to a state of structural
1395
    // correspondence using information in the transaction logs. When structural
1396
    // correspondence is achieved, we can reliably refresh the accessor hierarchy
1397
    // (Table::refresh_accessor_tree()) to bring it back to a fully consistent
1398
    // state. See AccessorConsistencyLevels.
1399
    //
1400
    // Much of the information in the transaction logs is not used in this
1401
    // process, because the changes have already been applied to the underlying
1402
    // node structure. All we need to do here is to bring the accessors back
1403
    // into a state where they correctly reflect the underlying structure (or
1404
    // detach them if the underlying object has been removed.)
1405
    //
1406
    // This is no longer needed in Core, but we need to compute "schema_changed",
1407
    // for the benefit of ObjectStore.
1408
    bool schema_changed = false;
249,738✔
1409
    if (in && has_schema_change_notification_handler()) {
249,738✔
1410
        TransactAdvancer advancer(*this, schema_changed);
43,797✔
1411
        _impl::TransactLogParser parser; // Throws
43,797✔
1412
        parser.parse(*in, advancer);     // Throws
43,797✔
1413
    }
43,797✔
1414

1415
    m_top.detach();                                           // Soft detach
249,738✔
1416
    bool create_group_when_missing = false;                   // See Group::attach_shared().
249,738✔
1417
    attach(new_top_ref, writable, create_group_when_missing); // Throws
249,738✔
1418
    refresh_dirty_accessors();                                // Throws
249,738✔
1419

1420
    if (schema_changed)
249,738✔
1421
        send_schema_change_notification();
11,970✔
1422
}
249,738✔
1423

1424
void Group::prepare_top_for_history(int history_type, int history_schema_version, uint64_t file_ident)
1425
{
62,043✔
1426
    REALM_ASSERT(m_file_format_version >= 7);
62,043✔
1427
    while (m_top.size() < s_hist_type_ndx) {
309,579✔
1428
        m_top.add(0); // Throws
247,536✔
1429
    }
247,536✔
1430

1431
    if (m_top.size() > s_hist_version_ndx) {
62,043✔
1432
        int stored_history_type = int(m_top.get_as_ref_or_tagged(s_hist_type_ndx).get_as_int());
156✔
1433
        int stored_history_schema_version = int(m_top.get_as_ref_or_tagged(s_hist_version_ndx).get_as_int());
156✔
1434
        if (stored_history_type != Replication::hist_None) {
156✔
1435
            REALM_ASSERT(stored_history_type == history_type);
6✔
1436
            REALM_ASSERT(stored_history_schema_version == history_schema_version);
6✔
1437
        }
6✔
1438
        m_top.set(s_hist_type_ndx, RefOrTagged::make_tagged(history_type));              // Throws
156✔
1439
        m_top.set(s_hist_version_ndx, RefOrTagged::make_tagged(history_schema_version)); // Throws
156✔
1440
    }
156✔
1441
    else {
61,887✔
1442
        // No history yet
1443
        REALM_ASSERT(m_top.size() == s_hist_type_ndx);
61,887✔
1444
        ref_type history_ref = 0;                                    // No history yet
61,887✔
1445
        m_top.add(RefOrTagged::make_tagged(history_type));           // Throws
61,887✔
1446
        m_top.add(RefOrTagged::make_ref(history_ref));               // Throws
61,887✔
1447
        m_top.add(RefOrTagged::make_tagged(history_schema_version)); // Throws
61,887✔
1448
    }
61,887✔
1449

1450
    if (m_top.size() > s_sync_file_id_ndx) {
62,043✔
1451
        m_top.set(s_sync_file_id_ndx, RefOrTagged::make_tagged(file_ident));
42✔
1452
    }
42✔
1453
    else {
62,001✔
1454
        m_top.add(RefOrTagged::make_tagged(file_ident)); // Throws
62,001✔
1455
    }
62,001✔
1456
}
62,043✔
1457

1458
void Group::clear_history()
1459
{
36✔
1460
    bool has_history = (m_top.is_attached() && m_top.size() > s_hist_type_ndx);
36✔
1461
    if (has_history) {
36✔
1462
        auto hist_ref = m_top.get_as_ref(s_hist_ref_ndx);
36✔
1463
        Array::destroy_deep(hist_ref, m_top.get_alloc());
36✔
1464
        m_top.set(s_hist_type_ndx, RefOrTagged::make_tagged(Replication::hist_None)); // Throws
36✔
1465
        m_top.set(s_hist_version_ndx, RefOrTagged::make_tagged(0));                   // Throws
36✔
1466
        m_top.set(s_hist_ref_ndx, 0);                                                 // Throws
36✔
1467
    }
36✔
1468
}
36✔
1469

1470
#ifdef REALM_DEBUG // LCOV_EXCL_START ignore debug functions
1471

1472
class MemUsageVerifier : public Array::MemUsageHandler {
1473
public:
1474
    MemUsageVerifier(ref_type ref_begin, ref_type immutable_ref_end, ref_type mutable_ref_end, ref_type baseline)
1475
        : m_ref_begin(ref_begin)
59,574✔
1476
        , m_immutable_ref_end(immutable_ref_end)
59,574✔
1477
        , m_mutable_ref_end(mutable_ref_end)
59,574✔
1478
        , m_baseline(baseline)
59,574✔
1479
    {
119,256✔
1480
    }
119,256✔
1481
    void add_immutable(ref_type ref, size_t size)
1482
    {
2,551,557✔
1483
        REALM_ASSERT_3(ref % 8, ==, 0);  // 8-byte alignment
2,551,557✔
1484
        REALM_ASSERT_3(size % 8, ==, 0); // 8-byte alignment
2,551,557✔
1485
        REALM_ASSERT_3(size, >, 0);
2,551,557✔
1486
        REALM_ASSERT_3(ref, >=, m_ref_begin);
2,551,557✔
1487
        REALM_ASSERT_3(size, <=, m_immutable_ref_end - ref);
2,551,557✔
1488
        Chunk chunk;
2,551,557✔
1489
        chunk.ref = ref;
2,551,557✔
1490
        chunk.size = size;
2,551,557✔
1491
        m_chunks.push_back(chunk);
2,551,557✔
1492
    }
2,551,557✔
1493
    void add_mutable(ref_type ref, size_t size)
1494
    {
431,100✔
1495
        REALM_ASSERT_3(ref % 8, ==, 0);  // 8-byte alignment
431,100✔
1496
        REALM_ASSERT_3(size % 8, ==, 0); // 8-byte alignment
431,100✔
1497
        REALM_ASSERT_3(size, >, 0);
431,100✔
1498
        REALM_ASSERT_3(ref, >=, m_immutable_ref_end);
431,100✔
1499
        REALM_ASSERT_3(size, <=, m_mutable_ref_end - ref);
431,100✔
1500
        Chunk chunk;
431,100✔
1501
        chunk.ref = ref;
431,100✔
1502
        chunk.size = size;
431,100✔
1503
        m_chunks.push_back(chunk);
431,100✔
1504
    }
431,100✔
1505
    void add(ref_type ref, size_t size)
1506
    {
9,346,062✔
1507
        REALM_ASSERT_3(ref % 8, ==, 0);  // 8-byte alignment
9,346,062✔
1508
        REALM_ASSERT_3(size % 8, ==, 0); // 8-byte alignment
9,346,062✔
1509
        REALM_ASSERT_3(size, >, 0);
9,346,062✔
1510
        REALM_ASSERT_3(ref, >=, m_ref_begin);
9,346,062✔
1511
        REALM_ASSERT(size <= (ref < m_baseline ? m_immutable_ref_end : m_mutable_ref_end) - ref);
9,346,062✔
1512
        Chunk chunk;
9,346,062✔
1513
        chunk.ref = ref;
9,346,062✔
1514
        chunk.size = size;
9,346,062✔
1515
        m_chunks.push_back(chunk);
9,346,062✔
1516
    }
9,346,062✔
1517
    void add(const MemUsageVerifier& verifier)
1518
    {
176,598✔
1519
        m_chunks.insert(m_chunks.end(), verifier.m_chunks.begin(), verifier.m_chunks.end());
176,598✔
1520
    }
176,598✔
1521
    void handle(ref_type ref, size_t allocated, size_t) override
1522
    {
9,345,954✔
1523
        add(ref, allocated);
9,345,954✔
1524
    }
9,345,954✔
1525
    void canonicalize()
1526
    {
472,449✔
1527
        // Sort the chunks in order of increasing ref, then merge adjacent
1528
        // chunks while checking that there is no overlap
1529
        typedef std::vector<Chunk>::iterator iter;
472,449✔
1530
        iter i_1 = m_chunks.begin(), end = m_chunks.end();
472,449✔
1531
        iter i_2 = i_1;
472,449✔
1532
        sort(i_1, end);
472,449✔
1533
        if (i_1 != end) {
472,449✔
1534
            while (++i_2 != end) {
16,021,284✔
1535
                ref_type prev_ref_end = i_1->ref + i_1->size;
15,593,763✔
1536
                REALM_ASSERT_3(prev_ref_end, <=, i_2->ref);
15,593,763✔
1537
                if (i_2->ref == prev_ref_end) { // in-file
15,593,763✔
1538
                    i_1->size += i_2->size;     // Merge
12,270,456✔
1539
                }
12,270,456✔
1540
                else {
3,323,307✔
1541
                    *++i_1 = *i_2;
3,323,307✔
1542
                }
3,323,307✔
1543
            }
15,593,763✔
1544
            m_chunks.erase(i_1 + 1, end);
427,521✔
1545
        }
427,521✔
1546
    }
472,449✔
1547
    void clear()
1548
    {
176,598✔
1549
        m_chunks.clear();
176,598✔
1550
    }
176,598✔
1551
    void check_total_coverage()
1552
    {
59,628✔
1553
        REALM_ASSERT_3(m_chunks.size(), ==, 1);
59,628✔
1554
        REALM_ASSERT_3(m_chunks.front().ref, ==, m_ref_begin);
59,628✔
1555
        REALM_ASSERT_3(m_chunks.front().size, ==, m_mutable_ref_end - m_ref_begin);
59,628✔
1556
    }
59,628✔
1557

1558
private:
1559
    struct Chunk {
1560
        ref_type ref;
1561
        size_t size;
1562
        bool operator<(const Chunk& c) const
1563
        {
135,886,737✔
1564
            return ref < c.ref;
135,886,737✔
1565
        }
135,886,737✔
1566
    };
1567
    std::vector<Chunk> m_chunks;
1568
    ref_type m_ref_begin, m_immutable_ref_end, m_mutable_ref_end, m_baseline;
1569
};
1570

1571
#endif
1572

1573
void Group::verify() const
1574
{
126,987✔
1575
#ifdef REALM_DEBUG
126,987✔
1576
    REALM_ASSERT(is_attached());
126,987✔
1577

1578
    m_alloc.verify();
126,987✔
1579

1580
    if (!m_top.is_attached()) {
126,987✔
1581
        return;
99✔
1582
    }
99✔
1583

1584
    // Verify tables
1585
    {
126,888✔
1586
        auto keys = get_table_keys();
126,888✔
1587
        for (auto key : keys) {
231,828✔
1588
            ConstTableRef table = get_table(key);
231,828✔
1589
            REALM_ASSERT_3(table->get_key().value, ==, key.value);
231,828✔
1590
            table->verify();
231,828✔
1591
        }
231,828✔
1592
    }
126,888✔
1593

1594
    // Verify history if present
1595
    if (Replication* repl = *get_repl()) {
126,888✔
1596
        if (auto hist = repl->_create_history_read()) {
69,531✔
1597
            hist->set_group(const_cast<Group*>(this), false);
69,525✔
1598
            _impl::History::version_type version = 0;
69,525✔
1599
            int history_type = 0;
69,525✔
1600
            int history_schema_version = 0;
69,525✔
1601
            get_version_and_history_info(m_top, version, history_type, history_schema_version);
69,525✔
1602
            REALM_ASSERT(history_type != Replication::hist_None || history_schema_version == 0);
69,525✔
1603
            ref_type hist_ref = get_history_ref(m_top);
69,525✔
1604
            hist->update_from_ref_and_version(hist_ref, version);
69,525✔
1605
            hist->verify();
69,525✔
1606
        }
69,525✔
1607
    }
69,531✔
1608

1609
    if (auto tr = dynamic_cast<const Transaction*>(this)) {
126,888✔
1610
        // This is a transaction
1611
        if (tr->get_transact_stage() == DB::TransactStage::transact_Reading) {
126,555✔
1612
            // Verifying the memory cannot be done from a read transaction
1613
            // There might be a write transaction running that has freed some
1614
            // memory that is seen as being in use in this transaction
1615
            return;
67,263✔
1616
        }
67,263✔
1617
    }
126,555✔
1618
    size_t logical_file_size = to_size_t(m_top.get_as_ref_or_tagged(2).get_as_int());
59,625✔
1619
    size_t ref_begin = sizeof(SlabAlloc::Header);
59,625✔
1620
    ref_type real_immutable_ref_end = logical_file_size;
59,625✔
1621
    ref_type real_mutable_ref_end = m_alloc.get_total_size();
59,625✔
1622
    ref_type real_baseline = m_alloc.get_baseline();
59,625✔
1623
    // Fake that any empty area between the file and slab is part of the file (immutable):
1624
    ref_type immutable_ref_end = m_alloc.align_size_to_section_boundary(real_immutable_ref_end);
59,625✔
1625
    ref_type mutable_ref_end = m_alloc.align_size_to_section_boundary(real_mutable_ref_end);
59,625✔
1626
    ref_type baseline = m_alloc.align_size_to_section_boundary(real_baseline);
59,625✔
1627

1628
    // Check the consistency of the allocation of used memory
1629
    MemUsageVerifier mem_usage_1(ref_begin, immutable_ref_end, mutable_ref_end, baseline);
59,625✔
1630
    m_top.report_memory_usage(mem_usage_1);
59,625✔
1631
    mem_usage_1.canonicalize();
59,625✔
1632

1633
    // Check concistency of the allocation of the immutable memory that was
1634
    // marked as free before the file was opened.
1635
    MemUsageVerifier mem_usage_2(ref_begin, immutable_ref_end, mutable_ref_end, baseline);
59,625✔
1636
    {
59,625✔
1637
        REALM_ASSERT_EX(m_top.size() == 3 || m_top.size() == 5 || m_top.size() == 7 || m_top.size() >= 10,
59,625✔
1638
                        m_top.size());
59,625✔
1639
        Allocator& alloc = m_top.get_alloc();
59,625✔
1640
        Array pos(alloc), len(alloc), ver(alloc);
59,625✔
1641
        pos.set_parent(const_cast<Array*>(&m_top), s_free_pos_ndx);
59,625✔
1642
        len.set_parent(const_cast<Array*>(&m_top), s_free_size_ndx);
59,625✔
1643
        ver.set_parent(const_cast<Array*>(&m_top), s_free_version_ndx);
59,625✔
1644
        if (m_top.size() > s_free_pos_ndx) {
59,625✔
1645
            if (ref_type ref = m_top.get_as_ref(s_free_pos_ndx))
59,115✔
1646
                pos.init_from_ref(ref);
57,342✔
1647
        }
59,115✔
1648
        if (m_top.size() > s_free_size_ndx) {
59,625✔
1649
            if (ref_type ref = m_top.get_as_ref(s_free_size_ndx))
59,115✔
1650
                len.init_from_ref(ref);
57,342✔
1651
        }
59,115✔
1652
        if (m_top.size() > s_free_version_ndx) {
59,625✔
1653
            if (ref_type ref = m_top.get_as_ref(s_free_version_ndx))
59,115✔
1654
                ver.init_from_ref(ref);
57,339✔
1655
        }
59,115✔
1656
        REALM_ASSERT(pos.is_attached() == len.is_attached());
59,625✔
1657
        REALM_ASSERT(pos.is_attached() || !ver.is_attached()); // pos.is_attached() <== ver.is_attached()
59,625✔
1658
        if (pos.is_attached()) {
59,625✔
1659
            size_t n = pos.size();
57,339✔
1660
            REALM_ASSERT_3(n, ==, len.size());
57,339✔
1661
            if (ver.is_attached())
57,339✔
1662
                REALM_ASSERT_3(n, ==, ver.size());
57,339✔
1663
            for (size_t i = 0; i != n; ++i) {
2,449,266✔
1664
                ref_type ref = to_ref(pos.get(i));
2,391,927✔
1665
                size_t size_of_i = to_size_t(len.get(i));
2,391,927✔
1666
                mem_usage_2.add_immutable(ref, size_of_i);
2,391,927✔
1667
            }
2,391,927✔
1668
            mem_usage_2.canonicalize();
57,339✔
1669
            mem_usage_1.add(mem_usage_2);
57,339✔
1670
            mem_usage_1.canonicalize();
57,339✔
1671
            mem_usage_2.clear();
57,339✔
1672
        }
57,339✔
1673
    }
59,625✔
1674

1675
    // Check the concistency of the allocation of the immutable memory that has
1676
    // been marked as free after the file was opened
1677
    for (const auto& free_block : m_alloc.m_free_read_only) {
100,008✔
1678
        mem_usage_2.add_immutable(free_block.first, free_block.second);
100,008✔
1679
    }
100,008✔
1680
    mem_usage_2.canonicalize();
59,625✔
1681
    mem_usage_1.add(mem_usage_2);
59,625✔
1682
    mem_usage_1.canonicalize();
59,625✔
1683
    mem_usage_2.clear();
59,625✔
1684

1685
    // Check the consistency of the allocation of the mutable memory that has
1686
    // been marked as free
1687
    m_alloc.for_all_free_entries([&](ref_type ref, size_t sz) {
431,100✔
1688
        mem_usage_2.add_mutable(ref, sz);
431,100✔
1689
    });
431,100✔
1690
    mem_usage_2.canonicalize();
59,625✔
1691
    mem_usage_1.add(mem_usage_2);
59,625✔
1692
    mem_usage_1.canonicalize();
59,625✔
1693
    mem_usage_2.clear();
59,625✔
1694

1695
    // There may be a hole between the end of file and the beginning of the slab area.
1696
    // We need to take that into account here.
1697
    REALM_ASSERT_3(real_immutable_ref_end, <=, real_baseline);
59,625✔
1698
    auto slab_start = immutable_ref_end;
59,625✔
1699
    if (real_immutable_ref_end < slab_start) {
59,628✔
1700
        ref_type ref = real_immutable_ref_end;
59,628✔
1701
        size_t corrected_size = slab_start - real_immutable_ref_end;
59,628✔
1702
        mem_usage_1.add_immutable(ref, corrected_size);
59,628✔
1703
        mem_usage_1.canonicalize();
59,628✔
1704
    }
59,628✔
1705

1706
    // At this point we have accounted for all memory managed by the slab
1707
    // allocator
1708
    mem_usage_1.check_total_coverage();
59,625✔
1709
#endif
59,625✔
1710
}
59,625✔
1711

1712
void Group::validate_primary_columns()
1713
{
480✔
1714
    auto table_keys = this->get_table_keys();
480✔
1715
    for (auto tk : table_keys) {
1,800✔
1716
        auto table = get_table(tk);
1,800✔
1717
        table->validate_primary_column();
1,800✔
1718
    }
1,800✔
1719
}
480✔
1720

1721
#ifdef REALM_DEBUG
1722

1723
MemStats Group::get_stats()
1724
{
×
1725
    MemStats mem_stats;
×
1726
    m_top.stats(mem_stats);
×
1727

1728
    return mem_stats;
×
1729
}
×
1730

1731
void Group::print() const
1732
{
×
1733
    m_alloc.print();
×
1734
}
×
1735

1736

1737
void Group::print_free() const
1738
{
×
1739
    Allocator& alloc = m_top.get_alloc();
×
1740
    Array pos(alloc), len(alloc), ver(alloc);
×
1741
    pos.set_parent(const_cast<Array*>(&m_top), s_free_pos_ndx);
×
1742
    len.set_parent(const_cast<Array*>(&m_top), s_free_size_ndx);
×
1743
    ver.set_parent(const_cast<Array*>(&m_top), s_free_version_ndx);
×
1744
    if (m_top.size() > s_free_pos_ndx) {
×
1745
        if (ref_type ref = m_top.get_as_ref(s_free_pos_ndx))
×
1746
            pos.init_from_ref(ref);
×
1747
    }
×
1748
    if (m_top.size() > s_free_size_ndx) {
×
1749
        if (ref_type ref = m_top.get_as_ref(s_free_size_ndx))
×
1750
            len.init_from_ref(ref);
×
1751
    }
×
1752
    if (m_top.size() > s_free_version_ndx) {
×
1753
        if (ref_type ref = m_top.get_as_ref(s_free_version_ndx))
×
1754
            ver.init_from_ref(ref);
×
1755
    }
×
1756

1757
    if (!pos.is_attached()) {
×
1758
        std::cout << "none\n";
×
1759
        return;
×
1760
    }
×
1761
    bool has_versions = ver.is_attached();
×
1762

1763
    size_t n = pos.size();
×
1764
    for (size_t i = 0; i != n; ++i) {
×
1765
        size_t offset = to_size_t(pos.get(i));
×
1766
        size_t size_of_i = to_size_t(len.get(i));
×
1767
        std::cout << i << ": " << offset << " " << size_of_i;
×
1768

1769
        if (has_versions) {
×
1770
            size_t version = to_size_t(ver.get(i));
×
1771
            std::cout << " " << version;
×
1772
        }
×
1773
        std::cout << "\n";
×
1774
    }
×
1775
    std::cout << "\n";
×
1776
}
×
1777
#endif
1778

1779
// LCOV_EXCL_STOP ignore debug functions
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