-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.h
553 lines (454 loc) · 14.6 KB
/
stack.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
#ifndef CUSTOM_STACK_IMPL
#define CUSTOM_STACK_IMPL
/**
* @file stack.h
* @author MeerkatBoss
* @brief Stack data structure
* @version 0.1
* @date 2022-09-25
*
* @copyright Copyright (c) 2022
* TODO: ^ usually here goes name :)
*
* @note For usage with any desired type define
* `element_t` type, `element_poison` constant,
* `int IsPoison(element_t element)` function, and
* `ELEMENT_SPEC` with `ELEMENT_ARGS(element)` macros.
*
* @warning This header DOES NOT support separate compilation
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "_stack_interface.h"
#include "logger.h"
/**
* @brief
* Recalculate hash values in stack
* @param[inout] stack `Stack` instance
*/
void StackRecalculateHash_ (Stack* stack);
/**
* @brief
* Calculate stack hash value
*
* @param[in] stack `Stack` instance
* @return Hash value
*/
hash_t GetStackHash_ (const Stack* stack);
/**
* @brief
* Check stack integrity
*
* @param[in] stack `Stack` instance
* @param[in] func calling fuction name
* @param[in] file calling file name
* @param[in] line calling line number
* @return zero upon success, some combination of
* `ErrorFlags` otherwise
*/
unsigned int StackCheck_ (const Stack* stack);
/**
* @brief
* Check stack buffer integrity
*
* @param[in] stack `Stack` instance
* @return zero upon success, some combination of
* `ErrorFlags` otherwise
*/
unsigned int StackDataCheck_ (const Stack* stack);
#define TRY_ASSIGN_PTR(ptr, value) if (ptr) {*(ptr) = value;}
inline enum ErrorFlags GetErrorFlag(int condition, enum ErrorFlags flag)
{
return (condition) ? flag : STK_NO_ERROR;
}
/**
* @brief
* Stack capacity growth coefficient
*/
const double stack_growth_ = 2;
/**
* @brief
* Stack default capacity
*/
const size_t default_cap_ = 16;
/**
* @brief
* Grow stack if needed so that it will be ready
* to accept new element
* @param[inout] stack `Stack` instance
* @return zero upon success, non-zero otherwise
*/
int StackTryGrow_ (Stack* stack);
/**
* @brief
* Ensure stack has no eccess capacity
* @param[inout] stack `Stack` instance
* @return zero upon success, non-zero otherwise
*/
int StackTryShrink_ (Stack* stack);
/**
* @brief
* (Re)allocate array with size `new_size`,
* add canaries before array start and after
* its end.
* @param[inout] old_array pointer to beginning of an
* array, returned by call to `ReallocWithCanary_` or
* `NULL`
* @param[in] old_size length of old array. This parameter
* is ignored if `old_array` is `NULL`
* @param[in] new_size required new length of array
* @return pointer to beginning of allocated array
* or `NULL` upon failure
*
* @warning If `old_array` is not `NULL` and it
* was not returned by previous call to `ReallocWithCanary_`,
* the result is undefined
*
* @warning If new_size is 0 the result is undefined
*/
element_t* ReallocWithCanary_ (element_t* old_array,
size_t old_size,
size_t new_size);
/**
* @brief
* Free memory allocated by `ReallocWithCanary_`
* @param[inout] ptr Memory to be freed
*/
void FreeWithCanary_ (element_t* ptr);
int StackCtor_(Stack* stack,
const char* name,
const char* func_name,
const char* file_name,
size_t line_num)
{
element_t* data = ReallocWithCanary_(NULL, 0, default_cap_);
if (!data)
return -1; // TODO: What about an enum for errors?)
_ON_CANARY(
canary_t canary = CANARY ^ (canary_t)stack;
)
*stack = {
_ON_CANARY( .canary_start_ = canary,)
.data = data,
.size = 0,
.capacity = default_cap_,
_ON_HASH( .hash_ = 0,)
_ON_HASH( .data_hash_ = 0,)
_ON_DEBUG_INFO(
.debug_ = {
.name = name,
.func_name = func_name,
.file_name = file_name,
.line_num = line_num
},
)
_ON_CANARY( .canary_end_ = canary,)
};
StackRecalculateHash_(stack);
log_message(MSG_TRACE, "Constructed stack at %p", stack);
return 0;
}
void StackDtor(Stack* stack)
{
if (StackAssert(stack) != STK_NO_ERROR)
return;
FreeWithCanary_(stack->data);
*stack = {};
log_message(MSG_TRACE, "Destroyed stack at %p", stack);
}
unsigned int StackPush(Stack* stack, element_t value)
{
unsigned int err = StackAssert(stack);
if (err) return err;
int push_status = StackTryGrow_(stack);
if (push_status < 0)
{
log_message(MSG_WARNING, "Failed to push to stack %p. Not enough memory", stack);
return STK_NO_MEMORY;
}
stack->data[stack->size++] = value;
StackRecalculateHash_(stack);
return STK_NO_ERROR;
}
unsigned int StackPop (Stack* stack)
{
unsigned int err = StackAssert(stack);
if (err) return err;
if (stack->size == 0)
{
log_message(MSG_WARNING, "Attempt to pop empty stack %p spotted.", stack);
return STK_EMPTY;
}
stack->data[--stack->size] = element_poison;
StackTryShrink_(stack);
StackRecalculateHash_(stack);
return STK_NO_ERROR;
}
element_t StackPopCopy (Stack* stack, unsigned int* err = NULL)
{
unsigned int err_flags = StackAssert(stack);
if (err_flags)
{
TRY_ASSIGN_PTR(err, err_flags);
return element_poison;
}
if (stack->size == 0)
{
TRY_ASSIGN_PTR(err, STK_EMPTY);
return element_poison;
}
element_t result = stack->data[stack->size - 1];
stack->data[--stack->size] = element_poison;
StackTryShrink_(stack);
_ON_HASH(
stack->hash_ = 0;
stack->data_hash_ = GetHash(stack->data, stack->capacity);
stack->hash_ = GetHash(stack, sizeof(*stack));
)
TRY_ASSIGN_PTR(err, STK_NO_ERROR);
return result;
}
element_t* StackPeek (const Stack* stack, unsigned int* err = NULL)
{
unsigned int err_flags = StackAssert(stack);
if (err_flags)
{
TRY_ASSIGN_PTR(err, err_flags);
return NULL;
}
TRY_ASSIGN_PTR(err, err_flags);
return stack->data + stack->size - 1;
}
unsigned int StackCheck_(const Stack* stack)
{
if (!CanReadPointer(stack))
return STK_BAD_PTR;
unsigned int flags = STK_NO_ERROR;
_ON_HASH(
flags |= GetErrorFlag(GetStackHash_(stack) != stack->hash_, STK_WRONG_HASH);
)
_ON_CANARY(
canary_t canary = CANARY ^ (canary_t)stack;
flags |= GetErrorFlag(stack->canary_start_ != canary, STK_DEAD_CANARY);
flags |= GetErrorFlag(stack->canary_end_ != canary, STK_DEAD_CANARY);
)
flags |= GetErrorFlag((long long)stack->size < 0, STK_CORRUPTED_SIZE);
flags |= GetErrorFlag(stack->size > stack->capacity, STK_CORRUPTED_SIZE);
flags |= GetErrorFlag((long long)stack->capacity < 0, STK_CORRUPTED_CAP);
if (flags & (STK_CORRUPTED_SIZE | STK_CORRUPTED_SIZE))
return flags;
flags |= StackDataCheck_(stack);
return flags;
}
unsigned int StackDataCheck_(const Stack* stack)
{
unsigned int flags = STK_NO_ERROR;
if (!CanReadPointer(stack->data))
return flags | STK_BAD_DATA_PTR;
_ON_HASH(
flags |= GetErrorFlag(
stack->data_hash_ != GetHash(stack->data, stack->capacity),
STK_WRONG_DATA_HASH);
)
_ON_CANARY(
canary_t* start = ((canary_t*) stack->data)- 1;
canary_t* end = (canary_t*)(stack->data + stack->capacity);
if (!CanReadPointer(start) || !CanReadPointer(end))
return flags | STK_BAD_DATA_PTR;
flags |= GetErrorFlag(CANARY != *start || CANARY != *end, STK_CORRUPTED_DATA);
)
// TODO: Extractable
for (size_t i = 0; i < stack->size; i++)
if (!CanReadPointer(stack->data + i) || IsPoison(stack->data[i]))
return flags | STK_CORRUPTED_DATA;
for (size_t i = stack->size; i < stack->capacity; i++)
if (!CanReadPointer(stack->data + i) || !IsPoison(stack->data[i]))
return flags | STK_CORRUPTED_DATA;
return flags;
}
unsigned int StackAssert_(const Stack* stack,
const char* func,
const char* file,
size_t line,
int force = 0)
{
unsigned int errs = 0;
_ON_STACK_CHECK(
errs = StackCheck_(stack);
)
if (!errs && !force)
return STK_NO_ERROR;
message_level level = errs ? MSG_ERROR : MSG_TRACE;
log_message(level, "Dumping stack[%p] (status: %s)",
stack,
errs ? "CORRUPTED" : "ok");
log_message(level, "\tin %s:%zu in file \'%s\'", func, line, file);
_ON_DEBUG_INFO(
log_message(level, "Stack \'%s\' declared in %s on line %zu, file \'%s\'",
stack->debug_.name,
stack->debug_.func_name,
stack->debug_.line_num,
stack->debug_.file_name);
)
if (errs)
log_message(level, "Error flags: %o\n", errs);
_ON_HASH(
log_message(level, "Hash:");
log_message(level, "\tstored: %#llx" ,stack->hash_);
log_message(level, "\tactual: %#llx\n", GetStackHash_(stack));
)
// TODO: Extractable!
_ON_CANARY(
log_message(level, "Canary state:");
log_message(level, "\tstart: %#016llx ^ %#016llx",
CANARY, stack->canary_start_ ^ CANARY);
log_message(level, "\tend : %#016llx ^ %#016llx",
CANARY, stack->canary_end_ ^ CANARY);
)
// TODO: Extractable!
log_message(level, "Elements stored: %zu",
stack->size);
log_message(level, "Total capacity : %zu\n",
stack->capacity);
_ON_HASH(
log_message(level, "Data hash:");
log_message(level, "\tstored: %#llx",
stack->data_hash_);
log_message(level, "\tactual: %#llx",
GetHash(stack->data, stack->capacity));
)
// TODO: Extractable!
log_message(level, "Data[%p]:", stack->data);
if (errs & STK_BAD_DATA_PTR) // TODO: Mix of conditinally and uncoditionally compilated, can you reduce?
{
log_message(level, "\tNOT READABLE");
return errs;
}
_ON_CANARY(
canary_t* start = ((canary_t*) stack->data)- 1;
if (CanReadPointer(start))
log_message(level, "\tcanary: %#016llx", *start);
else
log_message(level, "\tcanary: NOT READABLE");
)
for (size_t i = 0; i < stack->capacity; i++)
{
if (!CanReadPointer(stack->data + i) || IsPoison(stack->data[i]))
log_message(level, "\t%c[%zu]: %s",
i < stack->size ? '*' : ' ',
i,
CanReadPointer(stack->data + i)
? "POISON"
: "NOT READABLE");
else
log_message(level, "\t%c[%zu]: " ELEMENT_SPEC,
i < stack->size ? '*' : ' ',
i,
ELEMENT_ARGS(stack->data[i]));
}
_ON_CANARY(
canary_t* end = (canary_t*)(stack->data + stack->capacity);
if (CanReadPointer(end))
log_message(level, "\tcanary: %#016llx", *end);
else
log_message(level, "\tcanary: NOT READABLE");
)
return errs;
}
element_t* ReallocWithCanary_(element_t* old_array,
size_t old_size,
size_t new_size)
{
_ON_CANARY(
if (old_array == NULL) old_size = 0;
/* Allocate result */
void* allocated = realloc(
/* Calculate real array start*/
old_array
? (canary_t*)old_array - 1 /* get real beginning */
: NULL, /* allocate new array */
/* Ensure there is enough space for canaries */
new_size*sizeof(element_t) + 2*sizeof(canary_t));
if (allocated == NULL) // TODO: Check why? perror?
return NULL;
element_t* result = (element_t*)((canary_t*)allocated + 1);
/* Fill new elements (if any) with poison*/
for (size_t i = old_size; i < new_size; i++) // TODO: Trying to beat memset, huh?)
result[i] = element_poison;
/* Set canaries before and after array*/
((canary_t*) result)[-1] = CANARY;
*(canary_t*)(result + new_size) = CANARY;
return result;
)
_NO_CANARY(
return (element_t*)realloc(old_array, new_size * sizeof(element_t));
)
}
void FreeWithCanary_(element_t* ptr)
{
_ON_CANARY(
free((canary_t*)ptr - 1);
return;
)
free(ptr);
}
inline size_t GetNewCapacity_(size_t size)
{
return (size_t)round((double)size * stack_growth_);
}
inline size_t GetCapacityLimit_(size_t size)
{
return (size_t)round((double)size * stack_growth_*stack_growth_);
}
int StackTryGrow_(Stack* stack)
{
if (stack->size < stack->capacity)
return 0;
size_t new_capacity = GetNewCapacity_(stack->size);
element_t* new_data = ReallocWithCanary_(stack->data,
stack->capacity,
new_capacity);
if (!new_data)
return -1; /* There is no bool in C*/
stack->data = new_data;
stack->capacity = new_capacity;
return 0;
}
int StackTryShrink_(Stack* stack)
{
size_t capacity_limit = GetCapacityLimit_(stack->size);
if (capacity_limit <= default_cap_ || stack->capacity < capacity_limit)
return 0;
size_t new_capacity = GetNewCapacity_(stack->size);
if (new_capacity <= default_cap_)
new_capacity = default_cap_;
element_t* new_data = ReallocWithCanary_(
stack->data,
stack->capacity,
new_capacity);
if (!new_data)
return -1; /* Still no bools in C */
stack->data = new_data;
stack->capacity = new_capacity;
return 0;
}
void StackRecalculateHash_(Stack* stack)
{
_ON_HASH(
stack->data_hash_ = GetHash(stack->data, stack->capacity);
stack->hash_ = GetStackHash_(stack);
)
}
hash_t GetStackHash_(const Stack* stack)
{
_ON_HASH(
hash_t old_hash = stack->hash_;
const_cast<Stack*>(stack)->hash_ = 0;
hash_t new_hash = GetHash(stack, sizeof(*stack));
const_cast<Stack*>(stack)->hash_ = old_hash;
return new_hash;
)
return 0;
}
#endif