source: tags/ms_r18q1/ARBDB/arbdb.cxx

Last change on this file was 16986, checked in by westram, 6 years ago

Update: continued by [17178]

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 85.5 KB
Line 
1// =============================================================== //
2//                                                                 //
3//   File      : arbdb.cxx                                         //
4//   Purpose   :                                                   //
5//                                                                 //
6//   Institute of Microbiology (Technical University Munich)       //
7//   http://www.arb-home.de/                                       //
8//                                                                 //
9// =============================================================== //
10
11#include "gb_key.h"
12#include "gb_comm.h"
13#include "gb_compress.h"
14#include "gb_localdata.h"
15#include "gb_ta.h"
16#include "gb_ts.h"
17#include "gb_index.h"
18
19#include <rpc/types.h>
20#include <rpc/xdr.h>
21#include <arb_misc.h>
22
23gb_local_data *gb_local = NULp;
24
25#define INIT_TYPE_NAME(t) GB_TYPES_name[t] = #t
26
27static const char *GB_TYPES_2_name(GB_TYPES type) {
28    static const char *GB_TYPES_name[GB_TYPE_MAX];
29    static bool        initialized = false;
30
31    if (!initialized) {
32        memset(GB_TYPES_name, 0, sizeof(GB_TYPES_name));
33        INIT_TYPE_NAME(GB_NONE);
34        INIT_TYPE_NAME(GB_BIT);
35        INIT_TYPE_NAME(GB_BYTE);
36        INIT_TYPE_NAME(GB_INT);
37        INIT_TYPE_NAME(GB_FLOAT);
38        INIT_TYPE_NAME(GB_POINTER);
39        INIT_TYPE_NAME(GB_BITS);
40        INIT_TYPE_NAME(GB_BYTES);
41        INIT_TYPE_NAME(GB_INTS);
42        INIT_TYPE_NAME(GB_FLOATS);
43        INIT_TYPE_NAME(GB_STRING);
44        INIT_TYPE_NAME(GB_STRING_SHRT);
45        INIT_TYPE_NAME(GB_DB);
46
47        GB_TYPES_name[GB_OBSOLETE] = "GB_LINK (obsolete)";
48
49        initialized = true;
50    }
51
52    const char *name = NULp;
53    if (type >= 0 && type<GB_TYPE_MAX) name = GB_TYPES_name[type];
54    if (!name) {
55        static char *unknownType = NULp;
56        freeset(unknownType, GBS_global_string_copy("<invalid-type=%i>", type));
57        name = unknownType;
58    }
59    return name;
60}
61
62const char *GB_get_type_name(GBDATA *gbd) {
63    return GB_TYPES_2_name(gbd->type());
64}
65
66inline GB_ERROR gb_transactable_type(GB_TYPES type, GBDATA *gbd) {
67    GB_ERROR error = NULp;
68    if (GB_MAIN(gbd)->get_transaction_level() == 0) {
69        error = "No transaction running";
70    }
71    else if (GB_ARRAY_FLAGS(gbd).changed == GB_DELETED) {
72        error = "Entry has been deleted";
73    }
74    else {
75        GB_TYPES gb_type = gbd->type();
76        if (gb_type != type && (type != GB_STRING || gb_type != GB_OBSOLETE)) {
77            char *rtype    = ARB_strdup(GB_TYPES_2_name(type));
78            char *rgb_type = ARB_strdup(GB_TYPES_2_name(gb_type));
79           
80            error = GBS_global_string("type mismatch (want='%s', got='%s') in '%s'", rtype, rgb_type, GB_get_db_path(gbd));
81
82            free(rgb_type);
83            free(rtype);
84        }
85    }
86    if (error) {
87        GBK_dump_backtrace(stderr, error); // it's a bug: none of the above errors should ever happen
88        gb_assert(0);
89    }
90    return error;
91}
92
93__ATTR__USERESULT static GB_ERROR gb_security_error(GBDATA *gbd) {
94    GB_MAIN_TYPE *Main  = GB_MAIN(gbd);
95    const char   *error = GBS_global_string("Protection: Attempt to change a level-%i-'%s'-entry,\n"
96                                            "but your current security level is only %i",
97                                            GB_GET_SECURITY_WRITE(gbd),
98                                            GB_read_key_pntr(gbd),
99                                            Main->security_level);
100#if defined(DEBUG)
101    fprintf(stderr, "%s\n", error);
102#endif // DEBUG
103    return error;
104}
105
106inline GB_ERROR gb_type_writeable_to(GB_TYPES type, GBDATA *gbd) {
107    GB_ERROR error = gb_transactable_type(type, gbd);
108    if (!error) {
109        if (GB_GET_SECURITY_WRITE(gbd) > GB_MAIN(gbd)->security_level) {
110            error = gb_security_error(gbd);
111        }
112    }
113    return error;
114}
115inline GB_ERROR gb_type_readable_from(GB_TYPES type, GBDATA *gbd) {
116    return gb_transactable_type(type, gbd);
117}
118
119inline GB_ERROR error_with_dbentry(const char *action, GBDATA *gbd, GB_ERROR error) {
120    if (error) {
121        char       *error_copy = ARB_strdup(error);
122        const char *path       = GB_get_db_path(gbd);
123        error                  = GBS_global_string("Can't %s '%s':\n%s", action, path, error_copy);
124        free(error_copy);
125    }
126    return error;
127}
128
129
130#define RETURN_ERROR_IF_NOT_WRITEABLE_AS_TYPE(gbd,type)         \
131    do {                                                        \
132        GB_ERROR error = gb_type_writeable_to(type, gbd);       \
133        if (error) {                                            \
134            return error_with_dbentry("write", gbd, error);     \
135        }                                                       \
136    } while(0)
137
138#define EXPORT_ERROR_AND_RETURN_RES_IF_NOT_READABLE_AS_TYPE(gbd,res,type)       \
139    do {                                                                        \
140        GB_ERROR error = gb_type_readable_from(type, gbd);                      \
141        if (error) {                                                            \
142            error = error_with_dbentry("read", gbd, error);                     \
143            GB_export_error(error);                                             \
144            return res;                                                         \
145        }                                                                       \
146    } while(0)                                                                  \
147
148
149// @@@ replace GB_TEST_READ_NUM, GB_TEST_READ_PTR and GB_TEST_READ by new names
150
151#define GB_TEST_READ_NUM(gbd,type,ignored) EXPORT_ERROR_AND_RETURN_RES_IF_NOT_READABLE_AS_TYPE(gbd,0,type)
152#define GB_TEST_READ_PTR(gbd,type,ignored) EXPORT_ERROR_AND_RETURN_RES_IF_NOT_READABLE_AS_TYPE(gbd,NULp,type)
153#define GB_TEST_WRITE(gbd,type,ignored)    RETURN_ERROR_IF_NOT_WRITEABLE_AS_TYPE(gbd, type)
154
155#define GB_TEST_NON_BUFFER(x, gerror)                                   \
156    do {                                                                \
157        if (GB_is_in_buffer(x)) {                                       \
158            GBK_terminatef("%s: you are not allowed to write any data, which you get by pntr", gerror); \
159        }                                                               \
160    } while (0)
161
162
163static GB_ERROR GB_safe_atof(const char *str, float *res) {
164    GB_ERROR error = NULp;
165
166    char *end;
167    *res = strtof(str, &end);
168
169    if (end == str || end[0] != 0) {
170        if (!str[0]) {
171            *res = 0.0;
172        }
173        else {
174            error = GBS_global_string("cannot convert '%s' to float", str);
175        }
176    }
177    return error;
178}
179
180float GB_atof(const char *str) {
181    // convert ASCII to float
182    float    res = 0;
183    GB_ERROR err = GB_safe_atof(str, &res);
184    if (err) {
185        // expected float in 'str'- better use GB_safe_atof()
186        GBK_terminatef("GB_safe_atof(\"%s\", ..) returns error: %s", str, err);
187    }
188    return res;
189}
190
191// ---------------------------
192//      compression tables
193
194const int gb_convert_type_2_compression_flags[] = {
195    GB_COMPRESSION_NONE,                                                                 // GB_NONE  0
196    GB_COMPRESSION_NONE,                                                                 // GB_BIT   1
197    GB_COMPRESSION_NONE,                                                                 // GB_BYTE  2
198    GB_COMPRESSION_NONE,                                                                 // GB_INT   3
199    GB_COMPRESSION_NONE,                                                                 // GB_FLOAT 4
200    GB_COMPRESSION_NONE,                                                                 // GB_??    5
201    GB_COMPRESSION_BITS,                                                                 // GB_BITS  6
202    GB_COMPRESSION_NONE,                                                                 // GB_??    7
203    GB_COMPRESSION_RUNLENGTH | GB_COMPRESSION_HUFFMANN,                                  // GB_BYTES 8
204    GB_COMPRESSION_RUNLENGTH | GB_COMPRESSION_HUFFMANN | GB_COMPRESSION_SORTBYTES,       // GB_INTS  9
205    GB_COMPRESSION_RUNLENGTH | GB_COMPRESSION_HUFFMANN | GB_COMPRESSION_SORTBYTES,       // GB_FLTS 10
206    GB_COMPRESSION_NONE,                                                                 // GB_LINK 11
207    GB_COMPRESSION_RUNLENGTH | GB_COMPRESSION_HUFFMANN | GB_COMPRESSION_DICTIONARY,      // GB_STR  12
208    GB_COMPRESSION_NONE,                                                                 // GB_STRS 13
209    GB_COMPRESSION_NONE,                                                                 // GB??    14
210    GB_COMPRESSION_NONE                                                                  // GB_DB   15
211};
212
213int gb_convert_type_2_sizeof[] = { /* contains the unit-size of data stored in DB,
214                                    * i.e. realsize = unit_size * size()
215                                    */
216    0,                                              // GB_NONE  0
217    0,                                              // GB_BIT   1
218    sizeof(char),                                   // GB_BYTE  2
219    sizeof(int),                                    // GB_INT   3
220    sizeof(float),                                  // GB_FLOAT 4
221    0,                                              // GB_??    5
222    0,                                              // GB_BITS  6
223    0,                                              // GB_??    7
224    sizeof(char),                                   // GB_BYTES 8
225    sizeof(int),                                    // GB_INTS  9
226    sizeof(float),                                  // GB_FLTS 10
227    sizeof(char),                                   // GB_LINK 11
228    sizeof(char),                                   // GB_STR  12
229    sizeof(char),                                   // GB_STRS 13
230    0,                                              // GB_??   14
231    0,                                              // GB_DB   15
232};
233
234int gb_convert_type_2_appendix_size[] = { /* contains the size of the suffix (aka terminator element)
235                                           * size is in bytes
236                                           */
237
238    0,                                              // GB_NONE  0
239    0,                                              // GB_BIT   1
240    0,                                              // GB_BYTE  2
241    0,                                              // GB_INT   3
242    0,                                              // GB_FLOAT 4
243    0,                                              // GB_??    5
244    0,                                              // GB_BITS  6
245    0,                                              // GB_??    7
246    0,                                              // GB_BYTES 8
247    0,                                              // GB_INTS  9
248    0,                                              // GB_FLTS 10
249    1,                                              // GB_LINK 11 (zero terminated)
250    1,                                              // GB_STR  12 (zero terminated)
251    1,                                              // GB_STRS 13 (zero terminated)
252    0,                                              // GB_??   14
253    0,                                              // GB_DB   15
254};
255
256
257// ---------------------------------
258//      local buffer management
259
260static void init_buffer(gb_buffer *buf, size_t initial_size) {
261    buf->size = initial_size;
262    buf->mem  = buf->size ? ARB_alloc<char>(buf->size) : NULp;
263}
264
265static char *check_out_buffer(gb_buffer *buf) {
266    char *checkOut = buf->mem;
267
268    buf->mem  = NULp;
269    buf->size = 0;
270
271    return checkOut;
272}
273
274static void alloc_buffer(gb_buffer *buf, size_t size) {
275    free(buf->mem);
276    buf->size = size;
277#if (MEMORY_TEST==1)
278    ARB_alloc(buf->mem, buf->size);
279#else
280    ARB_calloc(buf->mem, buf->size);
281#endif
282}
283
284static GB_BUFFER give_buffer(gb_buffer *buf, size_t size) {
285#if (MEMORY_TEST==1)
286    alloc_buffer(buf, size); // do NOT reuse buffer if testing memory
287#else
288    if (size >= buf->size) {
289        alloc_buffer(buf, size);
290    }
291#endif
292    return buf->mem;
293}
294
295static int is_in_buffer(gb_buffer *buf, GB_CBUFFER ptr) {
296    return ptr >= buf->mem && ptr < buf->mem+buf->size;
297}
298
299// ------------------------------
300
301GB_BUFFER GB_give_buffer(size_t size) {
302    // return a pointer to a static piece of memory at least size bytes long
303    return give_buffer(&gb_local->buf1, size);
304}
305
306GB_BUFFER GB_increase_buffer(size_t size) {
307    if (size < gb_local->buf1.size) {
308        char   *old_buffer = gb_local->buf1.mem;
309        size_t  old_size   = gb_local->buf1.size;
310
311        gb_local->buf1.mem = NULp;
312        alloc_buffer(&gb_local->buf1, size);
313        memcpy(gb_local->buf1.mem, old_buffer, old_size);
314
315        free(old_buffer);
316    }
317    return gb_local->buf1.mem;
318}
319
320NOT4PERL int GB_give_buffer_size() {
321    return gb_local->buf1.size;
322}
323
324GB_BUFFER GB_give_buffer2(long size) {
325    return give_buffer(&gb_local->buf2, size);
326}
327
328static int GB_is_in_buffer(GB_CBUFFER ptr) {
329    /* returns 1 or 2 if 'ptr' points to gb_local->buf1/buf2
330     * returns 0 otherwise
331     */
332    int buffer = 0;
333
334    if (is_in_buffer(&gb_local->buf1, ptr)) buffer = 1;
335    else if (is_in_buffer(&gb_local->buf2, ptr)) buffer = 2;
336
337    return buffer;
338}
339
340char *GB_check_out_buffer(GB_CBUFFER buffer) {
341    /* Check a piece of memory out of the buffer management
342     * after it is checked out, the user has the full control to use and free it
343     * Returns a pointer to the start of the buffer (even if 'buffer' points inside the buffer!)
344     */
345    char *old = NULp;
346
347    if (is_in_buffer(&gb_local->buf1, buffer)) old = check_out_buffer(&gb_local->buf1);
348    else if (is_in_buffer(&gb_local->buf2, buffer)) old = check_out_buffer(&gb_local->buf2);
349
350    return old;
351}
352
353GB_BUFFER GB_give_other_buffer(GB_CBUFFER buffer, long size) {
354    return is_in_buffer(&gb_local->buf1, buffer)
355        ? GB_give_buffer2(size)
356        : GB_give_buffer(size);
357}
358
359static unsigned char GB_BIT_compress_data[] = {
360    0x1d, GB_CS_OK,  0, 0,
361    0x04, GB_CS_OK,  0, 1,
362    0x0a, GB_CS_OK,  0, 2,
363    0x0b, GB_CS_OK,  0, 3,
364    0x0c, GB_CS_OK,  0, 4,
365    0x1a, GB_CS_OK,  0, 5,
366    0x1b, GB_CS_OK,  0, 6,
367    0x1c, GB_CS_OK,  0, 7,
368    0xf0, GB_CS_OK,  0, 8,
369    0xf1, GB_CS_OK,  0, 9,
370    0xf2, GB_CS_OK,  0, 10,
371    0xf3, GB_CS_OK,  0, 11,
372    0xf4, GB_CS_OK,  0, 12,
373    0xf5, GB_CS_OK,  0, 13,
374    0xf6, GB_CS_OK,  0, 14,
375    0xf7, GB_CS_OK,  0, 15,
376    0xf8, GB_CS_SUB, 0, 16,
377    0xf9, GB_CS_SUB, 0, 32,
378    0xfa, GB_CS_SUB, 0, 48,
379    0xfb, GB_CS_SUB, 0, 64,
380    0xfc, GB_CS_SUB, 0, 128,
381    0xfd, GB_CS_SUB, 1, 0,
382    0xfe, GB_CS_SUB, 2, 0,
383    0xff, GB_CS_SUB, 4, 0,
384    0
385};
386
387struct gb_exitfun {
388    void (*exitfun)();
389    gb_exitfun *next;
390};
391
392void GB_atexit(void (*exitfun)()) {
393    // called when GB_shell is destroyed (use similar to atexit())
394    //
395    // Since the program does not neccessarily terminate, your code calling
396    // GB_atexit() may run multiple times. Make sure everything is completely reset by your 'exitfun'
397
398    gb_exitfun *fun = new gb_exitfun;
399    fun->exitfun    = exitfun;
400
401    fun->next          = gb_local->atgbexit;
402    gb_local->atgbexit = fun;
403}
404
405static void run_and_destroy_exit_functions(gb_exitfun *fun) {
406    if (fun) {
407        fun->exitfun();
408        run_and_destroy_exit_functions(fun->next);
409        delete fun;
410    }
411}
412
413static void GB_exit_gb() {
414    GB_shell::ensure_inside();
415
416    if (gb_local) {
417        gb_local->~gb_local_data(); // inplace-dtor
418        gbm_free_mem(gb_local, sizeof(*gb_local), 0);
419        gb_local = NULp;
420        gbm_flush_mem();
421    }
422}
423
424gb_local_data::~gb_local_data() {
425    gb_assert(openedDBs == closedDBs);
426
427    run_and_destroy_exit_functions(atgbexit);
428
429    free(bitcompress);
430    gb_free_compress_tree(bituncompress);
431    free(write_buffer);
432
433    free(check_out_buffer(&buf2));
434    free(check_out_buffer(&buf1));
435    free(open_gb_mains);
436}
437
438// -----------------
439//      GB_shell
440
441
442static GB_shell *inside_shell = NULp;
443
444GB_shell::GB_shell() {
445    if (inside_shell) GBK_terminate("only one GB_shell allowed");
446    inside_shell = this;
447}
448GB_shell::~GB_shell() {
449    gb_assert(inside_shell == this);
450    GB_exit_gb();
451    inside_shell = NULp;
452}
453void GB_shell::ensure_inside()  { if (!inside_shell) GBK_terminate("Not inside GB_shell"); }
454
455bool GB_shell::in_shell() { // used by code based on ARBDB (Kai IIRC)
456    return inside_shell;
457}
458
459struct GB_test_shell_closed {
460    ~GB_test_shell_closed() {
461        if (GB_shell::in_shell()) { // leave that call
462            inside_shell->~GB_shell(); // call dtor
463        }
464    }
465};
466static GB_test_shell_closed test;
467
468#if defined(UNIT_TESTS)
469static bool closed_open_shell_for_unit_tests() {
470    bool was_open = inside_shell;
471    if (was_open) {
472        if (gb_local) gb_local->fake_closed_DBs();
473        inside_shell->~GB_shell(); // just call dtor (not delete)
474    }
475    return was_open;
476}
477#endif
478
479void GB_init_gb() {
480    GB_shell::ensure_inside();
481    if (!gb_local) {
482        GBK_install_SIGSEGV_handler(true);          // never uninstalled
483        gbm_init_mem();
484        gb_local = (gb_local_data *)gbm_get_mem(sizeof(gb_local_data), 0);
485        ::new(gb_local) gb_local_data(); // inplace-ctor
486    }
487}
488
489int GB_open_DBs() { return gb_local ? gb_local->open_dbs() : 0; }
490
491gb_local_data::gb_local_data() {
492    init_buffer(&buf1, 4000);
493    init_buffer(&buf2, 4000);
494
495    write_bufsize = GBCM_BUFFER;
496    ARB_alloc(write_buffer, write_bufsize);
497
498    write_ptr  = write_buffer;
499    write_free = write_bufsize;
500
501    bituncompress = gb_build_uncompress_tree(GB_BIT_compress_data, 1, NULp);
502    bitcompress   = gb_build_compress_list(GB_BIT_compress_data, 1, &(bc_size));
503
504    openedDBs = 0;
505    closedDBs = 0;
506
507    open_gb_mains = NULp;
508    open_gb_alloc = 0;
509
510    atgbexit = NULp;
511
512    iamclient                  = false;
513    search_system_folder       = false;
514    running_client_transaction = ARB_NO_TRANS;
515}
516
517void gb_local_data::announce_db_open(GB_MAIN_TYPE *Main) {
518    gb_assert(Main);
519    int idx = open_dbs();
520    if (idx >= open_gb_alloc) {
521        int new_alloc = open_gb_alloc + 10;
522        ARB_recalloc(open_gb_mains, open_gb_alloc, new_alloc);
523        open_gb_alloc = new_alloc;
524    }
525    open_gb_mains[idx] = Main;
526    openedDBs++;
527}
528
529void gb_local_data::announce_db_close(GB_MAIN_TYPE *Main) {
530    gb_assert(Main);
531    int open = open_dbs();
532    int idx;
533    for (idx = 0; idx<open; ++idx) if (open_gb_mains[idx] == Main) break;
534
535    gb_assert(idx<open); // passed gb_main is unknown
536    if (idx<open) {
537        if (idx<(open-1)) { // not last
538            open_gb_mains[idx] = open_gb_mains[open-1];
539        }
540        closedDBs++;
541    }
542    if (closedDBs == openedDBs) {
543        GB_exit_gb(); // free most memory allocated by ARBDB library
544        // Caution: calling GB_exit_gb() frees 'this'!
545    }
546}
547
548static GBDATA *gb_remembered_db() {
549    GB_MAIN_TYPE *Main = gb_local ? gb_local->get_any_open_db() : NULp;
550    return Main ? Main->gb_main() : NULp;
551}
552
553GB_ERROR gb_unfold(GBCONTAINER *gbc, long deep, int index_pos) {
554    /*! get data from server.
555     *
556     * @param gbc container to unfold
557     * @param deep if != 0, then get subitems too.
558     * @param index_pos
559     * - >= 0, get indexed item from server
560     * - <0, get all items
561     *
562     * @return error on failure
563     */
564
565    GB_ERROR        error;
566    gb_header_list *header = GB_DATA_LIST_HEADER(gbc->d);
567
568    if (!gbc->flags2.folded_container) return NULp;
569    if (index_pos> gbc->d.nheader) gb_create_header_array(gbc, index_pos + 1);
570    if (index_pos >= 0  && GB_HEADER_LIST_GBD(header[index_pos])) return NULp;
571
572    if (GBCONTAINER_MAIN(gbc)->is_server()) {
573        GB_internal_error("Cannot unfold in server");
574        return NULp;
575    }
576
577    do {
578        if (index_pos<0) break;
579        if (index_pos >= gbc->d.nheader) break;
580        if (header[index_pos].flags.changed >= GB_DELETED) {
581            GB_internal_error("Tried to unfold a deleted item");
582            return NULp;
583        }
584        if (GB_HEADER_LIST_GBD(header[index_pos])) return NULp; // already unfolded
585    } while (0);
586
587    error = gbcm_unfold_client(gbc, deep, index_pos);
588    if (error) {
589        GB_print_error();
590        return error;
591    }
592
593    if (index_pos<0) {
594        gb_untouch_children(gbc);
595        gbc->flags2.folded_container = 0;
596    }
597    else {
598        GBDATA *gb2 = GBCONTAINER_ELEM(gbc, index_pos);
599        if (gb2) {
600            if (gb2->is_container()) {
601                gb_untouch_children_and_me(gb2->as_container());
602            }
603            else {
604                gb_untouch_me(gb2->as_entry());
605            }
606        }
607    }
608    return NULp;
609}
610
611// -----------------------
612//      close database
613
614static void run_close_callbacks(GBDATA *gb_main) {
615    GB_MAIN_TYPE *Main = GB_MAIN(gb_main);
616    gb_assert(Main->gb_main() == gb_main);
617    if (Main->close_callbacks) {
618        Main->close_callbacks->call(gb_main, GB_CB_DELETE);
619    }
620}
621
622void GB_close(GBDATA *gbd) {
623    GB_ERROR      error = NULp;
624    GB_MAIN_TYPE *Main  = GB_MAIN(gbd);
625
626    gb_assert(Main->get_transaction_level() <= 0); // transaction running - you can't close DB yet!
627
628    Main->forget_hierarchy_cbs();
629
630    gb_assert(Main->gb_main() == gbd);
631    run_close_callbacks(gbd);
632    Main->close_callbacks = NULp;
633
634    bool quick_exit = Main->mapped;
635    if (Main->is_client()) {
636        GBCM_ServerResult result = gbcmc_close(Main->c_link);
637        if (result != GBCM_SERVER_OK) error = GBS_global_string("close failed (with %i:%s)", result, GB_await_error());
638
639        gb_assert(!quick_exit); // client cannot be mapped
640    }
641
642    gbcm_logout(Main, NULp); // logout default user
643
644    if (!error) {
645        gb_assert(!Main->close_callbacks);
646
647#if defined(LEAKS_SANITIZED)
648        quick_exit = false;
649#endif
650
651        if (quick_exit) {
652            // fake some data to allow quick-exit
653            Main->dummy_father = NULp;
654            Main->cache.entries = NULp;
655        }
656        else {
657            // proper cleanup of DB (causes unwanted behavior described in #649)
658            gb_delete_dummy_father(Main->dummy_father);
659        }
660        Main->root_container = NULp;
661
662        /* ARBDB applications using awars easily crash in call_pending_callbacks(),
663         * if AWARs are still bound to elements in the closed database.
664         *
665         * To unlink awars call AW_root::unlink_awars_from_DB().
666         * If that doesn't help, test Main->data (often aka as GLOBAL_gb_main)
667         */
668        Main->call_pending_callbacks(); // do all callbacks
669        delete Main;
670    }
671
672    if (error) {
673        GB_warningf("Error in GB_close: %s", error);
674    }
675}
676
677void gb_abort_and_close_all_DBs() {
678    GBDATA *gb_main;
679    while ((gb_main = gb_remembered_db())) {
680        // abort any open transactions
681        GB_MAIN_TYPE *Main = GB_MAIN(gb_main);
682        while (Main->get_transaction_level()>0) {
683            GB_ERROR error = Main->abort_transaction();
684            if (error) {
685                fprintf(stderr, "Error in gb_abort_and_close_all_DBs: %s\n", error);
686            }
687        }
688        // and close DB
689        GB_close(gb_main);
690    }
691}
692
693// ------------------
694//      read data
695
696long GB_read_int(GBDATA *gbd) {
697    GB_TEST_READ_NUM(gbd, GB_INT, "GB_read_int");
698    return gbd->as_entry()->info.i;
699}
700
701int GB_read_byte(GBDATA *gbd) {
702    GB_TEST_READ_NUM(gbd, GB_BYTE, "GB_read_byte");
703    return gbd->as_entry()->info.i;
704}
705
706GBDATA *GB_read_pointer(GBDATA *gbd) {
707    GB_TEST_READ_PTR(gbd, GB_POINTER, "GB_read_pointer");
708    return gbd->as_entry()->info.ptr;
709}
710
711float GB_read_float(GBDATA *gbd) {
712    XDR   xdrs;
713    float f;
714
715    GB_TEST_READ_NUM(gbd, GB_FLOAT, "GB_read_float");
716    xdrmem_create(&xdrs, &gbd->as_entry()->info.in.data[0], SIZOFINTERN, XDR_DECODE);
717    xdr_float(&xdrs, &f);
718    xdr_destroy(&xdrs);
719
720    gb_assert(f == f); // !nan
721
722    return f;
723}
724
725long GB_read_count(GBDATA *gbd) {
726    return gbd->as_entry()->size();
727}
728
729long GB_read_memuse(GBDATA *gbd) {
730    return gbd->as_entry()->memsize();
731}
732
733#if defined(DEBUG)
734
735#define MIN_CBLISTNODE_SIZE 48 // minimum (found) callbacklist-elementsize
736
737#if defined(DARWIN)
738
739#define CBLISTNODE_SIZE MIN_CBLISTNODE_SIZE // assume known minimum (doesnt really matter; only used in db-browser)
740
741#else // linux:
742
743typedef std::_List_node<gb_callback_list::cbtype> CBLISTNODE_TYPE;
744const size_t CBLISTNODE_SIZE = sizeof(CBLISTNODE_TYPE);
745
746#if defined(ARB_64)
747// ignore smaller 32-bit implementations
748STATIC_ASSERT_ANNOTATED(MIN_CBLISTNODE_SIZE<=CBLISTNODE_SIZE, "MIN_CBLISTNODE_SIZE too big (smaller implementation detected)");
749#endif
750
751#endif
752
753inline long calc_size(gb_callback_list *gbcbl) {
754    return gbcbl
755        ? sizeof(*gbcbl) + gbcbl->callbacks.size()* CBLISTNODE_SIZE
756        : 0;
757}
758inline long calc_size(gb_transaction_save *gbts) {
759    return gbts
760        ? sizeof(*gbts)
761        : 0;
762}
763inline long calc_size(gb_if_entries *gbie) {
764    return gbie
765        ? sizeof(*gbie) + calc_size(GB_IF_ENTRIES_NEXT(gbie))
766        : 0;
767}
768inline long calc_size(GB_REL_IFES *gbri, int table_size) {
769    long size = 0;
770
771    gb_if_entries *ifes;
772    for (int idx = 0; idx<table_size; ++idx) {
773        for (ifes = GB_ENTRIES_ENTRY(gbri, idx);
774             ifes;
775             ifes = GB_IF_ENTRIES_NEXT(ifes))
776        {
777            size += calc_size(ifes);
778        }
779    }
780    return size;
781}
782inline long calc_size(gb_index_files *gbif) {
783    return gbif
784        ? sizeof(*gbif) + calc_size(GB_INDEX_FILES_NEXT(gbif)) + calc_size(GB_INDEX_FILES_ENTRIES(gbif), gbif->hash_table_size)
785        : 0;
786}
787inline long calc_size(gb_db_extended *gbe) {
788    return gbe
789        ? sizeof(*gbe) + calc_size(gbe->callback) + calc_size(gbe->old)
790        : 0;
791}
792inline long calc_size(GBENTRY *gbe) {
793    return gbe
794        ? sizeof(*gbe) + calc_size(gbe->ext)
795        : 0;
796}
797inline long calc_size(GBCONTAINER *gbc) {
798    return gbc
799        ? sizeof(*gbc) + calc_size(gbc->ext) + calc_size(GBCONTAINER_IFS(gbc))
800        : 0;
801}
802
803long GB_calc_structure_size(GBDATA *gbd) {
804    long size = 0;
805    if (gbd->is_container()) {
806        size = calc_size(gbd->as_container());
807    }
808    else {
809        size = calc_size(gbd->as_entry());
810    }
811    return size;
812}
813
814void GB_SizeInfo::collect(GBDATA *gbd) {
815    if (gbd->is_container()) {
816        ++containers;
817        for (GBDATA *gb_child = GB_child(gbd); gb_child; gb_child = GB_nextChild(gb_child)) {
818            collect(gb_child);
819        }
820    }
821    else {
822        ++terminals;
823        mem += GB_read_memuse(gbd);
824
825        long size;
826        switch (gbd->type()) {
827            case GB_INT:     size = sizeof(int); break;
828            case GB_FLOAT:   size = sizeof(float); break;
829            case GB_BYTE:    size = sizeof(char); break;
830            case GB_POINTER: size = sizeof(GBDATA*); break;
831            case GB_STRING:  size = GB_read_count(gbd); break; // accept 0 sized data for strings
832
833            default:
834                size = GB_read_count(gbd);
835                gb_assert(size>0);                            // terminal w/o data - really?
836                break;
837        }
838        data += size;
839    }
840    structure += GB_calc_structure_size(gbd);
841}
842#endif
843
844GB_CSTR GB_read_pntr(GBDATA *gbd) {
845    GBENTRY    *gbe  = gbd->as_entry();
846    const char *data = gbe->data();
847
848    if (data) {
849        if (gbe->flags.compressed_data) {   // uncompressed data return pntr to database entry
850            char *ca = gb_read_cache(gbe);
851
852            if (!ca) {
853                size_t      size = gbe->uncompressed_size();
854                const char *da   = gb_uncompress_data(gbe, data, size);
855
856                if (da) {
857                    ca = gb_alloc_cache_index(gbe, size);
858                    memcpy(ca, da, size);
859                }
860            }
861            data = ca;
862        }
863    }
864    return data;
865}
866
867int gb_read_nr(GBDATA *gbd) {
868    return gbd->index;
869}
870
871GB_CSTR GB_read_char_pntr(GBDATA *gbd) {
872    GB_TEST_READ_PTR(gbd, GB_STRING, "GB_read_char_pntr");
873    return GB_read_pntr(gbd);
874}
875
876char *GB_read_string(GBDATA *gbd) {
877    GB_TEST_READ_PTR(gbd, GB_STRING, "GB_read_string");
878    const char *d = GB_read_pntr(gbd);
879    if (!d) return NULp;
880    return GB_memdup(d, gbd->as_entry()->size()+1);
881}
882
883size_t GB_read_string_count(GBDATA *gbd) {
884    GB_TEST_READ_NUM(gbd, GB_STRING, "GB_read_string_count");
885    return gbd->as_entry()->size();
886}
887
888long GB_read_bits_count(GBDATA *gbd) {
889    GB_TEST_READ_NUM(gbd, GB_BITS, "GB_read_bits_count");
890    return gbd->as_entry()->size();
891}
892
893GB_CSTR GB_read_bits_pntr(GBDATA *gbd, char c_0, char c_1) {
894    GB_TEST_READ_PTR(gbd, GB_BITS, "GB_read_bits_pntr");
895    GBENTRY *gbe  = gbd->as_entry();
896    long     size = gbe->size();
897    if (size) {
898        // Note: the first 2 bytes of the cached entry contain the currently used encoding (c_0 and c_1)
899
900        char *ca = gb_read_cache(gbe);
901        if (ca) {
902            // check if encoding was the same during last read
903            if (ca[0] == c_0 && ca[1] == c_1) { // yes -> reuse
904                return ca+2;
905            }
906            // no -> re-read from DB
907            GB_flush_cache(gbe);
908            ca = NULp;
909        }
910
911        const char *data = gbe->data();
912        char       *da   = gb_uncompress_bits(data, size, c_0, c_1);
913
914        if (da) {
915            ca    = gb_alloc_cache_index(gbe, size+3); // 2 byte encoding + stored data + terminal '\0'
916            ca[0] = c_0;
917            ca[1] = c_1;
918            memcpy(ca+2, da, size+1);
919            return ca+2;
920        }
921    }
922    return NULp;
923}
924
925char *GB_read_bits(GBDATA *gbd, char c_0, char c_1) {
926    GB_CSTR d = GB_read_bits_pntr(gbd, c_0, c_1);
927    return d ? GB_memdup(d, gbd->as_entry()->size()+1) : NULp;
928}
929
930
931GB_CSTR GB_read_bytes_pntr(GBDATA *gbd) {
932    GB_TEST_READ_PTR(gbd, GB_BYTES, "GB_read_bytes_pntr");
933    return GB_read_pntr(gbd);
934}
935
936long GB_read_bytes_count(GBDATA *gbd) {
937    GB_TEST_READ_NUM(gbd, GB_BYTES, "GB_read_bytes_count");
938    return gbd->as_entry()->size();
939}
940
941char *GB_read_bytes(GBDATA *gbd) {
942    GB_CSTR d = GB_read_bytes_pntr(gbd);
943    return d ? GB_memdup(d, gbd->as_entry()->size()) : NULp;
944}
945
946GB_CUINT4 *GB_read_ints_pntr(GBDATA *gbd) {
947    GB_TEST_READ_PTR(gbd, GB_INTS, "GB_read_ints_pntr");
948    GBENTRY *gbe = gbd->as_entry();
949
950    GB_UINT4 *res;
951    if (gbe->flags.compressed_data) {
952        res = (GB_UINT4 *)GB_read_pntr(gbe);
953    }
954    else {
955        res = (GB_UINT4 *)gbe->data();
956    }
957    if (!res) return NULp;
958
959    if (0x01020304U == htonl(0x01020304U)) {
960        return res;
961    }
962    else {
963        int       size = gbe->size();
964        char     *buf2 = GB_give_other_buffer((char *)res, size<<2);
965        GB_UINT4 *s    = (GB_UINT4 *)res;
966        GB_UINT4 *d    = (GB_UINT4 *)buf2;
967
968        for (long i=size; i; i--) {
969            *(d++) = htonl(*(s++));
970        }
971        return (GB_UINT4 *)buf2;
972    }
973}
974
975long GB_read_ints_count(GBDATA *gbd) { // used by ../PERL_SCRIPTS/SAI/SAI.pm@read_ints_count
976    GB_TEST_READ_NUM(gbd, GB_INTS, "GB_read_ints_count");
977    return gbd->as_entry()->size();
978}
979
980GB_UINT4 *GB_read_ints(GBDATA *gbd) {
981    GB_CUINT4 *i = GB_read_ints_pntr(gbd);
982    if (!i) return NULp;
983    return  (GB_UINT4 *)GB_memdup((char *)i, gbd->as_entry()->size()*sizeof(GB_UINT4));
984}
985
986GB_CFLOAT *GB_read_floats_pntr(GBDATA *gbd) {
987    GB_TEST_READ_PTR(gbd, GB_FLOATS, "GB_read_floats_pntr");
988    GBENTRY *gbe = gbd->as_entry();
989    char    *res;
990    if (gbe->flags.compressed_data) {
991        res = (char *)GB_read_pntr(gbe);
992    }
993    else {
994        res = (char *)gbe->data();
995    }
996    if (res) {
997        long size      = gbe->size();
998        long full_size = size*sizeof(float);
999
1000        XDR xdrs;
1001        xdrmem_create(&xdrs, res, (int)(full_size), XDR_DECODE);
1002
1003        char  *buf2 = GB_give_other_buffer(res, full_size);
1004        float *d    = (float *)(void*)buf2;
1005        for (long i=size; i; i--) {
1006            xdr_float(&xdrs, d);
1007            d++;
1008        }
1009        xdr_destroy(&xdrs);
1010        return (float *)(void*)buf2;
1011    }
1012    return NULp;
1013}
1014
1015static long GB_read_floats_count(GBDATA *gbd) {
1016    GB_TEST_READ_NUM(gbd, GB_FLOATS, "GB_read_floats_count");
1017    return gbd->as_entry()->size();
1018}
1019
1020float *GB_read_floats(GBDATA *gbd) { // @@@ only used in unittest - check usage of floats
1021    GB_CFLOAT *f;
1022    f = GB_read_floats_pntr(gbd);
1023    if (!f) return NULp;
1024    return  (float *)GB_memdup((char *)f, gbd->as_entry()->size()*sizeof(float));
1025}
1026
1027char *GB_read_as_string(GBDATA *gbd) {
1028    /*! reads basic db-field types and returns content as text.
1029     * @see GB_write_autoconv_string
1030     * @see GB_readable_as_string
1031     */
1032    switch (gbd->type()) {
1033        case GB_STRING: return GB_read_string(gbd);
1034        case GB_BYTE:   return GBS_global_string_copy("%i", GB_read_byte(gbd));
1035        case GB_INT:    return GBS_global_string_copy("%li", GB_read_int(gbd));
1036        case GB_FLOAT:  return ARB_strdup(ARB_float_2_ascii(GB_read_float(gbd)));
1037        case GB_BITS:   return GB_read_bits(gbd, '0', '1');
1038            /* Be careful : When adding new types here, you have to make sure that
1039             * GB_write_autoconv_string is able to write them back and that this makes sense.
1040             */
1041        default:    return NULp;
1042    }
1043}
1044
1045bool GB_readable_as_string(GBDATA *gbd) {
1046    //! @see GB_TYPE_readable_as_string()
1047    return GB_TYPE_readable_as_string(GB_read_type(gbd));
1048}
1049
1050
1051inline GB_ERROR cannot_use_fun4entry(const char *fun, GBDATA *gb_entry) {
1052    return GBS_global_string("Error: Cannot use %s() with a field of type %i (field=%s)",
1053                             fun,
1054                             GB_read_type(gb_entry),
1055                             GB_read_key_pntr(gb_entry));
1056}
1057
1058NOT4PERL uint8_t GB_read_lossless_byte(GBDATA *gbd, GB_ERROR& error) {
1059    /*! Reads an uint8_t previously written with GB_write_lossless_byte()
1060     * @param gbd    the DB field
1061     * @param error  result parameter (has to be NULp)
1062     * @result is undefined if error got set; contains read value otherwise
1063     */
1064    gb_assert(!error);
1065    gb_assert(!GB_have_error());
1066    uint8_t result;
1067    switch (gbd->type()) {
1068        case GB_BYTE:
1069            result = GB_read_byte(gbd);
1070            break;
1071
1072        case GB_INT:
1073            result = GB_read_int(gbd);
1074            break;
1075
1076        case GB_FLOAT:
1077            result = GB_read_float(gbd)+.5;
1078            break;
1079
1080        case GB_STRING:
1081            result = atoi(GB_read_char_pntr(gbd));
1082            break;
1083
1084        default:
1085            error  = cannot_use_fun4entry("GB_read_lossless_byte", gbd);
1086            result = 0;
1087            break;
1088    }
1089
1090    if (!error) error = GB_incur_error();
1091    return result;
1092}
1093NOT4PERL int32_t GB_read_lossless_int(GBDATA *gbd, GB_ERROR& error) {
1094    /*! Reads an int32_t previously written with GB_write_lossless_int()
1095     * @param gbd    the DB field
1096     * @param error  result parameter (has to be NULp)
1097     * @result is undefined if error got set; contains read value otherwise
1098     */
1099    gb_assert(!error);
1100    gb_assert(!GB_have_error());
1101    int32_t result;
1102    switch (gbd->type()) {
1103        case GB_INT:
1104            result = GB_read_int(gbd);
1105            break;
1106
1107        case GB_STRING:
1108            result = atoi(GB_read_char_pntr(gbd));
1109            break;
1110
1111        default:
1112            error  = cannot_use_fun4entry("GB_read_lossless_int", gbd);
1113            result = 0;
1114            break;
1115    }
1116
1117    if (!error) error = GB_incur_error();
1118    return result;
1119}
1120NOT4PERL float GB_read_lossless_float(GBDATA *gbd, GB_ERROR& error) {
1121    /*! Reads a float previously written with GB_write_lossless_float()
1122     * @param gbd    the DB field
1123     * @param error  result parameter (has to be NULp)
1124     * @result is undefined if error got set; contains read value otherwise
1125     */
1126    gb_assert(!error);
1127    gb_assert(!GB_have_error());
1128    float result;
1129    switch (gbd->type()) {
1130        case GB_FLOAT:
1131            result = GB_read_float(gbd);
1132            break;
1133
1134        case GB_STRING:
1135            result = GB_atof(GB_read_char_pntr(gbd));
1136            break;
1137
1138        default:
1139            error  = cannot_use_fun4entry("GB_read_lossless_float", gbd);
1140            result = 0;
1141            break;
1142    }
1143
1144    if (!error) error = GB_incur_error();
1145    return result;
1146}
1147
1148// ------------------------------------------------------------
1149//      array type access functions (intended for perl use)
1150
1151long GB_read_from_ints(GBDATA *gbd, long index) { // used by ../PERL_SCRIPTS/SAI/SAI.pm@read_from_ints
1152    static GBDATA    *last_gbd = NULp;
1153    static long       count    = 0;
1154    static GB_CUINT4 *i        = NULp;
1155
1156    if (gbd != last_gbd) {
1157        count    = GB_read_ints_count(gbd);
1158        i        = GB_read_ints_pntr(gbd);
1159        last_gbd = gbd;
1160    }
1161
1162    if (index >= 0 && index < count) {
1163        return i[index];
1164    }
1165    return -1;
1166}
1167
1168double GB_read_from_floats(GBDATA *gbd, long index) { // @@@ unused
1169    static GBDATA    *last_gbd = NULp;
1170    static long       count    = 0;
1171    static GB_CFLOAT *f        = NULp;
1172
1173    if (gbd != last_gbd) {
1174        count    = GB_read_floats_count(gbd);
1175        f        = GB_read_floats_pntr(gbd);
1176        last_gbd = gbd;
1177    }
1178
1179    if (index >= 0 && index < count) {
1180        return f[index];
1181    }
1182    return -1;
1183}
1184
1185// -------------------
1186//      write data
1187
1188static void gb_do_callbacks(GBDATA *gbd) {
1189    gb_assert(GB_MAIN(gbd)->get_transaction_level() < 0); // only use in NO_TRANSACTION_MODE!
1190
1191    while (gbd) {
1192        GBDATA *gbdn = GB_get_father(gbd);
1193        gb_callback_list *cbl = gbd->get_callbacks();
1194        if (cbl && cbl->call(gbd, GB_CB_CHANGED)) {
1195            gb_remove_callbacks_marked_for_deletion(gbd);
1196        }
1197        gbd = gbdn;
1198    }
1199}
1200
1201#define GB_DO_CALLBACKS(gbd) do { if (GB_MAIN(gbd)->get_transaction_level() < 0) gb_do_callbacks(gbd); } while (0)
1202
1203GB_ERROR GB_write_byte(GBDATA *gbd, int i) {
1204    GB_TEST_WRITE(gbd, GB_BYTE, "GB_write_byte");
1205    GBENTRY *gbe = gbd->as_entry();
1206    if (gbe->info.i != i) {
1207        gb_save_extern_data_in_ts(gbe);
1208        gbe->info.i = i & 0xff;
1209        gb_touch_entry(gbe, GB_NORMAL_CHANGE);
1210        GB_DO_CALLBACKS(gbe);
1211    }
1212    return NULp;
1213}
1214
1215GB_ERROR GB_write_int(GBDATA *gbd, long i) {
1216#if defined(ARB_64)
1217#if defined(WARN_TODO)
1218#warning GB_write_int should be GB_ERROR GB_write_int(GBDATA *gbd,int32_t i)
1219#endif
1220#endif
1221
1222    GB_TEST_WRITE(gbd, GB_INT, "GB_write_int");
1223    if ((long)((int32_t)i) != i) {
1224        gb_assert(0);
1225        GB_warningf("Warning: 64bit incompatibility detected\nNo data written to '%s'\n", GB_get_db_path(gbd));
1226        return "GB_INT out of range (signed, 32bit)";
1227    }
1228    GBENTRY *gbe = gbd->as_entry();
1229    if (gbe->info.i != (int32_t)i) {
1230        gb_save_extern_data_in_ts(gbe);
1231        gbe->info.i = i;
1232        gb_touch_entry(gbe, GB_NORMAL_CHANGE);
1233        GB_DO_CALLBACKS(gbe);
1234    }
1235    return NULp;
1236}
1237
1238GB_ERROR GB_write_pointer(GBDATA *gbd, GBDATA *pointer) {
1239    GB_TEST_WRITE(gbd, GB_POINTER, "GB_write_pointer");
1240    GBENTRY *gbe = gbd->as_entry();
1241    if (gbe->info.ptr != pointer) {
1242        gb_save_extern_data_in_ts(gbe);
1243        gbe->info.ptr = pointer;
1244        gb_touch_entry(gbe, GB_NORMAL_CHANGE);
1245        GB_DO_CALLBACKS(gbe);
1246    }
1247    return NULp;
1248}
1249
1250GB_ERROR GB_write_float(GBDATA *gbd, float f) {
1251    gb_assert(f == f); // !nan
1252    GB_TEST_WRITE(gbd, GB_FLOAT, "GB_write_float");
1253
1254    if (GB_read_float(gbd) != f) {
1255        GBENTRY *gbe = gbd->as_entry();
1256        gb_save_extern_data_in_ts(gbe);
1257
1258        XDR xdrs;
1259        xdrmem_create(&xdrs, &gbe->info.in.data[0], SIZOFINTERN, XDR_ENCODE);
1260        xdr_float(&xdrs, &f);
1261        xdr_destroy(&xdrs);
1262
1263        gb_touch_entry(gbe, GB_NORMAL_CHANGE);
1264        GB_DO_CALLBACKS(gbe);
1265    }
1266    return NULp;
1267}
1268
1269inline void gb_save_extern_data_in_ts__and_uncache(GBENTRY *gbe) {
1270    // order of the following commands is important:
1271    // gb_save_extern_data_in_ts may recreate a cache-entry under the following conditions:
1272    //  - gbe is indexed AND
1273    //  - gbe is stored compressed (and compression really takes place)
1274    //
1275    // Calling these commands in reversed order (as done until [15622])
1276    // had the following effects:
1277    // - writing modified data to an entry had no effect (cache still contained old value)
1278    // - after saving and reloading the database, the modified value was effective
1279    //
1280    // Happened e.g. when copying an SAI (if dictionary compression occurred for SAI/name). See #742.
1281
1282    gb_save_extern_data_in_ts(gbe); // Warning: might undo effect of gb_uncache if called afterwards
1283    gb_uncache(gbe);
1284}
1285
1286GB_ERROR gb_write_compressed_pntr(GBENTRY *gbe, const char *s, long memsize, long stored_size) {
1287    gb_save_extern_data_in_ts__and_uncache(gbe);
1288
1289    gbe->flags.compressed_data = 1;
1290
1291    gb_assert(!gbe->cache_index); // insert_data() will recreate the cache-entry (if entry is_indexed)
1292    gbe->insert_data((char *)s, stored_size, (size_t)memsize);
1293    gb_touch_entry(gbe, GB_NORMAL_CHANGE);
1294
1295    return NULp;
1296}
1297
1298int gb_get_compression_mask(GB_MAIN_TYPE *Main, GBQUARK key, int gb_type) {
1299    gb_Key *ks = &Main->keys[key];
1300    int     compression_mask;
1301
1302    if (ks->gb_key_disabled) {
1303        compression_mask = 0;
1304    }
1305    else {
1306        if (!ks->gb_key) gb_load_single_key_data(Main->gb_main(), key);
1307        compression_mask = gb_convert_type_2_compression_flags[gb_type] & ks->compression_mask;
1308    }
1309
1310    return compression_mask;
1311}
1312
1313GB_ERROR GB_write_pntr(GBDATA *gbd, const char *s, size_t bytes_size, size_t stored_size) {
1314    // 'bytes_size' is the size of what 's' points to.
1315    // 'stored_size' is the size-information written into the DB
1316    //
1317    // e.g. for strings : stored_size = bytes_size-1, cause stored_size is string len,
1318    //                    but bytes_size includes zero byte.
1319
1320    GBENTRY      *gbe  = gbd->as_entry();
1321    GB_MAIN_TYPE *Main = GB_MAIN(gbe);
1322    GBQUARK       key  = GB_KEY_QUARK(gbe);
1323    GB_TYPES      type = gbe->type();
1324
1325    gb_assert(implicated(type == GB_STRING, stored_size == bytes_size-1)); // size constraint for strings not fulfilled!
1326
1327    gb_save_extern_data_in_ts__and_uncache(gbe);
1328
1329    int compression_mask = gb_get_compression_mask(Main, key, type);
1330
1331    const char *d;
1332    size_t      memsize;
1333    if (compression_mask) {
1334        d = gb_compress_data(gbe, key, s, bytes_size, &memsize, compression_mask, false);
1335    }
1336    else {
1337        d = NULp;
1338    }
1339    if (d) {
1340        gbe->flags.compressed_data = 1;
1341    }
1342    else {
1343        d = s;
1344        gbe->flags.compressed_data = 0;
1345        memsize = bytes_size;
1346    }
1347
1348    gb_assert(!gbe->cache_index); // insert_data() will recreate the cache-entry (if entry is_indexed)
1349    gbe->insert_data(d, stored_size, memsize);
1350    gb_touch_entry(gbe, GB_NORMAL_CHANGE);
1351    GB_DO_CALLBACKS(gbe);
1352
1353    return NULp;
1354}
1355
1356GB_ERROR GB_write_string(GBDATA *gbd, const char *s) {
1357    GBENTRY *gbe = gbd->as_entry();
1358    GB_TEST_WRITE(gbe, GB_STRING, "GB_write_string");
1359    GB_TEST_NON_BUFFER(s, "GB_write_string");        // compress would destroy the other buffer
1360
1361    if (!s) s = "";
1362    size_t size = strlen(s);
1363
1364    // no zero len strings allowed
1365    if (gbe->memsize() && (size == gbe->size())) {
1366        if (!strcmp(s, GB_read_pntr(gbe))) return NULp;
1367    }
1368#if defined(DEBUG) && 0
1369    // check for error (in compression)
1370    {
1371        GB_ERROR error = GB_write_pntr(gbe, s, size+1, size);
1372        if (!error) {
1373            char *check = GB_read_string(gbe);
1374
1375            gb_assert(check);
1376            gb_assert(strcmp(check, s) == 0);
1377
1378            free(check);
1379        }
1380        return error;
1381    }
1382#else
1383    return GB_write_pntr(gbe, s, size+1, size);
1384#endif // DEBUG
1385}
1386
1387GB_ERROR GB_write_bits(GBDATA *gbd, const char *bits, long size, const char *c_0) {
1388    GBENTRY *gbe = gbd->as_entry();
1389    GB_TEST_WRITE(gbe, GB_BITS, "GB_write_bits");
1390    GB_TEST_NON_BUFFER(bits, "GB_write_bits");       // compress would destroy the other buffer
1391    gb_save_extern_data_in_ts(gbe);
1392
1393    long  memsize;
1394    char *d = gb_compress_bits(bits, size, (const unsigned char *)c_0, &memsize);
1395
1396    gbe->flags.compressed_data = 1;
1397    gbe->insert_data(d, size, memsize);
1398    gb_touch_entry(gbe, GB_NORMAL_CHANGE);
1399    GB_DO_CALLBACKS(gbe);
1400    return NULp;
1401}
1402
1403GB_ERROR GB_write_bytes(GBDATA *gbd, const char *s, long size) {
1404    GB_TEST_WRITE(gbd, GB_BYTES, "GB_write_bytes");
1405    return GB_write_pntr(gbd, s, size, size);
1406}
1407
1408GB_ERROR GB_write_ints(GBDATA *gbd, const GB_UINT4 *i, long size) {
1409    GB_TEST_WRITE(gbd, GB_INTS, "GB_write_ints");
1410    GB_TEST_NON_BUFFER((char *)i, "GB_write_ints");  // compress would destroy the other buffer
1411
1412    if (0x01020304 != htonl((GB_UINT4)0x01020304)) {
1413        long      j;
1414        char     *buf2 = GB_give_other_buffer((char *)i, size<<2);
1415        GB_UINT4 *s    = (GB_UINT4 *)i;
1416        GB_UINT4 *d    = (GB_UINT4 *)buf2;
1417
1418        for (j=size; j; j--) {
1419            *(d++) = htonl(*(s++));
1420        }
1421        i = (GB_UINT4 *)buf2;
1422    }
1423    return GB_write_pntr(gbd, (char *)i, size* 4 /* sizeof(long4) */, size);
1424}
1425
1426GB_ERROR GB_write_floats(GBDATA *gbd, const float *f, long size) {
1427    long fullsize = size * sizeof(float);
1428    GB_TEST_WRITE(gbd, GB_FLOATS, "GB_write_floats");
1429    GB_TEST_NON_BUFFER((char *)f, "GB_write_floats"); // compress would destroy the other buffer
1430
1431    {
1432        XDR    xdrs;
1433        long   i;
1434        char  *buf2 = GB_give_other_buffer((char *)f, fullsize);
1435        float *s    = (float *)f;
1436
1437        xdrmem_create(&xdrs, buf2, (int)fullsize, XDR_ENCODE);
1438        for (i=size; i; i--) {
1439            xdr_float(&xdrs, s);
1440            s++;
1441        }
1442        xdr_destroy (&xdrs);
1443        f = (float*)(void*)buf2;
1444    }
1445    return GB_write_pntr(gbd, (char *)f, size*sizeof(float), size);
1446}
1447
1448GB_ERROR GB_write_autoconv_string(GBDATA *gbd, const char *val) {
1449    /*! writes data to database field using automatic conversion.
1450     *  Warning: Conversion may cause silent data-loss!
1451     *           (e.g. writing "hello" to a numeric db-field results in zero content)
1452     *
1453     *  Writing back the unmodified(!) result of GB_read_as_string will not cause data loss.
1454     *
1455     *  Consider using the GB_write_lossless_...() functions below (and their counterparts GB_read_lossless_...()).
1456     */
1457    switch (gbd->type()) {
1458        case GB_STRING: return GB_write_string(gbd, val);
1459        case GB_BYTE:   return GB_write_byte(gbd, atoi(val));
1460        case GB_INT:    return GB_write_int(gbd, atoi(val));
1461        case GB_FLOAT:  {
1462            float f;
1463            GB_ERROR error = GB_safe_atof(val, &f);
1464            return error ? error : GB_write_float(gbd, f);
1465        }
1466        case GB_BITS:   return GB_write_bits(gbd, val, strlen(val), "0");
1467        default: return GBS_global_string("Error: You cannot use GB_write_autoconv_string on this type of entry (%s)", GB_read_key_pntr(gbd));
1468    }
1469}
1470
1471GB_ERROR GB_write_lossless_byte(GBDATA *gbd, uint8_t byte) {
1472    /*! Writes an uint8_t to a database field capable to store any value w/o loss.
1473     *  @return error otherwise
1474     *  The corresponding field filter is FIELD_FILTER_BYTE_WRITEABLE.
1475     */
1476    switch (gbd->type()) {
1477        case GB_BYTE:   return GB_write_byte(gbd, byte);
1478        case GB_INT:    return GB_write_int(gbd, byte);
1479        case GB_FLOAT:  return GB_write_float(gbd, byte);
1480        case GB_STRING: {
1481            char buffer[4];
1482            sprintf(buffer, "%u", unsigned(byte));
1483            return GB_write_string(gbd, buffer);
1484        }
1485
1486        default: return cannot_use_fun4entry("GB_write_lossless_byte", gbd);
1487    }
1488}
1489
1490GB_ERROR GB_write_lossless_int(GBDATA *gbd, int32_t i) {
1491    /*! Writes an int32_t to a database field capable to store any value w/o loss.
1492     *  @return error otherwise
1493     *  The corresponding field filter is FIELD_FILTER_INT_WRITEABLE.
1494     */
1495
1496    switch (gbd->type()) {
1497        case GB_INT:    return GB_write_int(gbd, i);
1498        case GB_STRING: {
1499            const int BUFSIZE = 30;
1500            char      buffer[BUFSIZE];
1501#if defined(ASSERTION_USED)
1502            int printed =
1503#endif
1504                sprintf(buffer, "%i", i);
1505            gb_assert(printed<BUFSIZE);
1506            return GB_write_string(gbd, buffer);
1507        }
1508
1509        default: return cannot_use_fun4entry("GB_write_lossless_int", gbd);
1510    }
1511}
1512
1513GB_ERROR GB_write_lossless_float(GBDATA *gbd, float f) {
1514    /*! Writes a float to a database field capable to store any value w/o loss.
1515     *  @return error otherwise
1516     *  The corresponding field filter is FIELD_FILTER_FLOAT_WRITEABLE.
1517     */
1518
1519    switch (gbd->type()) {
1520        case GB_FLOAT:  return GB_write_float(gbd, f);
1521        case GB_STRING: {
1522            const int BUFSIZE = 30;
1523            char      buffer[BUFSIZE];
1524#if defined(ASSERTION_USED)
1525            int printed =
1526#endif
1527                sprintf(buffer, "%e", f);
1528            gb_assert(printed<BUFSIZE);
1529            return GB_write_string(gbd, buffer);
1530        }
1531
1532        default: return cannot_use_fun4entry("GB_write_lossless_float", gbd);
1533    }
1534}
1535
1536// ---------------------------
1537//      security functions
1538
1539int GB_read_security_write(GBDATA *gbd) {
1540    GB_test_transaction(gbd);
1541    return GB_GET_SECURITY_WRITE(gbd);
1542}
1543int GB_read_security_read(GBDATA *gbd) {
1544    GB_test_transaction(gbd);
1545    return GB_GET_SECURITY_READ(gbd);
1546}
1547int GB_read_security_delete(GBDATA *gbd) {
1548    GB_test_transaction(gbd);
1549    return GB_GET_SECURITY_DELETE(gbd);
1550}
1551GB_ERROR GB_write_security_write(GBDATA *gbd, unsigned long level) {
1552    GB_MAIN_TYPE *Main = GB_MAIN(gbd);
1553    GB_test_transaction(Main);
1554
1555    if (GB_GET_SECURITY_WRITE(gbd)>Main->security_level) return gb_security_error(gbd);
1556    if (GB_GET_SECURITY_WRITE(gbd) == level) return NULp;
1557    GB_PUT_SECURITY_WRITE(gbd, level);
1558    gb_touch_entry(gbd, GB_NORMAL_CHANGE);
1559    GB_DO_CALLBACKS(gbd);
1560    return NULp;
1561}
1562GB_ERROR GB_write_security_read(GBDATA *gbd, unsigned long level) { // @@@ unused
1563    GB_MAIN_TYPE *Main = GB_MAIN(gbd);
1564    GB_test_transaction(Main);
1565    if (GB_GET_SECURITY_WRITE(gbd)>Main->security_level) return gb_security_error(gbd);
1566    if (GB_GET_SECURITY_READ(gbd) == level) return NULp;
1567    GB_PUT_SECURITY_READ(gbd, level);
1568    gb_touch_entry(gbd, GB_NORMAL_CHANGE);
1569    GB_DO_CALLBACKS(gbd);
1570    return NULp;
1571}
1572GB_ERROR GB_write_security_delete(GBDATA *gbd, unsigned long level) {
1573    GB_MAIN_TYPE *Main = GB_MAIN(gbd);
1574    GB_test_transaction(Main);
1575    if (GB_GET_SECURITY_WRITE(gbd)>Main->security_level) return gb_security_error(gbd);
1576    if (GB_GET_SECURITY_DELETE(gbd) == level) return NULp;
1577    GB_PUT_SECURITY_DELETE(gbd, level);
1578    gb_touch_entry(gbd, GB_NORMAL_CHANGE);
1579    GB_DO_CALLBACKS(gbd);
1580    return NULp;
1581}
1582GB_ERROR GB_write_security_levels(GBDATA *gbd, unsigned long readlevel, unsigned long writelevel, unsigned long deletelevel) {
1583    GB_MAIN_TYPE *Main = GB_MAIN(gbd);
1584    GB_test_transaction(Main);
1585    if (GB_GET_SECURITY_WRITE(gbd)>Main->security_level) return gb_security_error(gbd);
1586    GB_PUT_SECURITY_WRITE(gbd, writelevel);
1587    GB_PUT_SECURITY_READ(gbd, readlevel);
1588    GB_PUT_SECURITY_DELETE(gbd, deletelevel);
1589    gb_touch_entry(gbd, GB_NORMAL_CHANGE);
1590    GB_DO_CALLBACKS(gbd);
1591    return NULp;
1592}
1593
1594void GB_change_my_security(GBDATA *gbd, int level) {
1595    GB_MAIN(gbd)->security_level = level<0 ? 0 : (level>7 ? 7 : level);
1596}
1597
1598void GB_push_my_security(GBDATA *gbd) {
1599    // for internal use only
1600
1601    GB_MAIN_TYPE *Main = GB_MAIN(gbd);
1602    Main->pushed_security_level++;
1603    if (Main->pushed_security_level <= 1) {
1604        Main->old_security_level = Main->security_level;
1605        Main->security_level = 7;
1606    }
1607}
1608
1609void GB_pop_my_security(GBDATA *gbd) {
1610    GB_MAIN_TYPE *Main = GB_MAIN(gbd);
1611    Main->pushed_security_level--;
1612    if (Main->pushed_security_level <= 0) {
1613        Main->security_level = Main->old_security_level;
1614    }
1615}
1616
1617
1618// ------------------------
1619//      Key information
1620
1621GB_TYPES GB_read_type(GBDATA *gbd) {
1622    GB_test_transaction(gbd);
1623    return gbd->type();
1624}
1625
1626bool GB_is_container(GBDATA *gbd) {
1627    return gbd && gbd->is_container();
1628}
1629
1630char *GB_read_key(GBDATA *gbd) {
1631    return ARB_strdup(GB_read_key_pntr(gbd));
1632}
1633
1634GB_CSTR GB_read_key_pntr(GBDATA *gbd) {
1635    GB_CSTR k;
1636    GB_test_transaction(gbd);
1637    k         = GB_KEY(gbd);
1638    if (!k) k = GBS_global_string("<invalid key (quark=%i)>", GB_KEY_QUARK(gbd));
1639    return k;
1640}
1641
1642GB_CSTR gb_read_key_pntr(GBDATA *gbd) {
1643    return GB_KEY(gbd);
1644}
1645
1646GBQUARK gb_find_or_create_quark(GB_MAIN_TYPE *Main, const char *key) {
1647    //! @return existing or newly created quark for 'key'
1648    GBQUARK quark = key2quark(Main, key);
1649    if (!quark) {
1650        if (!key[0]) GBK_terminate("Attempt to create quark from empty key");
1651        quark = gb_create_key(Main, key, true);
1652    }
1653    return quark;
1654}
1655
1656GBQUARK gb_find_or_create_NULL_quark(GB_MAIN_TYPE *Main, const char *key) {
1657    // similar to gb_find_or_create_quark,
1658    // but if 'key' is NULp, quark 0 will be returned.
1659    //
1660    // Use this function with care.
1661    //
1662    // Known good use:
1663    // - create main entry and its dummy father via gb_make_container()
1664
1665    return key ? gb_find_or_create_quark(Main, key) : 0;
1666}
1667
1668GBQUARK GB_find_existing_quark(GBDATA *gbd, const char *key) {
1669    //! @return existing quark for 'key' (-1 if key is NULp, 0 if key is unknown)
1670    return key2quark(GB_MAIN(gbd), key);
1671}
1672
1673GBQUARK GB_find_or_create_quark(GBDATA *gbd, const char *key) {
1674    //! @return existing or newly created quark for 'key'
1675    return gb_find_or_create_quark(GB_MAIN(gbd), key);
1676}
1677
1678
1679// ---------------------------------------------
1680
1681GBQUARK GB_get_quark(GBDATA *gbd) {
1682    return GB_KEY_QUARK(gbd);
1683}
1684
1685bool GB_has_key(GBDATA *gbd, const char *key) {
1686    GBQUARK quark = GB_find_existing_quark(gbd, key); 
1687    return quark && (quark == GB_get_quark(gbd));
1688}
1689
1690// ---------------------------------------------
1691
1692long GB_read_clock(GBDATA *gbd) {
1693    if (GB_ARRAY_FLAGS(gbd).changed) return GB_MAIN(gbd)->clock;
1694    return gbd->update_date();
1695}
1696
1697// ---------------------------------------------
1698//      Get and check the database hierarchy
1699
1700GBDATA *GB_get_father(GBDATA *gbd) {
1701    // Get the father of an entry
1702    GB_test_transaction(gbd);
1703    return gbd->get_father();
1704}
1705
1706GBDATA *GB_get_grandfather(GBDATA *gbd) {
1707    GB_test_transaction(gbd);
1708
1709    GBDATA *gb_grandpa = GB_FATHER(gbd);
1710    if (gb_grandpa) {
1711        gb_grandpa = GB_FATHER(gb_grandpa);
1712        if (gb_grandpa && !GB_FATHER(gb_grandpa)) gb_grandpa = NULp; // never return dummy_father of root container
1713    }
1714    return gb_grandpa;
1715}
1716
1717// Get the root entry (gb_main)
1718GBDATA *GB_get_root(GBDATA *gbd) { return GB_MAIN(gbd)->gb_main(); }
1719GBCONTAINER *gb_get_root(GBENTRY *gbe) { return GB_MAIN(gbe)->root_container; }
1720GBCONTAINER *gb_get_root(GBCONTAINER *gbc) { return GB_MAIN(gbc)->root_container; }
1721
1722bool GB_check_father(GBDATA *gbd, GBDATA *gb_maybefather) {
1723    // Test whether an entry is a subentry of another
1724    GBDATA *gbfather;
1725    for (gbfather = GB_get_father(gbd);
1726         gbfather;
1727         gbfather = GB_get_father(gbfather))
1728    {
1729        if (gbfather == gb_maybefather) return true;
1730    }
1731    return false;
1732}
1733
1734// --------------------------
1735//      create and rename
1736
1737GBENTRY *gb_create(GBCONTAINER *father, const char *key, GB_TYPES type) {
1738    GBENTRY *gbe = gb_make_entry(father, key, -1, 0, type);
1739    gb_touch_header(GB_FATHER(gbe));
1740    gb_touch_entry(gbe, GB_CREATED);
1741
1742    gb_assert(GB_ARRAY_FLAGS(gbe).changed < GB_DELETED); // happens sometimes -> needs debugging
1743
1744    return gbe;
1745}
1746
1747GBCONTAINER *gb_create_container(GBCONTAINER *father, const char *key) {
1748    // Create a container, do not check anything
1749    GBCONTAINER *gbc = gb_make_container(father, key, -1, 0);
1750    gb_touch_header(GB_FATHER(gbc));
1751    gb_touch_entry(gbc, GB_CREATED);
1752    return gbc;
1753}
1754
1755GBDATA *GB_create(GBDATA *father, const char *key, GB_TYPES type) {
1756    /*! Create a DB entry
1757     *
1758     * @param father container to create DB field in
1759     * @param key name of field
1760     * @param type field type
1761     *
1762     * @return
1763     * - created DB entry
1764     * - NULp on failure (error is exported then)
1765     *
1766     * @see GB_create_container()
1767     */
1768
1769    if (GB_check_key(key)) {
1770        GB_print_error();
1771        return NULp;
1772    }
1773
1774    if (type == GB_DB) {
1775        gb_assert(type != GB_DB); // you like to use GB_create_container!
1776        GB_export_error("GB_create error: can't create containers");
1777        return NULp;
1778    }
1779
1780    if (!father) {
1781        GB_internal_errorf("GB_create error in GB_create:\nno father (key = '%s')", key);
1782        return NULp;
1783    }
1784    GB_test_transaction(father);
1785    if (father->is_entry()) {
1786        GB_export_errorf("GB_create: father (%s) is not of GB_DB type (%i) (creating '%s')",
1787                         GB_read_key_pntr(father), father->type(), key);
1788        return NULp;
1789    }
1790
1791    if (type == GB_POINTER) {
1792        if (!GB_in_temporary_branch(father)) {
1793            GB_export_error("GB_create: pointers only allowed in temporary branches");
1794            return NULp;
1795        }
1796    }
1797
1798    return gb_create(father->expect_container(), key, type);
1799}
1800
1801GBDATA *GB_create_container(GBDATA *father, const char *key) {
1802    /*! Create a new DB container
1803     *
1804     * @param father parent container
1805     * @param key name of created container
1806     *
1807     * @return
1808     * - created container
1809     * - NULp on failure (error is exported then)
1810     *
1811     * @see GB_create()
1812     */
1813
1814    if (GB_check_key(key)) {
1815        GB_print_error();
1816        return NULp;
1817    }
1818
1819    if ((*key == '\0')) {
1820        GB_export_error("GB_create error: empty key");
1821        return NULp;
1822    }
1823    if (!father) {
1824        GB_internal_errorf("GB_create error in GB_create:\nno father (key = '%s')", key);
1825        return NULp;
1826    }
1827
1828    GB_test_transaction(father);
1829    return gb_create_container(father->expect_container(), key);
1830}
1831
1832// ----------------------
1833//      recompression
1834
1835#if defined(WARN_TODO)
1836#warning rename gb_set_compression into gb_recompress (misleading name)
1837#endif
1838
1839static GB_ERROR gb_set_compression(GBDATA *source) {
1840    GB_ERROR error = NULp;
1841    GB_test_transaction(source);
1842
1843    switch (source->type()) {
1844        case GB_STRING: {
1845            char *str = GB_read_string(source);
1846            GB_write_string(source, "");
1847            GB_write_string(source, str);
1848            free(str);
1849            break;
1850        }
1851        case GB_BITS:
1852        case GB_BYTES:
1853        case GB_INTS:
1854        case GB_FLOATS:
1855            break;
1856        case GB_DB:
1857            for (GBDATA *gb_p = GB_child(source); gb_p && !error; gb_p = GB_nextChild(gb_p)) {
1858                error = gb_set_compression(gb_p);
1859            }
1860            break;
1861        default:
1862            break;
1863    }
1864    return error;
1865}
1866
1867bool GB_allow_compression(GBDATA *gb_main, bool allow_compression) {
1868    GB_MAIN_TYPE *Main      = GB_MAIN(gb_main);
1869    int           prev_mask = Main->compression_mask;
1870    Main->compression_mask  = allow_compression ? -1 : 0;
1871
1872    return prev_mask == 0 ? false : true;
1873}
1874
1875
1876GB_ERROR GB_delete(GBDATA*& source) {
1877    GBDATA *gb_main;
1878
1879    GB_test_transaction(source);
1880    if (GB_GET_SECURITY_DELETE(source)>GB_MAIN(source)->security_level) {
1881        return GBS_global_string("Security error: deleting entry '%s' not permitted", GB_read_key_pntr(source));
1882    }
1883
1884    gb_main = GB_get_root(source);
1885
1886    if (source->flags.compressed_data) {
1887        bool was_allowed = GB_allow_compression(gb_main, false);
1888        gb_set_compression(source); // write data w/o compression (otherwise GB_read_old_value... won't work)
1889        GB_allow_compression(gb_main, was_allowed);
1890    }
1891
1892    {
1893        GB_MAIN_TYPE *Main = GB_MAIN(source);
1894        if (Main->get_transaction_level() < 0) { // no transaction mode
1895            gb_delete_entry(source);
1896            Main->call_pending_callbacks();
1897        }
1898        else {
1899            gb_touch_entry(source, GB_DELETED);
1900        }
1901    }
1902    return NULp;
1903}
1904
1905GB_ERROR gb_delete_force(GBDATA *source) {
1906    // delete always
1907    gb_touch_entry(source, GB_DELETED);
1908    return NULp;
1909}
1910
1911
1912// ------------------
1913//      Copy data
1914
1915#if defined(WARN_TODO)
1916#warning replace GB_copy with GB_copy_with_protection after release
1917#endif
1918
1919GB_ERROR GB_copy(GBDATA *dest, GBDATA *source) {
1920    return GB_copy_with_protection(dest, source, false);
1921}
1922
1923GB_ERROR GB_copy_with_protection(GBDATA *dest, GBDATA *source, bool copy_all_protections) {
1924    GB_ERROR error = NULp;
1925    GB_test_transaction(source);
1926
1927    GB_TYPES type = source->type();
1928    if (dest->type() != type) {
1929        return GB_export_errorf("incompatible types in GB_copy (source %s:%u != %s:%u",
1930                                GB_read_key_pntr(source), type, GB_read_key_pntr(dest), dest->type());
1931    }
1932
1933    switch (type) {
1934        case GB_INT:
1935            error = GB_write_int(dest, GB_read_int(source));
1936            break;
1937        case GB_FLOAT:
1938            error = GB_write_float(dest, GB_read_float(source));
1939            break;
1940        case GB_BYTE:
1941            error = GB_write_byte(dest, GB_read_byte(source));
1942            break;
1943        case GB_STRING:     // No local compression
1944            error = GB_write_string(dest, GB_read_char_pntr(source));
1945            break;
1946        case GB_OBSOLETE:
1947            error = GB_set_temporary(dest); // exclude obsolete type from next save
1948            break;
1949        case GB_BITS:       // only local compressions for the following types
1950        case GB_BYTES:
1951        case GB_INTS:
1952        case GB_FLOATS: {
1953            GBENTRY *source_entry = source->as_entry();
1954            GBENTRY *dest_entry   = dest->as_entry();
1955
1956            gb_save_extern_data_in_ts(dest_entry);
1957            dest_entry->insert_data(source_entry->data(), source_entry->size(), source_entry->memsize());
1958
1959            dest->flags.compressed_data = source->flags.compressed_data;
1960            break;
1961        }
1962        case GB_DB: {
1963            if (!dest->is_container()) {
1964                GB_ERROR err = GB_export_errorf("GB_COPY Type conflict %s:%i != %s:%i",
1965                                                GB_read_key_pntr(dest), dest->type(), GB_read_key_pntr(source), GB_DB);
1966                GB_internal_error(err);
1967                return err;
1968            }
1969
1970            GBCONTAINER *destc   = dest->as_container();
1971            GBCONTAINER *sourcec = source->as_container();
1972
1973            if (sourcec->flags2.folded_container) gb_unfold(sourcec, -1, -1);
1974            if (destc->flags2.folded_container)   gb_unfold(destc, 0, -1);
1975
1976            for (GBDATA *gb_p = GB_child(sourcec); gb_p; gb_p = GB_nextChild(gb_p)) {
1977                const char *key = GB_read_key_pntr(gb_p);
1978                GBDATA     *gb_d;
1979
1980                if (gb_p->is_container()) {
1981                    gb_d = GB_create_container(destc, key);
1982                    gb_create_header_array(gb_d->as_container(), gb_p->as_container()->d.size);
1983                }
1984                else {
1985                    gb_d = GB_create(destc, key, gb_p->type());
1986                }
1987
1988                if (!gb_d) error = GB_await_error();
1989                else error       = GB_copy_with_protection(gb_d, gb_p, copy_all_protections);
1990
1991                if (error) break;
1992            }
1993
1994            destc->flags3 = sourcec->flags3;
1995            break;
1996        }
1997        default:
1998            error = GB_export_error("GB_copy-error: unhandled type");
1999    }
2000    if (error) return error;
2001
2002    gb_touch_entry(dest, GB_NORMAL_CHANGE);
2003
2004    dest->flags.security_read = source->flags.security_read;
2005    if (copy_all_protections) {
2006        dest->flags.security_write  = source->flags.security_write;
2007        dest->flags.security_delete = source->flags.security_delete;
2008    }
2009
2010    return NULp;
2011}
2012
2013
2014static char *gb_stpcpy(char *dest, const char *source) {
2015    while ((*dest++=*source++)) ;
2016    return dest-1; // return pointer to last copied character (which is \0)
2017}
2018
2019char* GB_get_subfields(GBDATA *gbd) {
2020    /*! Get all subfield names
2021     *
2022     * @return all subfields of 'gbd' as ';'-separated heap-copy
2023     * (first and last char of result is a ';')
2024     */
2025    GB_test_transaction(gbd);
2026
2027    char *result = NULp;
2028    if (gbd->is_container()) {
2029        GBCONTAINER *gbc           = gbd->as_container();
2030        int          result_length = 0;
2031
2032        if (gbc->flags2.folded_container) {
2033            gb_unfold(gbc, -1, -1);
2034        }
2035
2036        for (GBDATA *gbp = GB_child(gbd); gbp; gbp = GB_nextChild(gbp)) {
2037            const char *key = GB_read_key_pntr(gbp);
2038            int keylen = strlen(key);
2039
2040            if (result) {
2041                char *neu_result = ARB_alloc<char>(result_length+keylen+1+1);
2042
2043                if (neu_result) {
2044                    char *p = gb_stpcpy(neu_result, result);
2045                    p = gb_stpcpy(p, key);
2046                    *p++ = ';';
2047                    p[0] = 0;
2048
2049                    freeset(result, neu_result);
2050                    result_length += keylen+1;
2051                }
2052                else {
2053                    gb_assert(0);
2054                }
2055            }
2056            else {
2057                ARB_alloc(result, 1+keylen+1+1);
2058                result[0] = ';';
2059                strcpy(result+1, key);
2060                result[keylen+1] = ';';
2061                result[keylen+2] = 0;
2062                result_length = keylen+2;
2063            }
2064        }
2065    }
2066    else {
2067        result = ARB_strdup(";");
2068    }
2069
2070    return result;
2071}
2072
2073// --------------------------
2074//      temporary entries
2075
2076GB_ERROR GB_set_temporary(GBDATA *gbd) { // goes to header: __ATTR__USERESULT
2077    /*! if the temporary flag is set, then that entry (including all subentries) will not be saved
2078     * @see GB_clear_temporary() and GB_is_temporary()
2079     */
2080
2081    GB_ERROR error = NULp;
2082    GB_test_transaction(gbd);
2083
2084    if (GB_GET_SECURITY_DELETE(gbd)>GB_MAIN(gbd)->security_level) {
2085        error = GBS_global_string("Security error in GB_set_temporary: %s", GB_read_key_pntr(gbd));
2086    }
2087    else {
2088        gbd->flags.temporary = 1;
2089        gb_touch_entry(gbd, GB_NORMAL_CHANGE);
2090    }
2091    RETURN_ERROR(error);
2092}
2093
2094GB_ERROR GB_clear_temporary(GBDATA *gbd) { // @@@ used in ptpan branch - do not remove
2095    //! undo effect of GB_set_temporary()
2096
2097    GB_test_transaction(gbd);
2098    gbd->flags.temporary = 0;
2099    gb_touch_entry(gbd, GB_NORMAL_CHANGE);
2100    return NULp;
2101}
2102
2103bool GB_is_temporary(GBDATA *gbd) {
2104    //! @see GB_set_temporary() and GB_in_temporary_branch()
2105    GB_test_transaction(gbd);
2106    return (long)gbd->flags.temporary;
2107}
2108
2109bool GB_in_temporary_branch(GBDATA *gbd) {
2110    /*! @return true, if 'gbd' is member of a temporary subtree,
2111     * i.e. if GB_is_temporary(itself or any parent)
2112     */
2113
2114    if (GB_is_temporary(gbd)) return true;
2115
2116    GBDATA *gb_parent = GB_get_father(gbd);
2117    if (!gb_parent) return false;
2118
2119    return GB_in_temporary_branch(gb_parent);
2120}
2121
2122// ---------------------
2123//      transactions
2124
2125GB_ERROR GB_MAIN_TYPE::initial_client_transaction() {
2126    // the first client transaction ever
2127    transaction_level = 1;
2128    GB_ERROR error    = gbcmc_init_transaction(root_container);
2129    if (!error) ++clock;
2130    return error;
2131}
2132
2133inline GB_ERROR GB_MAIN_TYPE::start_transaction() {
2134    gb_assert(transaction_level == 0);
2135
2136    transaction_level   = 1;
2137    aborted_transaction = 0;
2138
2139    GB_ERROR error = NULp;
2140    if (is_client()) {
2141        error = gbcmc_begin_transaction(gb_main());
2142        if (!error) {
2143            error = gb_commit_transaction_local_rek(gb_main_ref(), 0, NULp); // init structures
2144            gb_untouch_children_and_me(root_container);
2145        }
2146    }
2147
2148    if (!error) {
2149        /* do all callbacks
2150         * cb that change the db are no problem, because it's the beginning of a ta
2151         */
2152        call_pending_callbacks();
2153        ++clock;
2154    }
2155    return error;
2156}
2157
2158inline GB_ERROR GB_MAIN_TYPE::begin_transaction() {
2159    if (transaction_level>0) return GBS_global_string("attempt to start a NEW transaction (at transaction level %i)", transaction_level);
2160    if (transaction_level == 0) return start_transaction();
2161    return NULp; // NO_TRANSACTION_MODE
2162}
2163
2164inline GB_ERROR GB_MAIN_TYPE::abort_transaction() {
2165    if (transaction_level<=0) {
2166        if (transaction_level<0) return "GB_abort_transaction: Attempt to abort transaction in no-transaction-mode";
2167        return "GB_abort_transaction: No transaction running";
2168    }
2169    if (transaction_level>1) {
2170        aborted_transaction = 1;
2171        return pop_transaction();
2172    }
2173
2174    gb_abort_transaction_local_rek(gb_main_ref());
2175    if (is_client()) {
2176        GB_ERROR error = gbcmc_abort_transaction(gb_main());
2177        if (error) return error;
2178    }
2179    clock--;
2180    call_pending_callbacks();
2181    transaction_level = 0;
2182    gb_untouch_children_and_me(root_container);
2183    return NULp;
2184}
2185
2186inline GB_ERROR GB_MAIN_TYPE::commit_transaction() {
2187    GB_ERROR      error = NULp;
2188    GB_CHANGE     flag;
2189
2190    if (!transaction_level) {
2191        return "commit_transaction: No transaction running";
2192    }
2193    if (transaction_level>1) {
2194        return GBS_global_string("attempt to commit at transaction level %i", transaction_level);
2195    }
2196    if (aborted_transaction) {
2197        aborted_transaction = 0;
2198        return abort_transaction();
2199    }
2200    if (is_server()) {
2201        char *error1 = gb_set_undo_sync(gb_main());
2202        while (1) {
2203            flag = (GB_CHANGE)GB_ARRAY_FLAGS(gb_main()).changed;
2204            if (!flag) break;           // nothing to do
2205            error = gb_commit_transaction_local_rek(gb_main_ref(), 0, NULp);
2206            gb_untouch_children_and_me(root_container);
2207            if (error) break;
2208            call_pending_callbacks();
2209        }
2210        gb_disable_undo(gb_main());
2211        if (error1) {
2212            transaction_level = 0;
2213            gb_assert(error); // maybe return error1?
2214            return error; // @@@ huh? why not return error1
2215        }
2216    }
2217    else {
2218        gb_disable_undo(gb_main());
2219        while (1) {
2220            flag = (GB_CHANGE)GB_ARRAY_FLAGS(gb_main()).changed;
2221            if (!flag) break;           // nothing to do
2222
2223            error = gbcmc_begin_sendupdate(gb_main());                       if (error) break;
2224            error = gb_commit_transaction_local_rek(gb_main_ref(), 1, NULp); if (error) break;
2225            error = gbcmc_end_sendupdate(gb_main());                         if (error) break;
2226
2227            gb_untouch_children_and_me(root_container);
2228            call_pending_callbacks();
2229        }
2230        if (!error) error = gbcmc_commit_transaction(gb_main());
2231
2232    }
2233    transaction_level = 0;
2234    return error;
2235}
2236
2237inline GB_ERROR GB_MAIN_TYPE::push_transaction() {
2238    if (transaction_level == 0) return start_transaction();
2239    if (transaction_level>0) ++transaction_level;
2240    // transaction<0 is NO_TRANSACTION_MODE
2241    return NULp;
2242}
2243
2244inline GB_ERROR GB_MAIN_TYPE::pop_transaction() {
2245    if (transaction_level==0) return "attempt to pop nested transaction while none running";
2246    if (transaction_level<0)  return NULp;  // NO_TRANSACTION_MODE
2247    if (transaction_level==1) return commit_transaction();
2248    transaction_level--;
2249    return NULp;
2250}
2251
2252inline GB_ERROR GB_MAIN_TYPE::no_transaction() {
2253    if (is_client()) return "Tried to disable transactions in a client";
2254    transaction_level = -1;
2255    return NULp;
2256}
2257
2258GB_ERROR GB_MAIN_TYPE::send_update_to_server(GBDATA *gbd) {
2259    GB_ERROR error = NULp;
2260
2261    if (!transaction_level) error = "send_update_to_server: no transaction running";
2262    else if (is_server()) error   = "send_update_to_server: only possible from clients (not from server itself)";
2263    else {
2264        const gb_triggered_callback *chg_cbl_old = changeCBs.pending.get_tail();
2265        const gb_triggered_callback *del_cbl_old = deleteCBs.pending.get_tail();
2266
2267        error             = gbcmc_begin_sendupdate(gb_main());
2268        if (!error) error = gb_commit_transaction_local_rek(gbd, 2, NULp);
2269        if (!error) error = gbcmc_end_sendupdate(gb_main());
2270
2271        if (!error &&
2272            (chg_cbl_old != changeCBs.pending.get_tail() ||
2273             del_cbl_old != deleteCBs.pending.get_tail()))
2274        {
2275            error = "send_update_to_server triggered a callback (this is not allowed)";
2276        }
2277    }
2278    return error;
2279}
2280
2281// --------------------------------------
2282//      client transaction interface
2283
2284GB_ERROR GB_push_transaction(GBDATA *gbd) {
2285    /*! start a transaction if no transaction is running.
2286     * (otherwise only trace nested transactions)
2287     *
2288     * recommended transaction usage:
2289     *
2290     * \code
2291     * GB_ERROR myFunc() {
2292     *     GB_ERROR error = GB_push_transaction(gbd);
2293     *     if (!error) {
2294     *         error = ...;
2295     *     }
2296     *     return GB_end_transaction(gbd, error);
2297     * }
2298     *
2299     * void myFunc() {
2300     *     GB_ERROR error = GB_push_transaction(gbd);
2301     *     if (!error) {
2302     *         error = ...;
2303     *     }
2304     *     GB_end_transaction_show_error(gbd, error, aw_message);
2305     * }
2306     * \endcode
2307     *
2308     * @see GB_pop_transaction(), GB_end_transaction(), GB_begin_transaction()
2309     */
2310
2311    return GB_MAIN(gbd)->push_transaction();
2312}
2313
2314GB_ERROR GB_pop_transaction(GBDATA *gbd) {
2315    //! commit a transaction started with GB_push_transaction()
2316    return GB_MAIN(gbd)->pop_transaction();
2317}
2318GB_ERROR GB_begin_transaction(GBDATA *gbd) {
2319    /*! like GB_push_transaction(),
2320     * but fails if there is already an transaction running.
2321     * @see GB_commit_transaction() and GB_abort_transaction()
2322     */
2323    return GB_MAIN(gbd)->begin_transaction();
2324}
2325GB_ERROR GB_no_transaction(GBDATA *gbd) { // goes to header: __ATTR__USERESULT
2326    return GB_MAIN(gbd)->no_transaction();
2327}
2328
2329GB_ERROR GB_abort_transaction(GBDATA *gbd) {
2330    /*! abort a running transaction,
2331     * i.e. forget all changes made to DB inside the current transaction.
2332     *
2333     * May be called instead of GB_pop_transaction() or GB_commit_transaction()
2334     *
2335     * If a nested transactions got aborted,
2336     * committing a surrounding transaction will silently abort it as well.
2337     */
2338    return GB_MAIN(gbd)->abort_transaction();
2339}
2340
2341GB_ERROR GB_commit_transaction(GBDATA *gbd) {
2342    /*! commit a transaction started with GB_begin_transaction()
2343     *
2344     * commit changes made to DB.
2345     *
2346     * in case of nested transactions, this is equal to GB_pop_transaction()
2347     */
2348    return GB_MAIN(gbd)->commit_transaction();
2349}
2350
2351GB_ERROR GB_end_transaction(GBDATA *gbd, GB_ERROR error) {
2352    /*! abort or commit transaction
2353     *
2354     * @ param error
2355     * - if NULp commit transaction
2356     * - else abort transaction
2357     *
2358     * always commits in no-transaction-mode
2359     *
2360     * @return error or transaction error
2361     * @see GB_push_transaction() for example
2362     */
2363
2364    if (GB_get_transaction_level(gbd)<0) {
2365        ASSERT_RESULT(GB_ERROR, NULp, GB_pop_transaction(gbd));
2366    }
2367    else {
2368        if (error) GB_abort_transaction(gbd);
2369        else error = GB_pop_transaction(gbd);
2370    }
2371    return error;
2372}
2373
2374void GB_end_transaction_show_error(GBDATA *gbd, GB_ERROR error, void (*error_handler)(GB_ERROR)) {
2375    //! like GB_end_transaction(), but show error using 'error_handler'
2376    error = GB_end_transaction(gbd, error);
2377    if (error) error_handler(error);
2378}
2379
2380int GB_get_transaction_level(GBDATA *gbd) {
2381    /*! @return transaction level
2382     * <0 -> in no-transaction-mode (abort is impossible)
2383     *  0 -> not in transaction
2384     *  1 -> one single transaction
2385     *  2, ... -> nested transactions
2386     */
2387    return GB_MAIN(gbd)->get_transaction_level();
2388}
2389
2390GB_ERROR GB_release(GBDATA *gbd) {
2391    /*! free cached data in client.
2392     *
2393     * Warning: pointers into the freed region(s) will get invalid!
2394     */
2395    GBCONTAINER  *gbc;
2396    GBDATA       *gb;
2397    int           index;
2398    GB_MAIN_TYPE *Main = GB_MAIN(gbd);
2399
2400    GB_test_transaction(gbd);
2401    if (Main->is_server()) return NULp;
2402    if (GB_ARRAY_FLAGS(gbd).changed && !gbd->flags2.update_in_server) {
2403        GB_ERROR error = Main->send_update_to_server(gbd);
2404        if (error) return error;
2405    }
2406    if (gbd->type() != GB_DB) {
2407        GB_ERROR error = GB_export_errorf("You cannot release non container (%s)",
2408                                          GB_read_key_pntr(gbd));
2409        GB_internal_error(error);
2410        return error;
2411    }
2412    if (gbd->flags2.folded_container) return NULp;
2413    gbc = (GBCONTAINER *)gbd;
2414
2415    for (index = 0; index < gbc->d.nheader; index++) {
2416        if ((gb = GBCONTAINER_ELEM(gbc, index))) {
2417            gb_delete_entry(gb);
2418        }
2419    }
2420
2421    gbc->flags2.folded_container = 1;
2422    Main->call_pending_callbacks();
2423    return NULp;
2424}
2425
2426int GB_nsons(GBDATA *gbd) {
2427    /*! return number of child entries
2428     *
2429     * @@@ does this work in clients ?
2430     */
2431
2432    return gbd->is_container()
2433        ? gbd->as_container()->d.size
2434        : 0;
2435}
2436
2437void GB_disable_quicksave(GBDATA *gbd, const char *reason) {
2438    /*! Disable quicksaving database
2439     * @param gbd any DB node
2440     * @param reason why quicksaving is not allowed
2441     */
2442    freedup(GB_MAIN(gbd)->qs.quick_save_disabled, reason);
2443}
2444
2445GB_ERROR GB_resort_data_base(GBDATA *gb_main, GBDATA **new_order_list, long listsize) {
2446    {
2447        long client_count = GB_read_clients(gb_main);
2448        if (client_count<0) {
2449            return "Sorry: this program is not the arbdb server, you cannot resort your data";
2450        }
2451        if (client_count>0) {
2452            // resort will do a big amount of client update callbacks => disallow clients here
2453            bool called_from_macro = GB_inside_remote_action(gb_main);
2454            if (!called_from_macro) { // accept macro clients
2455                return GBS_global_string("There are %li clients (editors, tree programs) connected to this server.\n"
2456                                         "You need to close these clients before you can run this operation.",
2457                                         client_count);
2458            }
2459        }
2460    }
2461
2462    if (listsize <= 0) return NULp;
2463
2464    GBCONTAINER *father = GB_FATHER(new_order_list[0]);
2465    GB_disable_quicksave(gb_main, "some entries in the database got a new order");
2466
2467    gb_header_list *hl = GB_DATA_LIST_HEADER(father->d);
2468    for (long new_index = 0; new_index< listsize; new_index++) {
2469        long old_index = new_order_list[new_index]->index;
2470
2471        if (old_index < new_index) {
2472            GB_warningf("Warning at resort database: entry exists twice: %li and %li",
2473                        old_index, new_index);
2474        }
2475        else {
2476            GBDATA *ogb = GB_HEADER_LIST_GBD(hl[old_index]);
2477            GBDATA *ngb = GB_HEADER_LIST_GBD(hl[new_index]);
2478
2479            gb_header_list h = hl[new_index];
2480            hl[new_index] = hl[old_index];
2481            hl[old_index] = h;              // Warning: Relative Pointers are incorrect !!!
2482
2483            SET_GB_HEADER_LIST_GBD(hl[old_index], ngb);
2484            SET_GB_HEADER_LIST_GBD(hl[new_index], ogb);
2485
2486            if (ngb) ngb->index = old_index;
2487            if (ogb) ogb->index = new_index;
2488        }
2489    }
2490
2491    gb_touch_entry(father, GB_NORMAL_CHANGE);
2492    return NULp;
2493}
2494
2495GB_ERROR gb_resort_system_folder_to_top(GBCONTAINER *gb_main) {
2496    if (GB_read_clients(gb_main)<0) {
2497        return NULp; // we are not server
2498    }
2499
2500    GBDATA *gb_system = GB_entry(gb_main, GB_SYSTEM_FOLDER);
2501    if (!gb_system) {
2502        return GB_export_error("System databaseentry does not exist");
2503    }
2504
2505    GBDATA *gb_first = GB_child(gb_main);
2506    if (gb_first == gb_system) {
2507        return NULp;
2508    }
2509
2510    int      len            = GB_number_of_subentries(gb_main);
2511    GBDATA **new_order_list = ARB_calloc<GBDATA*>(len);
2512
2513    new_order_list[0] = gb_system;
2514    for (int i=1; i<len; i++) {
2515        new_order_list[i] = gb_first;
2516        do gb_first = GB_nextChild(gb_first); while (gb_first == gb_system);
2517    }
2518
2519    GB_ERROR error = GB_resort_data_base(gb_main, new_order_list, len);
2520    free(new_order_list);
2521
2522    return error;
2523}
2524
2525// ------------------------------
2526//      private(?) user flags
2527
2528STATIC_ASSERT_ANNOTATED(((GB_USERFLAG_ANY+1)&GB_USERFLAG_ANY) == 0, "not all bits set in GB_USERFLAG_ANY");
2529
2530#if defined(ASSERTION_USED)
2531inline bool legal_user_bitmask(unsigned char bitmask) {
2532    return bitmask>0 && bitmask<=GB_USERFLAG_ANY;
2533}
2534#endif
2535
2536inline gb_flag_types2& get_user_flags(GBDATA *gbd) {
2537    return gbd->expect_container()->flags2;
2538}
2539
2540bool GB_user_flag(GBDATA *gbd, unsigned char user_bit) {
2541    gb_assert(legal_user_bitmask(user_bit));
2542    return get_user_flags(gbd).user_bits & user_bit;
2543}
2544
2545void GB_raise_user_flag(GBDATA *gbd, unsigned char user_bit) {
2546    gb_assert(legal_user_bitmask(user_bit));
2547    gb_flag_types2& flags  = get_user_flags(gbd);
2548    flags.user_bits       |= user_bit;
2549}
2550void GB_clear_user_flag(GBDATA *gbd, unsigned char user_bit) {
2551    gb_assert(legal_user_bitmask(user_bit));
2552    gb_flag_types2& flags  = get_user_flags(gbd);
2553    flags.user_bits       &= (user_bit^GB_USERFLAG_ANY);
2554}
2555void GB_write_user_flag(GBDATA *gbd, unsigned char user_bit, bool state) {
2556    (state ? GB_raise_user_flag : GB_clear_user_flag)(gbd, user_bit);
2557}
2558
2559
2560// ------------------------
2561//      mark DB entries
2562
2563void GB_write_flag(GBDATA *gbd, long flag) {
2564    GBCONTAINER  *gbc  = gbd->expect_container();
2565    GB_MAIN_TYPE *Main = GB_MAIN(gbc);
2566
2567    GB_test_transaction(Main);
2568
2569    int ubit = Main->users[0]->userbit;
2570    int prev = GB_ARRAY_FLAGS(gbc).flags;
2571    gbc->flags.saved_flags = prev;
2572
2573    if (flag) {
2574        GB_ARRAY_FLAGS(gbc).flags |= ubit;
2575    }
2576    else {
2577        GB_ARRAY_FLAGS(gbc).flags &= ~ubit;
2578    }
2579    if (prev != (int)GB_ARRAY_FLAGS(gbc).flags) {
2580        gb_touch_entry(gbc, GB_NORMAL_CHANGE);
2581        gb_touch_header(GB_FATHER(gbc));
2582        GB_DO_CALLBACKS(gbc);
2583    }
2584}
2585
2586int GB_read_flag(GBDATA *gbd) {
2587    GB_test_transaction(gbd);
2588    if (GB_ARRAY_FLAGS(gbd).flags & GB_MAIN(gbd)->users[0]->userbit) return 1;
2589    else return 0;
2590}
2591
2592void GB_touch(GBDATA *gbd) {
2593    GB_test_transaction(gbd);
2594    gb_touch_entry(gbd, GB_NORMAL_CHANGE);
2595    GB_DO_CALLBACKS(gbd);
2596}
2597
2598
2599char GB_type_2_char(GB_TYPES type) {
2600    const char *type2char = "-bcif-B-CIFlSS-%";
2601    return type2char[type];
2602}
2603
2604void GB_print_debug_information(struct Unfixed_cb_parameter *, GBDATA *gb_main) {
2605    GB_MAIN_TYPE *Main = GB_MAIN(gb_main);
2606    GB_push_transaction(gb_main);
2607    for (int i=0; i<Main->keycnt; i++) {
2608        gb_Key& KEY = Main->keys[i];
2609        if (KEY.key) {
2610            printf("%3i %20s    nref %li\n", i, KEY.key, KEY.nref);
2611        }
2612        else {
2613            printf("    %3i unused key, next free key = %li\n", i, KEY.next_free_key);
2614        }
2615    }
2616    gbm_debug_mem();
2617    GB_pop_transaction(gb_main);
2618}
2619
2620static int GB_info_deep = 15;
2621
2622
2623static int gb_info(GBDATA *gbd, int deep) {
2624    if (!gbd) { printf("NULp\n"); return -1; }
2625    GB_push_transaction(gbd);
2626
2627    GB_TYPES type = gbd->type();
2628
2629    if (deep) {
2630        printf("    ");
2631    }
2632
2633    printf("(GBDATA*)0x%lx (GBCONTAINER*)0x%lx ", (long)gbd, (long)gbd);
2634
2635    if (gbd->rel_father==0) { printf("father=NULp\n"); return -1; }
2636
2637    GBCONTAINER  *gbc;
2638    GB_MAIN_TYPE *Main;
2639    if (type==GB_DB) { gbc = gbd->as_container(); Main = GBCONTAINER_MAIN(gbc); }
2640    else             { gbc = NULp;                Main = GB_MAIN(gbd); }
2641
2642    if (!Main) { printf("Oops - I have no main entry!!!\n"); return -1; }
2643    if (gbd==Main->dummy_father) { printf("dummy_father!\n"); return -1; }
2644
2645    printf("%10s Type '%c'  ", GB_read_key_pntr(gbd), GB_type_2_char(type));
2646
2647    switch (type) {
2648        case GB_DB: {
2649            int size = gbc->d.size;
2650            printf("Size %i nheader %i hmemsize %i", gbc->d.size, gbc->d.nheader, gbc->d.headermemsize);
2651            printf(" father=(GBDATA*)0x%lx\n", (long)GB_FATHER(gbd));
2652            if (size < GB_info_deep) {
2653                int             index;
2654                gb_header_list *header;
2655
2656                header = GB_DATA_LIST_HEADER(gbc->d);
2657                for (index = 0; index < gbc->d.nheader; index++) {
2658                    GBDATA  *gb_sub = GB_HEADER_LIST_GBD(header[index]);
2659                    GBQUARK  quark  = header[index].flags.key_quark;
2660                    printf("\t\t%10s (GBDATA*)0x%lx (GBCONTAINER*)0x%lx\n", quark2key(Main, quark), (long)gb_sub, (long)gb_sub);
2661                }
2662            }
2663            break;
2664        }
2665        default: {
2666            char *data = GB_read_as_string(gbd);
2667            if (data) { printf("%s", data); free(data); }
2668            printf(" father=(GBDATA*)0x%lx\n", (long)GB_FATHER(gbd));
2669        }
2670    }
2671
2672
2673    GB_pop_transaction(gbd);
2674
2675    return 0;
2676}
2677
2678int GB_info(GBDATA *gbd) { // unused - intended to be used in debugger
2679    return gb_info(gbd, 0);
2680}
2681
2682long GB_number_of_subentries(GBDATA *gbd) {
2683    GBCONTAINER    *gbc        = gbd->expect_container();
2684    gb_header_list *header     = GB_DATA_LIST_HEADER(gbc->d);
2685
2686    long subentries = 0;
2687    int  end        = gbc->d.nheader;
2688
2689    for (int index = 0; index<end; index++) {
2690        if (header[index].flags.changed < GB_DELETED) subentries++;
2691    }
2692    return subentries;
2693}
2694
2695// --------------------------------------------------------------------------------
2696
2697#ifdef UNIT_TESTS
2698
2699#include <test_unit.h>
2700#include <locale.h>
2701
2702void TEST_GB_atof() {
2703    // arb depends on locale for floating-point conversion!
2704    // see ../SOURCE_TOOLS/arb_main.h@setlocale
2705    TEST_EXPECT_SIMILAR(GB_atof("0.031"), 0.031, 0.0001); // fails if LC_NUMERIC is set to "de_DE..."
2706}
2707
2708#if !defined(DARWIN)
2709// @@@ TEST_DISABLED_OSX: test fails to compile for OSX on build server
2710// @@@ re-activate test later; see missing libs http://bugs.arb-home.de/changeset/11664#file2
2711void TEST_999_strtod_replacement() {
2712    // caution: if it fails -> locale is not reset (therefore call with low priority 999)
2713    const char *old = setlocale(LC_NUMERIC, "de_DE.UTF-8");
2714    {
2715        // TEST_EXPECT_SIMILAR__BROKEN(strtod("0.031", NULp), 0.031, 0.0001);
2716        TEST_EXPECT_SIMILAR(g_ascii_strtod("0.031", NULp), 0.031, 0.0001);
2717    }
2718    setlocale(LC_NUMERIC, old);
2719}
2720#endif
2721
2722#if defined(ENABLE_CRASH_TESTS)
2723static void test_another_shell() { delete new GB_shell; }
2724#endif
2725static void test_opendb() { GB_close(GB_open("no.arb", "c")); }
2726
2727void TEST_GB_shell() {
2728    {
2729        GB_shell *shell = new GB_shell;
2730        TEST_EXPECT_SEGFAULT(test_another_shell);
2731        test_opendb(); // no SEGV here
2732        delete shell;
2733    }
2734
2735    TEST_EXPECT_SEGFAULT(test_opendb); // should be impossible to open db w/o shell
2736}
2737
2738void TEST_GB_number_of_subentries() {
2739    GB_shell  shell;
2740    GBDATA   *gb_main = GB_open("no.arb", "c");
2741
2742    {
2743        GB_transaction ta(gb_main);
2744
2745        GBDATA   *gb_cont = GB_create_container(gb_main, "container");
2746        TEST_EXPECT_EQUAL(GB_number_of_subentries(gb_cont), 0);
2747
2748        TEST_EXPECT_RESULT__NOERROREXPORTED(GB_create(gb_cont, "entry", GB_STRING));
2749        TEST_EXPECT_EQUAL(GB_number_of_subentries(gb_cont), 1);
2750
2751        {
2752            GBDATA *gb_entry;
2753            TEST_EXPECT_RESULT__NOERROREXPORTED(gb_entry = GB_create(gb_cont, "entry", GB_STRING));
2754            TEST_EXPECT_EQUAL(GB_number_of_subentries(gb_cont), 2);
2755
2756            TEST_EXPECT_NO_ERROR(GB_delete(gb_entry));
2757            TEST_EXPECT_EQUAL(GB_number_of_subentries(gb_cont), 1);
2758        }
2759
2760        TEST_EXPECT_RESULT__NOERROREXPORTED(GB_create(gb_cont, "entry", GB_STRING));
2761        TEST_EXPECT_EQUAL(GB_number_of_subentries(gb_cont), 2);
2762    }
2763
2764    GB_close(gb_main);
2765}
2766
2767
2768void TEST_POSTCOND_arbdb() {
2769    GB_ERROR error             = GB_incur_error(); // clears the error (to make further tests succeed)
2770    bool     unclosed_GB_shell = closed_open_shell_for_unit_tests();
2771
2772    TEST_REJECT(error);             // your test finished with an exported error
2773    TEST_REJECT(unclosed_GB_shell); // your test finished w/o destroying GB_shell
2774}
2775
2776#endif // UNIT_TESTS
2777
2778
Note: See TracBrowser for help on using the repository browser.