bee2-rs 0.2.1

Bindings for cryptographic library Bee2
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
/*
*******************************************************************************
\file mem.c
\brief Memory management
\project bee2 [cryptographic library]
\created 2012.12.18
\version 2025.06.10
\copyright The Bee2 authors
\license Licensed under the Apache License, Version 2.0 (see LICENSE.txt).
*******************************************************************************
*/

#include "bee2/defs.h"

#ifdef OS_WIN
	#include <windows.h>
#else
	#include <memory.h>
	#include <string.h>
	#ifndef OS_APPLE
		#include <malloc.h>
	#else
		#include <stdlib.h>
	#endif
#endif

#include "bee2/core/mem.h"
#include "bee2/core/util.h"
#include "bee2/core/word.h"

/*
*******************************************************************************
Проверка

\todo Реализовать полноценную проверку корректности памяти.
*******************************************************************************
*/

bool_t memIsValid(const void* buf, size_t count)
{
	return count == 0 || buf != 0;
}

bool_t memIsAligned(const void* buf, size_t size)
{
	return (size_t)buf % size == 0;
}

/*
*******************************************************************************
Стандартные функции

\remark Перед вызовом memcpy(), memmove(), memset() проверяется, 
что count != 0: при count == 0 поведение стандартных функций непредсказуемо
(см. https://www.imperialviolet.org/2016/06/26/nonnull.html).

\remark Прямое обращение к функции ядра HeapAlloc() решает проблему 
с освобождением памяти в плагине bee2evp, связывающем bee2 с OpenSSL (1.1.0).
*******************************************************************************
*/

void memCopy(void* dest, const void* src, size_t count)
{
	ASSERT(memIsDisjoint(src, dest, count));
	if (count)
		memcpy(dest, src, count);
}

void memMove(void* dest, const void* src, size_t count)
{
	ASSERT(memIsValid(src, count));
	ASSERT(memIsValid(dest, count));
	if (count)
		memmove(dest, src, count);
}

void memSet(void* buf, octet c, size_t count)
{
	ASSERT(memIsValid(buf, count));
	if (count)
		memset(buf, c, count);
}

void memNeg(void* buf, size_t count)
{
	ASSERT(memIsValid(buf, count));
	for (; count >= O_PER_W; count -= O_PER_W)
	{
		*(word*)buf = ~*(word*)buf;
		buf = (word*)buf + 1;
	}
	while (count--)
	{
		*(octet*)buf = ~*(octet*)buf;
		buf = (octet*)buf + 1;
	}
}

void* memAlloc(size_t count)
{
#ifdef OS_WIN
	return HeapAlloc(GetProcessHeap(), 0, count);
#else
	return malloc(count);
#endif
}

void* memRealloc(void* buf, size_t count)
{
	if (count == 0)
	{
		memFree(buf);
		return 0;
	}
#ifdef OS_WIN
	if (!buf)
		return HeapAlloc(GetProcessHeap(), 0, count);
	return HeapReAlloc(GetProcessHeap(), 0, buf, count);
#else
	return realloc(buf, count);
#endif
}

void memFree(void* buf)
{
#ifdef OS_WIN
	HeapFree(GetProcessHeap(), 0, buf);
#else
	free(buf);
#endif
}

/*
*******************************************************************************
Дополнительные функции

\remark Функция memWipe() повторяет функцию OPENSSL_cleanse()
из библиотеки OpenSSL:
\code
	unsigned char cleanse_ctr = 0;
	void OPENSSL_cleanse(void *ptr, size_t len)
	{
		unsigned char *p = ptr;
		size_t loop = len, ctr = cleanse_ctr;
		while(loop--)
		{
			*(p++) = (unsigned char)ctr;
			ctr += (17 + ((size_t)p & 0xF));
		}
		p=memchr(ptr, (unsigned char)ctr, len);
		if(p)
			ctr += (63 + (size_t)p);
		cleanse_ctr = (unsigned char)ctr;
	}
\endcode

\remark На платформе Windows есть функции SecureZeroMemory()
и RtlSecureZeroMemory(), которые, как и memWipe(), выполняют
гарантированную очистку памяти.
*******************************************************************************
*/

bool_t SAFE(memEq)(const void* buf1, const void* buf2, size_t count)
{
	register word diff = 0;
	ASSERT(memIsValid(buf1, count));
	ASSERT(memIsValid(buf2, count));
	for (; count >= O_PER_W; count -= O_PER_W)
	{
		diff |= *(const word*)buf1 ^ *(const word*)buf2;
		buf1 = (const word*)buf1 + 1;
		buf2 = (const word*)buf2 + 1;
	}
	while (count--)
	{
		diff |= *(const octet*)buf1 ^ *(const octet*)buf2;
		buf1 = (const octet*)buf1 + 1;
		buf2 = (const octet*)buf2 + 1;
	}
	return wordEq(diff, 0);
}

bool_t FAST(memEq)(const void* buf1, const void* buf2, size_t count)
{
	ASSERT(memIsValid(buf1, count));
	ASSERT(memIsValid(buf2, count));
	return memcmp(buf1, buf2, count) == 0;
}

int SAFE(memCmp)(const void* buf1, const void* buf2, size_t count)
{
	register word less = 0;
	register word greater = 0;
	register word w1 = 0;
	register word w2 = 0;
	const octet* b1 = (const octet*)buf1;
	const octet* b2 = (const octet*)buf2;
	size_t filled = 0;
	ASSERT(memIsValid(buf1, count));
	ASSERT(memIsValid(buf2, count));
	for (; count--; ++b1, ++b2)
	{
		w1 = w1 << 8 | *b1;
		w2 = w2 << 8 | *b2;
		if (++filled == O_PER_W)
		{
			less |= ~greater & wordLess(w1, w2);
			greater |= ~less & wordGreater(w1, w2);
			filled = 0;
		}
	}
	if (filled)
	{
		less |= ~greater & wordLess(w1, w2);
		greater |= ~less & wordGreater(w1, w2);
	}
	CLEAN2(w1, w2);
	return (wordEq(less, 0) - 1) | wordNeq(greater, 0);
}

int FAST(memCmp)(const void* buf1, const void* buf2, size_t count)
{
	const octet* b1 = (const octet*)buf1;
	const octet* b2 = (const octet*)buf2;
	ASSERT(memIsValid(buf1, count));
	ASSERT(memIsValid(buf2, count));
	for (; count--; ++b1, ++b2)
		if (*b1 > *b2)
			return 1;
		else if (*b1 < *b2)
			return -1;
	return 0;
}

int SAFE(memCmpRev)(const void* buf1, const void* buf2, size_t count)
{
	register word less = 0;
	register word greater = 0;
	register word w1;
	register word w2;
	ASSERT(memIsValid(buf1, count));
	ASSERT(memIsValid(buf2, count));
	if (count % O_PER_W)
	{
		w1 = w2 = 0;
		while (count % O_PER_W)
		{
			w1 = w1 << 8 | ((const octet*)buf1)[--count];
			w2 = w2 << 8 | ((const octet*)buf2)[count];
		}
		less |= ~greater & wordLess01(w1, w2);
		greater |= ~less & wordGreater01(w1, w2);
	}
	count /= O_PER_W;
	while (count--)
	{
		w1 = ((const word*)buf1)[count];
		w2 = ((const word*)buf2)[count];
#if (OCTET_ORDER == BIG_ENDIAN)
		w1 = wordRev(w1);
		w2 = wordRev(w2);
#endif
		less |= ~greater & wordLess(w1, w2);
		greater |= ~less & wordGreater(w1, w2);
	}
	CLEAN2(w1, w2);
	return (wordEq(less, 0) - 1) | wordNeq(greater, 0);
}

int FAST(memCmpRev)(const void* buf1, const void* buf2, size_t count)
{
	const octet* b1 = (const octet*)buf1 + count;
	const octet* b2 = (const octet*)buf2 + count;
	ASSERT(memIsValid(buf1, count));
	ASSERT(memIsValid(buf2, count));
	while (count--)
		if (*--b1 > *--b2)
			return 1;
		else if (*b1 < *b2)
			return -1;
	return 0;
}

void memWipe(void* buf, size_t count)
{
	static octet wipe_ctr = 0;
	volatile octet* p = (octet*)buf;
	size_t ctr = wipe_ctr;
	size_t i = count;
	ASSERT(memIsValid(buf, count));
	// вычисления, которые должны показаться полезными оптимизатору
	while (i--)
		*(p++) = (octet)ctr, ctr += 17 + ((size_t)p & 15);
	p = memchr(buf, (octet)ctr, count);
	if (p)
		ctr += (63 + (size_t)p);
	wipe_ctr = (octet)ctr;
}

bool_t SAFE(memIsZero)(const void* buf, size_t count)
{
	register word diff = 0;
	ASSERT(memIsValid(buf, count));
	for (; count >= O_PER_W; count -= O_PER_W)
	{
		diff |= *(const word*)buf;
		buf = (const word*)buf + 1;
	}
	while (count--)
	{
		diff |= *(const octet*)buf;
		buf = (const octet*)buf + 1;
	}
	return (bool_t)wordEq(diff, 0);
}

bool_t FAST(memIsZero)(const void* buf, size_t count)
{
	ASSERT(memIsValid(buf, count));
	for (; count >= O_PER_W; count -= O_PER_W, buf = (const word*)buf + 1)
		if (*(const word*)buf)
			return FALSE;
	for (; count--; buf = (const octet*)buf + 1)
		if (*(const octet*)buf)
			return FALSE;
	return TRUE;
}

size_t memNonZeroSize(const void* buf, size_t count)
{
	ASSERT(memIsValid(buf, count));
	while (count--)
		if (*((const octet*)buf + count))
			return count + 1;
	return 0;
}

bool_t SAFE(memIsRep)(const void* buf, size_t count, octet o)
{
	register word diff = 0;
	ASSERT(memIsValid(buf, count));
	for (; count--; buf = (const octet*)buf + 1)
		diff |= *(const octet*)buf ^ o;
	return wordEq(diff, 0);
}

bool_t FAST(memIsRep)(const void* buf, size_t count, octet o)
{
	ASSERT(memIsValid(buf, count));
	for (; count--; buf = (const octet*)buf + 1)
		if (*(const octet*)buf != o)
			return FALSE;
	return TRUE;
}

bool_t memIsDisjoint(const void* buf1, const void* buf2, size_t count)
{
	ASSERT(memIsValid(buf1, count));
	ASSERT(memIsValid(buf2, count));
	return count == 0 || (const octet*)buf1 + count <= (const octet*)buf2 ||
		(const octet*)buf1 >= (const octet*)buf2 + count;
}

bool_t memIsSameOrDisjoint(const void* buf1, const void* buf2, size_t count)
{
	ASSERT(memIsValid(buf1, count));
	ASSERT(memIsValid(buf2, count));
	return buf1 == buf2 || count == 0 ||
		(const octet*)buf1 + count <= (const octet*)buf2 ||
		(const octet*)buf1 >= (const octet*)buf2 + count;
}

bool_t memIsDisjoint2(const void* buf1, size_t count1,
	const void* buf2, size_t count2)
{
	ASSERT(memIsValid(buf1, count1));
	ASSERT(memIsValid(buf2, count2));
	return count1 == 0 || count2 == 0 ||
		(const octet*)buf1 + count1 <= (const octet*)buf2 ||
		(const octet*)buf1 >= (const octet*)buf2 + count2;
}

bool_t memIsDisjoint3(const void* buf1, size_t count1,
	const void* buf2, size_t count2,
	const void* buf3, size_t count3)
{
	return memIsDisjoint2(buf1, count1, buf2, count2) &&
		memIsDisjoint2(buf1, count1, buf3, count3) &&
		memIsDisjoint2(buf2, count2, buf3, count3);
}

bool_t memIsDisjoint4(const void* buf1, size_t count1,
	const void* buf2, size_t count2,
	const void* buf3, size_t count3,
	const void* buf4, size_t count4)
{
	return memIsDisjoint2(buf1, count1, buf2, count2) &&
		memIsDisjoint2(buf1, count1, buf3, count3) &&
		memIsDisjoint2(buf1, count1, buf4, count4) &&
		memIsDisjoint3(buf2, count2, buf3, count3, buf4, count4);
}

void memJoin(void* dest, const void* src1, size_t count1, const void* src2,
	size_t count2)
{
	register octet o;
	size_t i;
	ASSERT(memIsValid(src1, count1));
	ASSERT(memIsValid(src2, count2));
	ASSERT(memIsValid(dest, count1 + count2));
repeat:
	if (memIsDisjoint2(dest, count1, src2, count2))
	{
		memMove(dest, src1, count1);
		memMove((octet*)dest + count1, src2, count2);
	}
	else if (memIsDisjoint2((octet*)dest + count1, count2, src1, count1))
	{
		memMove((octet*)dest + count1, src2, count2);
		memMove(dest, src1, count1);
	}
	else if (memIsDisjoint2(dest, count2, src1, count1))
	{
		// dest <- src2 || src1
		memMove(dest, src2, count2);
		memMove((octet*)dest + count2, src1, count1);
		// dest <- dest <<< count2
		for (i = 0; i < count2; ++i)
		{
			o = ((octet*)dest)[0];
			memMove(dest, (octet*)dest + 1, count1 + count2 - 1);
			((octet*)dest)[count1 + count2 - 1] = o;
		}
	}
	else if (memIsDisjoint2((octet*)dest + count2, count1, src2, count2))
	{
		// dest <- src2 || src1
		memMove((octet*)dest + count2, src1, count1);
		memMove(dest, src2, count2);
		// dest <- dest <<< count2
		for (i = 0; i < count2; ++i)
		{
			o = ((octet*)dest)[0];
			memMove(dest, (octet*)dest + 1, count1 + count2 - 1);
			((octet*)dest)[count1 + count2 - 1] = o;
		}
	}
	else
	{
		// src1 (src2) пересекается и с префиксом, и с суффиксом dest
		// длины count2 (count1) => и первый, и последний октет dest
		// не входят не входят ни в src1, ни в src2
		((octet*)dest)[0] = ((const octet*)src1)[0];
		((octet*)dest)[count1 + count2 - 1] = ((const octet*)src2)[count2 - 1];
		VERIFY(count1--);
		VERIFY(count2--);
		src1 = (const octet*)src1 + 1;
		dest = (octet*)dest + 1;
		goto repeat;
	}
}

void memXor(void* dest, const void* src1, const void* src2, size_t count)
{
	ASSERT(memIsSameOrDisjoint(src1, dest, count));
	ASSERT(memIsSameOrDisjoint(src2, dest, count));
	for (; count >= O_PER_W; count -= O_PER_W)
	{
		*(word*)dest = *(const word*)src1 ^ *(const word*)src2;
		src1 = (const word*)src1 + 1;
		src2 = (const word*)src2 + 1;
		dest = (word*)dest + 1;
	}
	while (count--)
	{
		*(octet*)dest = *(const octet*)src1 ^ *(const octet*)src2;
		src1 = (const octet*)src1 + 1;
		src2 = (const octet*)src2 + 1;
		dest = (octet*)dest + 1;
	}
}

void memXor2(void* dest, const void* src, size_t count)
{
	ASSERT(memIsSameOrDisjoint(src, dest, count));
	for (; count >= O_PER_W; count -= O_PER_W)
	{
		*(word*)dest ^= *(const word*)src;
		src = (const word*)src + 1;
		dest = (word*)dest + 1;
	}
	while (count--)
	{
		*(octet*)dest ^= *(const octet*)src;
		src = (const octet*)src + 1;
		dest = (octet*)dest + 1;
	}
}

void memSwap(void* buf1, void* buf2, size_t count)
{
	ASSERT(memIsDisjoint(buf1, buf2, count));
	for (; count >= O_PER_W; count -= O_PER_W)
	{
		SWAP(*(word*)buf1, *(word*)buf2);
		buf1 = (word*)buf1 + 1;
		buf2 = (word*)buf2 + 1;
	}
	while (count--)
	{
		SWAP(*(octet*)buf1, *(octet*)buf2);
		buf1 = (octet*)buf1 + 1;
		buf2 = (octet*)buf2 + 1;
	}
}

/*
*******************************************************************************
Реверс октетов
*******************************************************************************
*/

void memRev(void* buf, size_t count)
{
	register size_t i = count / 2;
	ASSERT(memIsValid(buf, count));
	while (i--)
	{
		((octet*)buf)[i] ^= ((octet*)buf)[count - 1 - i];
		((octet*)buf)[count - 1 - i] ^= ((octet*)buf)[i];
		((octet*)buf)[i] ^= ((octet*)buf)[count - 1 - i];
	}
}