forked from nlitsme/idbutil
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathidb3.h
2150 lines (1912 loc) · 61.2 KB
/
idb3.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* idb3.h is a library for accessing IDApro databases.
*
* Author: Willem Hengeveld <[email protected]>
*
*
* Toplevel class: IDBFile, use getsection to get a stream to the desired section,
* Then create an ID0File, ID1File, NAMFile for that section.
*
*/
#include <iostream>
#include <sstream>
#include <vector>
#include <set>
#include <cassert>
#include "formatter.h"
#define dbgprint(...)
// a sharedptr, so i can pass an istream around without
// worrying about who owns it.
typedef std::shared_ptr<std::istream> stream_ptr;
// create vector from `n` invocations of `f`
template<typename T, typename FN>
std::vector<T> getvec(int n, FN f)
{
std::vector<T> v;
while (n--)
v.push_back(f());
return v;
}
////////////////////////////////////////////////////////////////////////
// Sometimes i need to pass backinserter iterators as <first, last> pair
// These functions make that possible.
// ANY - backinserter == INT_MAX -> always enough space after a backinserter
template<typename T, typename C>
int operator-(T lhs, typename std::back_insert_iterator<C> rhs)
{
return INT_MAX;
}
// backinserter += INT -> does nothing
template<typename C>
typename std::back_insert_iterator<C>& operator+=(typename std::back_insert_iterator<C>& rhs, int n)
{
return rhs;
}
// streamhelper: get little/big endian integers of various sizes from a stream
// There are functions for 8, 16, 32, 64 bit little/big endian unsigned integers.
// And a function for reading a database dependent word (64bit for .i64, 32bit for .idb)
template<typename ISPTR>
class streamhelper {
ISPTR _is;
int _wordsize; // the wordsize of the current database
public:
streamhelper(ISPTR is, int wordsize)
: _is(is), _wordsize(wordsize)
{
}
uint8_t get8()
{
auto c = _is->get();
if (c==-1)
throw "EOF";
return (uint8_t)c;
}
uint16_t get16le()
{
uint8_t lo = get8();
uint8_t hi = get8();
return (hi<<8) | lo;
}
uint16_t get16be()
{
uint8_t hi = get8();
uint8_t lo = get8();
return (hi<<8) | lo;
}
uint32_t get32le()
{
uint16_t lo = get16le();
uint16_t hi = get16le();
return (hi<<16) | lo;
}
uint32_t get32be()
{
uint16_t hi = get16be();
uint16_t lo = get16be();
return (hi<<16) | lo;
}
uint64_t get64le()
{
uint32_t lo = get32le();
uint32_t hi = get32le();
return (uint64_t(hi)<<32) | lo;
}
uint64_t get64be()
{
uint32_t hi = get32be();
uint32_t lo = get32be();
return (uint64_t(hi)<<32) | lo;
}
// function used to get the right wordsize for either .i64 or .idb file.
uint64_t getword()
{
if (_wordsize==4)
return get32le();
else if (_wordsize==8)
return get64le();
throw "unsupported wordsize";
}
std::string getdata(int n)
{
std::string str(n, char(0));
auto m = _is->readsome(&str.front(), n);
str.resize(m);
dbgprint("getdata -> %b\n", str);
return str;
}
std::istream& seekg( std::istream::off_type off, std::ios_base::seekdir dir)
{
return _is->seekg(off, dir);
}
std::istream& seekg( std::istream::pos_type pos )
{
return _is->seekg(pos);
}
};
// function for creating a streamhelper.
template<typename ISPTR>
auto makehelper(ISPTR is, int wordsize = 0)
{
return streamhelper<ISPTR>(is, wordsize);
}
// EndianTools: a collection of static functions for reading/writing
// little/big endian integers of various sizes from an iterator range
struct EndianTools {
template<typename P>
static void set8(P first, P last, uint8_t w)
{
if (last-first < 1)
throw "not enough space";
*first = w;
}
template<typename P, typename T>
static void setbe16(P first, P last, T w)
{
P p = first;
if (last-p < 2)
throw "not enough space";
set8(p, last, w>>8); p += 1;
set8(p, last, w);
}
template<typename P, typename T>
static void setbe32(P first, P last, T w)
{
P p = first;
if (last-p < 4)
throw "not enough space";
setbe16(p, last, w>>16); p += 2;
setbe16(p, last, w);
}
template<typename P, typename T>
static void setbe64(P first, P last, T w)
{
P p = first;
if (last-p < 8)
throw "not enough space";
setbe32(p, last, w>>32); p += 4;
setbe32(p, last, w);
}
template<typename P, typename T>
static void setle16(P first, P last, T w)
{
P p = first;
if (last-p < 2)
throw "not enough space";
set8(p, last, w); p += 1;
set8(p, last, w>>8);
}
template<typename P, typename T>
static void setle32(P first, P last, T w)
{
P p = first;
if (last-p < 4)
throw "not enough space";
setle16(p, last, w); p += 2;
setle16(p, last, w>>16);
}
template<typename P, typename T>
static void setle64(P first, P last, T w)
{
P p = first;
if (last-p < 8)
throw "not enough space";
setle32(p, last, w); p += 4;
setle32(p, last, w>>32);
}
template<typename P>
static uint8_t get8(P first, P last)
{
if (first>=last)
throw "not enough space";
return *first;
}
template<typename P>
static uint16_t getbe16(P first, P last)
{
P p = first;
if (last-p < 2)
throw "not enough space";
uint8_t hi =get8(p, last); p += 1;
uint8_t lo =get8(p, last);
return (uint16_t(hi)<<8) | lo;
}
template<typename P>
static uint32_t getbe32(P first, P last)
{
P p = first;
if (last-p < 4)
throw "not enough space";
uint16_t hi =getbe16(p, last); p += 2;
uint16_t lo =getbe16(p, last);
return (uint32_t(hi)<<16) | lo;
}
template<typename P>
static uint64_t getbe64(P first, P last)
{
P p = first;
if (last-p < 8)
throw "not enough space";
uint32_t hi =getbe32(p, last); p += 4;
uint32_t lo =getbe32(p, last);
return (uint64_t(hi)<<32) | lo;
}
template<typename P>
static uint16_t getle16(P first, P last)
{
P p = first;
if (last-p < 2)
throw "not enough space";
uint8_t lo =get8(p, last); p += 1;
uint8_t hi =get8(p, last);
return (uint16_t(hi)<<8) | lo;
}
template<typename P>
static uint32_t getle32(P first, P last)
{
P p = first;
if (last-p < 4)
throw "not enough space";
uint16_t lo =getle16(p, last); p += 2;
uint16_t hi =getle16(p, last);
return (uint32_t(hi)<<16) | lo;
}
template<typename P>
static uint64_t getle64(P first, P last)
{
P p = first;
if (last-p < 8)
throw "not enough space";
uint32_t lo =getle32(p, last); p += 4;
uint32_t hi =getle32(p, last);
return (uint64_t(hi)<<32) | lo;
}
};
// stream buffer for sectionstream
// This is the class doing the actual work for sectionstream.
// This presents a view of a section of a random access stream.
class sectionbuffer : public std::streambuf {
stream_ptr _is;
std::streamoff _first;
std::streamoff _last;
std::streampos _curpos;
public:
sectionbuffer(stream_ptr is, uint64_t first, uint64_t last)
: _is(is), _first(first), _last(last), _curpos(0)
{
_is->seekg(_first);
}
protected:
std::streampos seekoff(std::streamoff off, std::ios_base::seekdir way, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out)
{
std::streampos newpos;
switch(way)
{
case std::ios_base::beg:
newpos = off;
break;
case std::ios_base::cur:
newpos = _curpos + off;
break;
case std::ios_base::end:
newpos = (_last-_first) + off;
break;
default:
throw std::ios_base::failure("bad seek direction");
}
return seekpos(newpos, which);
}
std::streampos seekpos(std::streampos sp, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out)
{
if (sp<0 || sp > (_last-_first))
return -1;
_is->seekg(sp+_first);
return _curpos = sp;
}
std::streamsize showmanyc()
{
return (_last-_first)-_curpos;
}
std::streamsize xsgetn(char_type* s, std::streamsize n)
{
if (n<=0 || _curpos >= (_last-_first))
return 0;
auto want = std::min(std::streamsize(_last-_first - _curpos), n);
//auto got = _is->readsome(s, want);
_is->read(s, want); auto got = want;
_curpos += got;
return got;
}
int_type underflow()
{
if (_curpos >= (_last-_first))
return traits_type::eof();
int r = _is->peek();
return r;
}
int_type uflow()
{
if (_curpos >= (_last-_first))
return traits_type::eof();
int r = _is->get();
if (r==traits_type::eof())
return traits_type::eof();
_curpos+=1;
return r;
}
};
// istream restricted to a section of a seakable stream
class sectionstream : public std::istream {
sectionbuffer _buf;
public:
template<typename ISPTR>
sectionstream(ISPTR is, uint64_t from, uint64_t size)
: std::istream(nullptr), _buf(is, from, from+size)
{
init(&_buf);
}
};
///////////////////////////////////////////////////////////////
// read .idb file, returns sectionstreams for sections
//
// IDBFile knows how to read sections from all types of IDApro databases.
//
// Compression is not yet supported.
class IDBFile {
stream_ptr _is;
uint32_t _magic;
int _fileversion;
std::vector<uint64_t> _offsets;
std::vector<uint32_t> _checksums;
public:
enum {
MAGIC_IDA2 = 0x32414449,
MAGIC_IDA1 = 0x31414449,
MAGIC_IDA0 = 0x30414449,
};
IDBFile(stream_ptr is)
: _is(is), _magic(0), _fileversion(-1)
{
readheader();
}
uint32_t magic() const { return _magic; }
void readheader()
{
auto s = makehelper(_is);
_magic = s.get32le();
/*zero = */ s.get16le();
auto values = getvec<uint32_t>(6, [&](){ return s.get32le(); });
if (values[5]!=0xaabbccdd) {
_fileversion = 0;
for (auto v : values)
_offsets.push_back(v);
_offsets[5] = 0;
_checksums.resize(6);
return;
}
_fileversion = s.get16le();
if (_fileversion < 5) {
/*auto unknown =*/ s.get32le();
for (auto v : values)
_offsets.push_back(v);
_offsets.pop_back();
_checksums = getvec<uint32_t>(5, [&](){ return s.get32le(); });
uint32_t idsofs = s.get32le();
uint32_t idscheck = _fileversion==1 ? s.get16le() : s.get32le();
_offsets.push_back(idsofs);
_checksums.push_back(idscheck);
// in filever==4 there is more in the .idb header:
// 0x5c, 0, 0, <md5>, 128*NUL
}
else {
// ver 5, 6 : 64 bit fileptrs
_offsets.push_back((uint64_t(values[1])<<32)|values[0]);
_offsets.push_back((uint64_t(values[3])<<32)|values[2]);
_offsets.push_back(s.get64le());
_offsets.push_back(s.get64le());
_offsets.push_back(s.get64le());
_checksums = getvec<uint32_t>(5, [&](){ return s.get32le(); });
_offsets.push_back(s.get64le());
_checksums.push_back(s.get32le());
// more data in the .idb header:
// 0x7c, 0, 0, <md5>, 128*NUL
}
}
void dump()
{
print("IDB v%d, m=%08x\n", _fileversion, _magic);
for (int i=0 ; i<std::max(_offsets.size(), _checksums.size()) ; i++)
print("%d: %10llx %08x\n", i, i<_offsets.size() ? _offsets[i] : -1, i<_checksums.size() ? _checksums[i] : -1);
}
auto getinfo(int i)
{
_is->seekg(_offsets[i]);
auto s = makehelper(_is);
auto comp = s.get8();
uint64_t size = _fileversion<5 ? s.get32le() : s.get64le();
uint64_t ofs = _offsets[i] + (_fileversion<5 ? 5 : 9);
return std::make_tuple(comp, ofs, size);
}
stream_ptr getsection(int i)
{
auto info = getinfo(i);
if (std::get<0>(info))
throw "compression not supported";
return std::make_shared<sectionstream>(_is, std::get<1>(info), std::get<2>(info));
}
};
// search relation
enum relation_t {
REL_LESS,
REL_LESS_EQUAL,
REL_EQUAL,
REL_GREATER_EQUAL,
REL_GREATER,
REL_RECURSE,
};
// baseclass for Btree Pages
// baseclass for Btree database, subclassed by v1.5, v1.6, v2.0
class BasePage {
protected:
stream_ptr _is;
int _pagesize;
uint32_t _nr;
uint32_t _preceeding;
int _count;
// item for the entry table
class Entry {
public:
uint32_t pagenr;
int indent;
int recofs;
Entry() : pagenr(0), indent(0), recofs(0) { }
Entry(Entry&& e) : pagenr(e.pagenr), indent(e.indent), recofs(e.recofs) { }
};
std::vector<Entry> _index;
std::vector<std::string> _keys; // only for leaf pages
// IntIter, used to be able to use upper_bound on `_index`
class IntIter : public std::iterator<std::random_access_iterator_tag, int> {
int _ix;
public:
IntIter(int x) : _ix(x) { }
IntIter() : _ix(0) { }
IntIter(const IntIter& i) : _ix(i._ix) { }
bool operator==(const IntIter& rhs) {return _ix==rhs._ix;}
bool operator!=(const IntIter& rhs) {return _ix!=rhs._ix;}
int operator*() {return _ix;}
int operator[](int i) {return _ix+i;}
IntIter& operator++() {++_ix;return *this;}
IntIter operator++(int) {IntIter tmp(*this); operator++(); return tmp;}
IntIter& operator--() {--_ix;return *this;}
IntIter operator--(int) {IntIter tmp(*this); operator--(); return tmp;}
IntIter& operator+=(int n) { _ix += n; return *this; }
IntIter& operator-=(int n) { _ix -= n; return *this; }
friend IntIter operator+(int n, IntIter p) { return p+=n; }
friend IntIter operator+(IntIter p, int n) { return p+=n; }
friend IntIter operator-(IntIter p, int n) { return p-=n; }
friend int operator-(const IntIter& p, const IntIter& q) { return p._ix-q._ix; }
bool operator<(const IntIter& rhs) { return _ix<rhs._ix; }
bool operator<=(const IntIter& rhs) { return _ix<=rhs._ix; }
bool operator>(const IntIter& rhs) { return _ix>rhs._ix; }
bool operator>=(const IntIter& rhs) { return _ix>=rhs._ix; }
};
// unused, iterator returning Entry's
class PageIter : public std::iterator<std::random_access_iterator_tag, Entry> {
BasePage* _page;
int _ix;
public:
PageIter(BasePage*page, int ix) : _page(page), _ix(ix) { }
PageIter() : _page(nullptr), _ix(0) { }
PageIter(const PageIter& i) : _page(i._page), _ix(i._ix) { }
bool operator==(const PageIter& rhs) {return _ix==rhs._ix;}
bool operator!=(const PageIter& rhs) {return _ix!=rhs._ix;}
Entry& operator*() {return _page->getent(_ix);}
Entry& operator[](int i) {return _page->getent(_ix+i);}
PageIter& operator++() {++_ix;return *this;}
PageIter operator++(int) {PageIter tmp(*this); operator++(); return tmp;}
PageIter& operator--() {--_ix;return *this;}
PageIter operator--(int) {PageIter tmp(*this); operator--(); return tmp;}
PageIter& operator+=(int n) { _ix += n; return *this; }
PageIter& operator-=(int n) { _ix -= n; return *this; }
friend PageIter operator+(int n, PageIter p) { return p+=n; }
friend PageIter operator+(PageIter p, int n) { return p+=n; }
friend PageIter operator-(PageIter p, int n) { return p-=n; }
friend int operator-(const PageIter& p, const PageIter& q) { return p._ix-q._ix; }
bool operator<(const PageIter& rhs) { return _ix<rhs._ix; }
bool operator<=(const PageIter& rhs) { return _ix<=rhs._ix; }
bool operator>(const PageIter& rhs) { return _ix>rhs._ix; }
bool operator>=(const PageIter& rhs) { return _ix>=rhs._ix; }
};
public:
BasePage(stream_ptr is, uint32_t nr, int pagesize)
: _is(is), _pagesize(pagesize), _nr(nr), _preceeding(0), _count(0)
{
}
uint32_t nr() const { return _nr; }
bool isindex() const { return _preceeding!=0; }
bool isleaf() const { return _preceeding==0; }
size_t indexsize() const { return _index.size(); }
virtual Entry readent() = 0;
void dump()
{
if (_preceeding)
print("prec = %05x\n", _preceeding);
for (int i=0 ; i<_index.size() ; i++)
print("%-b = %-b\n", getkey(i), getval(i));
}
void readindex()
{
for (int i=0 ; i<_count ; i++)
_index.emplace_back(readent());
//print("got %d entries\n", _index.size());
if (isleaf())
readkeys();
}
// for a leafpage, calculate all key values
void readkeys()
{
auto s = makehelper(_is);
std::string key;
for (auto & ent : _index) {
_is->seekg(ent.recofs);
int klen = s.get16le();
key.resize(klen+ent.indent);
_is->read(&key[ent.indent], klen);
dbgprint("key i=%d, l=%d -> %b\n", ent.indent, klen, key);
_keys.push_back(key);
}
}
// get the subpage for the item at positon `i`
uint32_t getpage(int i) const
{
if (!isindex())
throw "getpage called on leaf";
if (i<0)
return _preceeding;
if (i>=_index.size()) {
print("#%06x i=%d, max=%d\n", _nr, i, _index.size());
throw "page: i too large";
}
return _index[i].pagenr;
}
// get key for the item at position `i`
std::string getkey(int i)
{
auto& ent = getent(i);
if (isindex()) {
_is->seekg(ent.recofs);
auto s = makehelper(_is);
int klen = s.get16le();
dbgprint("indexkey(%d) -> l=%d\n", i, klen);
return s.getdata(klen);
}
else if (isleaf()) {
dbgprint("leafkey(%d)\n", i);
return _keys[i];
}
throw "not a leaf of index";
}
// get value for the item at position `i`
std::string getval(int i)
{
auto& ent = getent(i);
_is->seekg(ent.recofs);
auto s = makehelper(_is);
int klen = s.get16le();
_is->seekg(klen, std::ios_base::cur);
int vlen = s.get16le();
dbgprint("%04x: val(%d), kl=%d, vl=%d\n", ent.recofs, i, klen, vlen);
return s.getdata(vlen);
}
Entry& getent(int i) {
if (i<0 || i>=_index.size())
throw "invalid key index";
return _index[i];
}
// unused
//auto begin() { return PageIter(this, 0); }
//auto end() { return PageIter(this, _count); }
struct result {
relation_t act;
int index;
bool operator==(const result& rhs) const { return act==rhs.act && index==rhs.index; }
bool operator!=(const result& rhs) const { return !(*this==rhs); }
friend std::ostream& operator<<(std::ostream& os, const result& res)
{
os << '{';
switch(res.act)
{
case REL_LESS: os << "<"; break;
case REL_LESS_EQUAL: os << "<="; break;
case REL_EQUAL: os << "=="; break;
case REL_GREATER_EQUAL: os << ">="; break;
case REL_GREATER: os << ">"; break;
case REL_RECURSE: os << "r"; break;
default: os << "?";
}
os << res.index;
os << '}';
return os;
}
};
// search for the key in this page.
// getkey(index) ... act ... key
result find(const std::string& key)
{
//auto i = std::upper_bound(begin(), end(), key, [](const std::string& key, const Entry& ent){ return false; });
auto i = std::upper_bound(IntIter(0), IntIter(_count), key, [this](const std::string& key, int ix){ return key < this->getkey(ix); });
if (i==IntIter(0)) {
if (isindex())
return {REL_RECURSE, -1};
return {REL_GREATER, 0}; // index[0] > key
}
--i;
int ix = i-IntIter(0);
if (getkey(ix) == key)
return {REL_EQUAL, ix};
if (isindex())
return {REL_RECURSE, ix};
return {REL_LESS, ix}; // index[ix] < key
}
};
typedef std::shared_ptr<BasePage> Page_ptr;
// baseclass for Btree database, subclassed by v1.5, v1.6, v2.0
class BtreeBase {
protected:
stream_ptr _is;
uint32_t _firstindex;
uint32_t _pagesize;
uint32_t _firstfree;
uint32_t _reccount;
uint32_t _pagecount;
public:
class Cursor {
BtreeBase *_bt;
struct ent {
Page_ptr page;
int index;
ent(Page_ptr page, int index)
: page(page), index(index)
{
}
ent() : index(0) { }
bool operator==(const ent& rhs) const { return page==rhs.page && index==rhs.index; }
bool operator!=(const ent& rhs) const { return !(*this==rhs); }
};
std::vector<ent> _stack;
void dump() const {
std::stringstream x;
for (auto& ent : _stack)
x << stringformat(" %05x:%d", ent.page->nr(), ent.index);
std::cout << x.str() << std::endl;
}
public:
Cursor(BtreeBase *bt)
: _bt(bt)
{
}
void clear()
{
_stack.clear();
}
void next()
{
if (eof())
throw "cursor:EOF";
auto ent = _stack.back(); _stack.pop_back();
if (ent.page->isleaf()) {
// from leaf move towards root
ent.index++;
while (!_stack.empty() && ent.index==ent.page->indexsize()) {
ent = _stack.back(); _stack.pop_back();
ent.index++;
}
if (ent.index<ent.page->indexsize()) {
add(ent.page, ent.index);
}
}
else {
// from node move towards leaf
add(ent.page, ent.index);
ent.page = _bt->readpage(ent.page->getpage(ent.index));
while (ent.page->isindex()) {
ent.index = -1;
add(ent.page, ent.index);
ent.page = _bt->readpage(ent.page->getpage(ent.index));
}
ent.index = 0;
add(ent.page, ent.index);
}
}
void prev()
{
if (eof())
throw "cursor:EOF";
auto ent = _stack.back(); _stack.pop_back();
ent.index--;
if (ent.page->isleaf()) {
while (!_stack.empty() && ent.index<0) {
ent = _stack.back(); _stack.pop_back();
}
if (ent.index>=0)
add(ent.page, ent.index);
}
else {
add(ent.page, ent.index);
while (ent.page->isindex()) {
ent.page = _bt->readpage(ent.page->getpage(ent.index));
ent.index = ent.page->indexsize()-1;
add(ent.page, ent.index);
}
}
}
bool eof() const
{
return _stack.empty();
}
// for Btree.find to create cursor.
void add(Page_ptr page, int index)
{
_stack.emplace_back(page, index);
}
// getting key/value from cursor pos
auto getkey() const
{
if (eof())
throw "cursor:EOF";
auto ent = _stack.back();
return ent.page->getkey(ent.index);
}
auto getval() const
{
if (eof())
throw "cursor:EOF";
auto ent = _stack.back();
return ent.page->getval(ent.index);
}
bool operator==(const Cursor& rhs) const { return _stack == rhs._stack; }
bool operator!=(const Cursor& rhs) const { return !(*this==rhs); }
bool operator<(const Cursor& rhs) const { return getkey() < rhs.getkey(); }
};
BtreeBase(stream_ptr is) : _is(is) { }
virtual ~BtreeBase() { }
virtual int version() const = 0;
virtual void readheader() = 0;
virtual Page_ptr makepage(int nr) = 0;
Page_ptr readpage(int nr)
{
auto page = makepage(nr);
page->readindex();
return page;
}
void dump()
{
print("btree v%02d ff=%d, pg=%d, root=%05x, #recs=%d #pgs=%d\n",
version(), _firstfree, _pagesize, _firstindex, _reccount, _pagecount);
dumptree(_firstindex);
}
void dumptree(int nr)
{
auto page = readpage(nr);
page->dump();
if (page->isindex()) {
dumptree(page->getpage(-1));
for (int i=0 ; i<page->indexsize() ; i++)
dumptree(page->getpage(i));
}
}
stream_ptr pagestream(int nr)
{
return std::make_shared<sectionstream>(_is, nr*_pagesize, _pagesize);
}
Cursor find(relation_t rel, const std::string& key)
{
auto page = readpage(_firstindex);
Cursor cursor(this);
relation_t act;
while (true)
{
auto res = page->find(key);
dbgprint("bt.find %d : %d\n", res.act, res.index);
cursor.add(page, res.index);
if (res.act != REL_RECURSE)
{
act = res.act;
break;
}
page = readpage(page->getpage(res.index));
}
if (act == rel) {
dbgprint("same -> pass\n");
// pass
}
else if (rel==REL_EQUAL && act!=REL_EQUAL) {
cursor.clear();
dbgprint("not equal -> empty\n");
}
else if ((rel==REL_LESS_EQUAL || rel==REL_GREATER_EQUAL) && act==REL_EQUAL) {
dbgprint("want: <=/>=, got: == -> pass\n");
// pass
}
else if ((rel==REL_GREATER || rel==REL_GREATER_EQUAL) && act==REL_LESS) {
dbgprint("want: >/>=, got: < -> next\n");
cursor.next();
}
else if (rel==REL_GREATER && act==REL_EQUAL) {
dbgprint("want: >, got: == -> next\n");
cursor.next();
}
else if ((rel==REL_LESS || rel==REL_LESS_EQUAL) && act==REL_GREATER) {
dbgprint("want: </<=, got: > -> prev\n");
cursor.prev();
}
else if (rel==REL_LESS && act==REL_EQUAL) {
dbgprint("want: <, got: == -> prev\n");
cursor.prev();
}
return cursor;
}
};
class Page15 : public BasePage {
public:
Page15(stream_ptr is, uint32_t nr, int pagesize)
: BasePage(is, nr, pagesize)
{
auto s = makehelper(_is);
_preceeding = s.get16le();
_count = s.get16le();
}
virtual Entry readent()
{
auto s = makehelper(_is);
if (isindex()) {
Entry ent;
ent.pagenr = s.get16le();
ent.recofs = s.get16le()+1;
dbgprint("@%04x: ix ent15 %08x %04x\n", (int)_is->tellg(), ent.pagenr, ent.recofs);
return ent;
}
else if (isleaf()) {
Entry ent;
ent.indent = s.get8();
/*ent.unknown = */s.get8();
ent.recofs = s.get16le()+1;
dbgprint("@%04x: lf ent15 %+4d %04x\n", (int)_is->tellg(), ent.indent, ent.recofs);
return ent;
}
throw "page not a index or leaf";
}
};
class Btree15 : public BtreeBase {
public:
Btree15(stream_ptr is) : BtreeBase(is) { }
int version() const { return 15; }
void readheader()
{
_is->seekg(0);
auto s = makehelper(_is);
_firstfree = s.get16le();
_pagesize = s.get16le();
_firstindex = s.get16le();
_reccount = s.get32le();
_pagecount = s.get16le();
}
virtual Page_ptr makepage(int nr)
{
dbgprint("page15\n");
return std::make_shared<Page15>(pagestream(nr), nr, _pagesize);