Coverage Report

Created: 2026-12-01 07:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/hobbes/lib/hobbes/db/file.C
Line
Count
Source
1
2
#include <hobbes/hobbes.H>
3
#include <hobbes/fregion.H>
4
#include <hobbes/db/file.H>
5
#include <hobbes/db/signals.H>
6
#include <hobbes/eval/cc.H>
7
#include <hobbes/util/str.H>
8
#include <hobbes/util/ptr.H>
9
#include <set>
10
#include <stdexcept>
11
#include <sstream>
12
13
#include <sys/types.h>
14
#include <sys/stat.h>
15
#include <sys/mman.h>
16
#include <sys/file.h>
17
#include <fcntl.h>
18
#include <unistd.h>
19
20
using namespace hobbes::fregion;
21
22
namespace hobbes {
23
24
0
bool isDBFile(const std::string& f) {
25
0
  return isFRegion(f);
26
0
}
27
28
// does a type represent a 'darray' (the previous storage for all arrays "up to capacity")?
29
0
static bool isDArray(const MonoTypePtr& t) {
30
0
  if (const TApp* ap = is<TApp>(t)) {
31
0
    if (ap->args().size() == 1) {
32
0
      if (const Prim* f = is<Prim>(ap->fn())) {
33
0
        if (f->name() == "darray") {
34
0
          return true;
35
0
        }
36
0
      }
37
0
    }
38
0
  }
39
0
  return false;
40
0
}
41
42
10
MonoTypePtr darrayty(const MonoTypePtr& t) {
43
10
  return tapp(primty("darray", tabs(str::strings("x"), arrayty(t))), list(t));
44
10
}
45
46
// the representation of file reference types changed after v0
47
struct mapFileRefs : public switchTyFn {
48
0
  MonoTypePtr with(const TApp* ap) const override {
49
0
    if (ap->args().size() == 2) {
50
0
      if (const Prim* f = is<Prim>(ap->fn())) {
51
0
        if (f->name() == "fileref") {
52
0
          return fileRefTy(switchOf(ap->args()[1], *this));
53
0
        }
54
0
      }
55
0
    }
56
0
    return MonoTypePtr(TApp::make(switchOf(ap->fn(), *this), switchOf(ap->args(), *this)));
57
0
  }
58
};
59
60
// the representation of stored array types changed after v1
61
struct mapStoredArrays : public switchTyFn {
62
0
  MonoTypePtr with(const Array* a) const override {
63
0
    return darrayty(switchOf(a->type(), *this));
64
0
  }
65
};
66
67
// translate a stored type by file version
68
0
static MonoTypePtr v0_to_v1(const MonoTypePtr& t) {
69
0
  return fileRefTy(switchOf(t, mapFileRefs()));
70
0
}
71
72
0
static MonoTypePtr v1_to_v2(const MonoTypePtr& t) {
73
0
  return switchOf(t, mapStoredArrays());
74
0
}
75
76
0
static MonoTypePtr decodeBindingByVersion(uint16_t version, const binding& b) {
77
0
  switch (version) {
78
0
  case 0:  return v1_to_v2(v0_to_v1(decode(b.type)));
79
0
  case 1:  return v1_to_v2(decode(b.type));
80
0
  default: return decode(b.type);
81
0
  }
82
0
}
83
84
// for storage, we need to make sure that size is computed slightly differently than for memory
85
0
size_t storageSizeOf(const MonoTypePtr& mty) {
86
0
  if (is<Recursive>(mty) != nullptr) {
87
0
    return sizeOf(unroll(mty));
88
0
  } else {
89
0
    return sizeOf(mty);
90
0
  }
91
0
}
92
93
// the base interface for reading data archives
94
0
reader::reader(imagefile* f) : fdata(f) {
95
  // just go ahead and map the whole file in
96
0
  mapFileData(this->fdata, 0, this->fdata->file_size);
97
98
  // and translate bindings
99
0
  for (const auto& b : this->fdata->bindings) {
100
0
    if (!b.first.empty() && b.first[0] != '.') {
101
0
      SBinding sb;
102
0
      sb.type   = decodeBindingByVersion(this->fdata->version, b.second.type);
103
104
      // the type decoder accepts a type that carries a whole expression, and
105
      // a file reference that names its file that way ('T@e') keeps it when a
106
      // field is projected (injFileReferences only completes 'T@?', which is
107
      // what every writer stores), so that 'load' and the other reference
108
      // primitives (db/bindings.C) compile and run an expression that came
109
      // out of the file. Nothing a writer stores needs one, so refuse it here
110
      // as hog does for the types a producer sends. This is checked after the
111
      // version translation, which drops the extra argument of a v0 reference
112
0
      if (embedsExpression(sb.type)) {
113
0
        std::string err = "Not a valid structured data file, the type of '" + b.first + "' carries an embedded expression: " + this->fdata->path;
114
0
        closeFile(this->fdata); // no destructor runs for a constructor that throws
115
0
        throw std::runtime_error(err);
116
0
      }
117
0
      sb.offset = this->fdata->version==0 ? b.second.boffset : b.second.offset;
118
0
      this->sbindings[b.first] = sb;
119
0
    }
120
0
  }
121
0
}
122
123
137
reader::reader(const std::string& path) : reader(openFile(path, true, 0, HFREGION_CURRENT_FILE_FORMAT_VERSION)) {
124
137
}
125
126
0
reader::~reader() {
127
0
  closeFile(this->fdata);
128
0
}
129
130
0
imagefile* reader::fileData() const {
131
0
  return this->fdata;
132
0
}
133
134
0
const std::string& reader::file() const {
135
0
  return this->fdata->path;
136
0
}
137
138
0
size_t reader::size() const {
139
0
  return this->fdata->file_size;
140
0
}
141
142
0
MonoTypeSubst reader::signature() const {
143
0
  MonoTypeSubst s;
144
0
  for (const auto& b : this->sbindings) {
145
0
    s[b.first] = b.second.type;
146
0
  }
147
0
  return s;
148
0
}
149
150
0
bool reader::isDefined(const std::string& vn) const {
151
0
  return this->sbindings.find(vn) != this->sbindings.end();
152
0
}
153
154
0
void* reader::unsafeLookup(const std::string& vn, const MonoTypePtr& ty) const {
155
0
  return unsafeLoad(ty, unsafeLookupOffset(vn, ty));
156
0
}
157
158
0
uint64_t reader::unsafeLookupOffset(const std::string& vn, const MonoTypePtr& ty) const {
159
0
  auto b = this->sbindings.find(vn);
160
0
  if (b == this->sbindings.end()) {
161
0
    throw std::runtime_error("Variable undefined in database: " + vn);
162
0
  }
163
164
0
  if (*b->second.type == *ty) {
165
0
    return b->second.offset;
166
0
  } else {
167
0
    throw std::runtime_error("Database variable has unexpected type: " + hobbes::show(b->second.type) + " != " + hobbes::show(ty));
168
0
  }
169
0
}
170
171
0
uint64_t reader::unsafeOffsetOf(const MonoTypePtr& ty, const void* p) const {
172
0
  return unsafeOffsetOfVal(isDArray(ty), p);
173
0
}
174
175
0
uint64_t reader::unsafeOffsetOfVal(bool isDArr, const void* p) const {
176
0
  fallocs::const_iterator fa = gleb(this->fdata->allocs, crcast<char*>(p));
177
0
  if (fa == this->fdata->allocs.end()) {
178
0
    throw std::runtime_error("No file offset can be determined for unmapped memory");
179
0
  } else {
180
0
    fmappings::const_iterator fm = this->fdata->mappings.find(fa->second.page);
181
0
    if (fm == this->fdata->mappings.end()) {
182
0
      throw std::runtime_error("Internal error, inconsistent file mapping state");
183
0
    }
184
185
0
    return pageOffset(this->fdata, fm->second.base_page) + (reinterpret_cast<const char*>(p) - fm->second.base) - (isDArr ? sizeof(long) : 0);
186
0
  }
187
0
}
188
189
0
const Array* storedAsArray(const MonoTypePtr& ty) {
190
0
  if (const Recursive* rty = is<Recursive>(ty)) {
191
0
    return storedAsArray(rty->recType());
192
0
  } else {
193
0
    return is<Array>(ty);
194
0
  }
195
0
}
196
0
bool storedAsDArray(const MonoTypePtr& ty) {
197
0
  if (const Recursive* rty = is<Recursive>(ty)) {
198
0
    return storedAsDArray(rty->recType());
199
0
  } else {
200
0
    return isDArray(ty);
201
0
  }
202
0
}
203
204
// A value is loaded out of a file by handing out the bytes at its offset as a
205
// value of its type, so that type has to be one whose values are held entirely
206
// in those bytes: primitives, and records, variants and fixed-length arrays of
207
// them, with a file reference (an offset into the same file) to whatever is
208
// kept elsewhere. A function, a closure, an array or a recursive type inside
209
// of a value, a file, a process, ... is an address in the memory of the
210
// process that made it. No writer stores one of those, but the type of a
211
// stored value is read out of the file too (and for a log, hog had it from
212
// whoever sent the log statements), and with such a type the bytes of the
213
// file would be called or followed as addresses by whoever loads them.
214
namespace {
215
struct storedInPlaceF : public switchType<bool> {
216
  // (each type is looked at once, however many times it is shared)
217
  mutable std::set<const MonoType*> seen;
218
219
0
  bool storedInPlace(const MonoTypePtr& t) const {
220
    // aliases and type functions are stored as what they stand for
221
    // (so a file reference is the offset that it is, whatever it refers to)
222
0
    MonoTypePtr rt = repType(t);
223
0
    return !this->seen.insert(rt.get()).second || switchOf(rt, *this);
224
0
  }
225
226
0
  bool with(const Prim*        ) const override { return true; }
227
  // a C++ object can be stored in place (writer::define<T> does that for any
228
  // T it is given), but whether it is says the file, and the one such type
229
  // that this library itself takes apart is a std::string, which is pointers
230
0
  bool with(const OpaquePtr*  v) const override { return v->storedContiguously() && v->name() != "std::string"; }
231
0
  bool with(const FixedArray* v) const override { return storedInPlace(v->type()); }
232
0
  bool with(const Variant*    v) const override {
233
0
    for (const auto& m : v->members()) {
234
0
      if (!storedInPlace(m.type)) return false;
235
0
    }
236
0
    return true;
237
0
  }
238
0
  bool with(const Record*     v) const override {
239
0
    for (const auto& m : v->members()) {
240
0
      if (!storedInPlace(m.type)) return false;
241
0
    }
242
0
    return true;
243
0
  }
244
245
  // held by address
246
0
  bool with(const Array*      ) const override { return false; }
247
0
  bool with(const Func*       ) const override { return false; }
248
0
  bool with(const Exists*     ) const override { return false; }
249
0
  bool with(const Recursive*  ) const override { return false; }
250
251
  // no representation at all (the built-in type constructors, for files,
252
  // processes, lists, ..., are these: the type decoder lets no description
253
  // give one of them a representation, see validPrimRepresentation)
254
0
  bool with(const TApp*       ) const override { return false; }
255
0
  bool with(const TVar*       ) const override { return false; }
256
0
  bool with(const TGen*       ) const override { return false; }
257
0
  bool with(const TAbs*       ) const override { return false; }
258
0
  bool with(const TString*    ) const override { return false; }
259
0
  bool with(const TLong*      ) const override { return false; }
260
0
  bool with(const TExpr*      ) const override { return false; }
261
};
262
}
263
264
0
bool isStorableType(const MonoTypePtr& ty) {
265
0
  storedInPlaceF f;
266
267
  // (following what reader::unsafeLoad does with each type)
268
0
  if (const Array* a = storedAsArray(ty)) {
269
0
    return f.storedInPlace(a->type());
270
0
  } else if (storedAsDArray(ty)) {
271
    // known by its name, and loaded as the array of its argument
272
0
    MonoTypePtr dty = ty;
273
0
    while (const Recursive* rty = is<Recursive>(dty)) {
274
0
      dty = rty->recType();
275
0
    }
276
0
    MonoTypePtr  ety = is<TApp>(dty)->args()[0];
277
0
    const Array* a   = is<Array>(repType(dty));
278
0
    return a != nullptr && *a->type() == *ety && f.storedInPlace(ety);
279
0
  } else if (is<Recursive>(ty) != nullptr) {
280
0
    return f.storedInPlace(unroll(ty));
281
0
  } else {
282
0
    return f.storedInPlace(ty);
283
0
  }
284
0
}
285
286
0
void* reader::unsafeLoad(const MonoTypePtr& ty, uint64_t pos) const {
287
0
  if (pos > this->fdata->file_size) {
288
    // actually, this will be wrong in general since the writer might have written away from the reader
289
0
    throw std::runtime_error("Offset out of range of file");
290
0
  } else if (const Array* a = storedAsArray(ty)) {
291
0
    return unsafeLoadArray(pos, storageSizeOf(a->type()));
292
0
  } else if (storedAsDArray(ty)) {
293
0
    return unsafeLoadDArray(pos);
294
0
  } else {
295
0
    return unsafeLoad(pos, storageSizeOf(ty));
296
0
  }
297
0
}
298
299
// the lengths and offsets read below come out of the file, and what they
300
// reach is what the JIT then dereferences (dbloadv/dbloadarr/dbloaddarr), so
301
// each is checked against the file's size before it is mapped. Only the typed
302
// unsafeLoad above checked its offset at all, and none of them checked a
303
// length: an array length of 0x10000000, or one whose product with the
304
// element size wrapped to zero, mapped an address outside the file that
305
// faulted on the first read.
306
0
void* reader::unsafeLoad(uint64_t pos, size_t datasz) const {
307
0
  return mapFileDataInFile(this->fdata, pos, datasz, "stored value");
308
0
}
309
310
0
uint64_t reader::unsafeDArrayCapacity(uint64_t pos) const {
311
0
  auto* cap    = reinterpret_cast<uint64_t*>(mapFileDataInFile(this->fdata, pos, sizeof(uint64_t), "stored array capacity"));
312
0
  uint64_t  result = *cap;
313
0
  unmapFileData(this->fdata, cap, sizeof(uint64_t));
314
0
  return result;
315
0
}
316
0
void* reader::unsafeLoadDArray(uint64_t pos) const {
317
  // if we're loading a darray, we actually have to read the data size first to know how much to map
318
0
  auto* cap    = reinterpret_cast<uint64_t*>(mapFileDataInFile(this->fdata, pos, sizeof(uint64_t), "stored array capacity"));
319
0
  uint64_t capacity = *cap;
320
0
  unmapFileData(this->fdata, cap, sizeof(uint64_t));
321
0
  return mapFileDataInFile(this->fdata, pos+sizeof(uint64_t), capacity, "stored array data");
322
0
}
323
324
0
void* reader::unsafeLoadArray(uint64_t pos, size_t sz) const {
325
0
  auto* lenp   = reinterpret_cast<uint64_t*>(mapFileDataInFile(this->fdata, pos, sizeof(uint64_t), "stored array length"));
326
0
  uint64_t len = *lenp;
327
0
  unmapFileData(this->fdata, lenp, sizeof(uint64_t));
328
329
  // 'sz * len' is what decides how much of the file this array covers, and a
330
  // length near 2^64 wraps it to something small (or to zero) that passes any
331
  // check made after the multiplication, so bound the length before it is
332
  // multiplied by anything
333
0
  ensureCountInFile(this->fdata, pos + sizeof(uint64_t), sz, len, "stored array");
334
0
  return mapFileDataInFile(this->fdata, pos, sizeof(uint64_t) + sz * len, "stored array");
335
0
}
336
337
0
int reader::unsafeGetFD() const {
338
0
  return this->fdata->fd;
339
0
}
340
341
0
reader::PageEntries* reader::pageEntries() const {
342
0
  PageEntries* r = makeArray<PageEntry>(this->fdata->pages.size());
343
0
  for (size_t i = 0; i < r->size; ++i) {
344
0
    r->data[i].first  = this->fdata->pages[i].type();
345
0
    r->data[i].second = this->fdata->pages[i].availBytes();
346
0
  }
347
0
  return r;
348
0
}
349
350
0
void reader::addSBinding(const std::string& vn, const MonoTypePtr& t, uint64_t offset) {
351
0
  SBinding sb;
352
0
  sb.type   = t;
353
0
  sb.offset = offset;
354
0
  this->sbindings[vn] = sb;
355
0
}
356
357
0
void reader::unsafeUnload(void* p, size_t sz) {
358
0
  unmapFileData(this->fdata, p, sz);
359
0
}
360
361
0
void reader::unsafeUnloadDArray(void* p) {
362
0
  unsigned char* pxd = reinterpret_cast<unsigned char*>(p) - sizeof(long);
363
0
  unmapFileData(this->fdata, pxd, *reinterpret_cast<long*>(pxd));
364
0
}
365
366
0
void reader::unsafeUnloadArray(void* p, size_t sz) {
367
0
  unmapFileData(this->fdata, p, sizeof(uint64_t) + sz * *reinterpret_cast<uint64_t*>(p));
368
0
}
369
370
// change any file ref types to point to this reader because they must be out of this file (this is a bit of a hack)
371
0
void reader::showFileSummary(std::ostream& out) const {
372
0
  out << this->fdata->path << " : " << str::showDataSize(this->fdata->file_size) << std::endl;
373
0
}
374
375
0
void reader::showEnvironment(std::ostream& out) const {
376
0
  str::seqs table;
377
0
  table.resize(3);
378
379
0
  for (const auto& b : this->sbindings) {
380
0
    std::string tn = hobbes::show(b.second.type);
381
0
    if (tn.size() > 100) { tn = tn.substr(0, 100) + "..."; }
382
383
0
    table[0].push_back(b.first);
384
0
    table[1].push_back("::");
385
0
    table[2].push_back(tn);
386
0
  }
387
388
0
  str::printHeadlessLeftAlignedTable(out, table);
389
0
}
390
391
0
void reader::showMappings(std::ostream& out, size_t pageRows) const {
392
0
  static const size_t bytesPerRow = 20;
393
0
  static const size_t bytesToShow = std::min<size_t>(bytesPerRow * pageRows, this->fdata->page_size);
394
395
0
  for (const auto& m : this->fdata->mappings) {
396
0
    out << "map from page " << m.first << " for " << m.second.pages << " page(s) at address " << reinterpret_cast<void*>(m.second.base) << std::endl;
397
398
0
    for (size_t i = 0; i < bytesToShow; ++i) {
399
0
      out << str::hex(*(reinterpret_cast<unsigned char*>(m.second.base) + i)) << " ";
400
0
      if (((i+1) % bytesPerRow) == 0) {
401
0
        out << std::endl;
402
0
      }
403
0
    }
404
0
    if (bytesToShow < this->fdata->page_size) {
405
0
      out << "..." << std::endl;
406
0
    }
407
0
  }
408
0
}
409
410
0
std::string showPageDesc(const pagedata& pd) {
411
0
  std::ostringstream ss;
412
0
  switch (pd.type()) {
413
0
  case pagetype::toc:         ss << "T"; break;
414
0
  case pagetype::environment: ss << "E"; break;
415
0
  case pagetype::data:        ss << "D"; break;
416
0
  default:                    ss << "?"; break;
417
0
  }
418
419
0
  std::string sz = str::from(pd.availBytes());
420
0
  for (size_t p = sz.size(); p < 5; ++p) {
421
0
    ss << "0";
422
0
  }
423
0
  ss << sz;
424
0
  return ss.str();
425
0
}
426
427
0
void reader::showPageTable(std::ostream& out, size_t maxRows) const {
428
0
  static const size_t cellSize = 6;
429
0
  static const size_t rowSize  = 10;
430
431
  // gather page descriptions
432
0
  str::seq pdescs;
433
0
  for (size_t i = 0; i < this->fdata->pages.size(); ++i) {
434
0
    if (i == rowSize * maxRows) {
435
0
      break;
436
0
    }
437
0
    pdescs.push_back(showPageDesc(this->fdata->pages[i]));
438
0
  }
439
440
  // show the page table
441
0
  out << "page table:" << std::endl;
442
0
  for (size_t i = 0; i < pdescs.size(); ++i) {
443
0
    out << pdescs[i] << "|";
444
0
    if (((i+1) % rowSize) == 0) {
445
0
      out << std::endl << std::string(rowSize * (cellSize + 1), '-') << std::endl;
446
0
    }
447
0
  }
448
0
  if (pdescs.size() < this->fdata->pages.size()) {
449
0
    out << "..." << std::endl;
450
0
  }
451
0
  out << std::endl;
452
0
}
453
454
0
void reader::show(std::ostream& out) const {
455
0
  showEnvironment(out);
456
0
}
457
458
// the interface for writing data archives
459
0
writer::writer(const std::string& path) : reader(openFile(path, false, 0, HFREGION_CURRENT_FILE_FORMAT_VERSION)) {
460
0
}
461
462
0
void* writer::unsafeDefine(const std::string& vn, const MonoTypePtr& ty) {
463
0
  return allocNamed(vn, ty, storageSizeOf(ty));
464
0
}
465
466
0
void* writer::unsafeDefineDArray(const std::string& vn, const MonoTypePtr& ty, size_t len) {
467
  // allocate an extra bit of space in this array data to store the actual allocated length
468
0
  size_t datasz = sizeof(long) + sizeof(long) + (len * storageSizeOf(ty));
469
0
  unsigned char* result = reinterpret_cast<unsigned char*>(allocNamed(vn, darrayty(ty), datasz));
470
0
  *reinterpret_cast<uint64_t*>(result) = datasz;
471
0
  return reinterpret_cast<void*>(result + sizeof(long));
472
0
}
473
474
0
void* writer::unsafeDefineArray(const std::string& vn, const MonoTypePtr& ty, size_t len) {
475
0
  size_t datasz = sizeof(long) + (len * storageSizeOf(ty));
476
0
  unsigned char* result = reinterpret_cast<unsigned char*>(allocNamed(vn, arrayty(ty), datasz));
477
0
  *reinterpret_cast<uint64_t*>(result) = len;
478
0
  return result;
479
0
}
480
481
0
void* writer::allocNamed(const std::string& vn, const MonoTypePtr& ty, size_t datasz) {
482
  // make sure that we're not redefining a value that's already defined
483
0
  if (this->fdata->bindings.find(vn) != this->fdata->bindings.end()) {
484
0
    throw std::runtime_error("Variable already defined in database: " + vn);
485
0
  }
486
487
  // allocate space for the data
488
0
  size_t dloc = findSpace(this->fdata, pagetype::data, datasz, alignment(ty));
489
490
  // add the environment binding
491
0
  bytes ety; encode(ty, &ety);
492
0
  addBinding(this->fdata, vn, ety, dloc);
493
0
  addSBinding(vn, ty, dloc);
494
495
  // get the mapped address of this data
496
0
  return mapFileData(this->fdata, dloc, datasz);
497
0
}
498
499
0
void* writer::unsafeStore(const MonoTypePtr& ty) {
500
0
  return allocAnon(storageSizeOf(ty), alignment(ty));
501
0
}
502
503
0
void* writer::unsafeStore(size_t sz, size_t align) {
504
0
  return allocAnon(sz, align);
505
0
}
506
507
0
uint64_t writer::unsafeStoreToOffset(size_t sz, size_t align) {
508
0
  return findSpace(this->fdata, pagetype::data, sz, align);
509
0
}
510
511
0
void* writer::unsafeStoreDArray(size_t esize, size_t len) {
512
0
  size_t datasz = sizeof(long) + sizeof(long) + (len * esize);
513
0
  auto* result = reinterpret_cast<unsigned char*>(allocAnon(datasz, sizeof(size_t)));
514
0
  *reinterpret_cast<long*>(result) = datasz;
515
0
  return reinterpret_cast<void*>(result + sizeof(long));
516
0
}
517
518
0
uint64_t writer::unsafeStoreDArrayToOffset(size_t esize, size_t len) {
519
0
  void*    p = unsafeStoreDArray(esize, len);
520
0
  uint64_t r = unsafeOffsetOfVal(true, p);
521
522
0
  unsafeUnloadDArray(p);
523
0
  return r;
524
0
}
525
526
0
void* writer::unsafeStoreArray(size_t esize, size_t len) {
527
0
  if (len > 0) {
528
0
    auto* result = reinterpret_cast<unsigned char*>(allocAnon(sizeof(long) + (len * esize), sizeof(size_t)));
529
0
    *reinterpret_cast<long*>(result) = len;
530
0
    return result;
531
0
  } else {
532
0
    return mapFileData(this->fdata, this->fdata->empty_array, sizeof(size_t));
533
0
  }
534
0
}
535
536
0
uint64_t writer::unsafeStoreArrayToOffset(size_t esize, size_t len) {
537
0
  void*    p = unsafeStoreArray(esize, len);
538
0
  uint64_t r = unsafeOffsetOfVal(false, p);
539
540
0
  unsafeUnloadArray(p, esize);
541
0
  return r;
542
0
}
543
544
0
void writer::signalUpdate() {
545
  // write a (safe) dummy byte to the file header to trigger an update signal
546
0
  seekAbs(this->fdata, 0);
547
0
  write(this->fdata, static_cast<uint8_t>(0x0d));
548
0
}
549
550
0
void* writer::allocAnon(size_t datasz, size_t align) {
551
  // allocate space for this data
552
0
  size_t dloc = findSpace(this->fdata, pagetype::data, datasz, align);
553
554
  // get the mapped address of this data
555
0
  return mapFileData(this->fdata, dloc, datasz);
556
0
}
557
558
// convenience storage methods
559
0
fileref<array<char>*> writer::store(const char* x, size_t sz) {
560
0
  return store(x, x + sz);
561
0
}
562
563
0
fileref<array<char>*> writer::store(const char* x) {
564
0
  return store(x, strlen(x));
565
0
}
566
567
0
fileref<array<char>*> writer::store(const array<char>* x) {
568
0
  return store(x->data, x->size);
569
0
}
570
571
0
fileref<array<char>*> writer::store(const std::string& x) {
572
0
  return store(x.begin(), x.end());
573
0
}
574
575
// create every directory in a path if it doesn't exist already
576
//  (equivalent to 'mkdir -p')
577
0
void ensureDirExists(const std::string& path) {
578
0
  str::seq ps = str::csplit(path, "/");
579
0
  std::ostringstream pfx;
580
581
0
  for (const auto& p : ps) {
582
0
    pfx << p << "/";
583
0
    if (mkdir(pfx.str().c_str(), S_IRWXU | S_IRWXG | S_IRWXO) == -1 && errno != EEXIST && errno != EISDIR) {
584
0
      throw std::runtime_error("Failed to make directory '" + pfx.str() + "' with error: " + strerror(errno));
585
0
    }
586
0
  }
587
0
}
588
589
0
std::string withUniqueFilenameBy(const std::string& fprefix, const std::string& fsuffix, const std::function<bool(const std::string&)>& fileOp) {
590
  // the directory that this file is in can be created if necessary
591
0
  ensureDirExists(str::rsplit(fprefix, "/").first);
592
593
  // keep trying for new filenames until we get one that's distinct
594
0
  size_t inst = 0;
595
0
  while (true) {
596
0
    std::ostringstream ss;
597
0
    ss << fprefix << "-" << inst << fsuffix;
598
0
    if (fileOp(ss.str())) {
599
0
      return ss.str();
600
0
    }
601
0
    ++inst;
602
0
  }
603
0
}
604
605
// generate a new file with a given prefix & suffix
606
0
std::string uniqueFilename(const std::string& fprefix, const std::string& fsuffix) {
607
0
  return withUniqueFilenameBy(fprefix, fsuffix, [](const std::string& newpath) {
608
0
    int fd = open(newpath.c_str(), O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
609
0
    if (fd >= 0) {
610
0
      close(fd);
611
0
      return true;
612
0
    } else if (errno == EEXIST) {
613
0
      return false;
614
0
    } else {
615
0
      throw std::runtime_error("Failed to generate a log database file with error: " + std::string(strerror(errno)));
616
0
    }
617
0
  });
618
0
}
619
620
// move an existing file to a new file with a given prefix & suffix
621
0
std::string moveToUniqueFilename(const std::string& oldpath, const std::string& fprefix, const std::string& fsuffix) {
622
0
  return withUniqueFilenameBy(fprefix, fsuffix, [&oldpath](const std::string& newpath) {
623
0
    int rt = link(oldpath.c_str(), newpath.c_str());
624
0
    if (rt == 0) {
625
0
      unlink(oldpath.c_str());
626
0
      return true;
627
0
    } else if (errno == EEXIST) {
628
0
      return false;
629
0
    } else {
630
0
      throw std::runtime_error("Failed to move to a log database file with error: " + std::string(strerror(errno)));
631
0
    }
632
0
  });
633
0
}
634
635
// take a file for one writer, or find that another writer already has it
636
//  (flock rather than fcntl/lockf because the lock has to belong to the open
637
//   file and not to the process: a second writer opened on the file by the
638
//   same process must neither succeed in taking it nor, when it is closed,
639
//   drop the lock that the first writer holds)
640
0
bool lockForWriting(writer* f) {
641
0
  return flock(f->unsafeGetFD(), LOCK_EX | LOCK_NB) == 0;
642
0
}
643
644
}
645