infix
A JIT-Powered FFI Library for C
Loading...
Searching...
No Matches
fuzz_regression_helpers.h
Go to the documentation of this file.
1#pragma once
33#include <stddef.h>
34#include <stdlib.h>
35#include <string.h>
36
47static unsigned char * b64_decode(const char * data, size_t * out_len) {
48 // A standard lookup table for Base64 decoding. -1 represents an invalid character.
49 static const int b64_decode_table[] = {
50 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
51 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55,
52 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
53 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32,
54 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1};
55
56 size_t in_len = strlen(data);
57 if (in_len % 4 != 0)
58 return NULL; // Base64 strings must have a length that is a multiple of 4.
59
60 // Calculate the output length, accounting for padding characters.
61 *out_len = in_len / 4 * 3;
62 if (data[in_len - 1] == '=')
63 (*out_len)--;
64 if (data[in_len - 2] == '=')
65 (*out_len)--;
66
67 unsigned char * out = (unsigned char *)malloc(*out_len);
68 if (out == NULL)
69 return NULL;
70
71 // Process the input string in 4-character chunks.
72 for (size_t i = 0, j = 0; i < in_len;) {
73 int sextet_a = b64_decode_table[(unsigned char)data[i++]];
74 int sextet_b = b64_decode_table[(unsigned char)data[i++]];
75 int sextet_c = b64_decode_table[(unsigned char)data[i++]];
76 int sextet_d = b64_decode_table[(unsigned char)data[i++]];
77
78 // Validate the characters and handle padding.
79 if (sextet_a == -1 || sextet_b == -1 || (data[i - 2] != '=' && sextet_c == -1) ||
80 (data[i - 1] != '=' && sextet_d == -1)) {
81 free(out);
82 return NULL;
83 }
84
85 // Combine the four 6-bit sextets into a 24-bit triple.
86 unsigned int triple = (sextet_a << 3 * 6) + (sextet_b << 2 * 6) + (sextet_c << 1 * 6) + (sextet_d << 0 * 6);
87
88 // Extract the three 8-bit bytes from the triple.
89 if (j < *out_len)
90 out[j++] = (triple >> 2 * 8) & 0xFF;
91 if (j < *out_len)
92 out[j++] = (triple >> 1 * 8) & 0xFF;
93 if (j < *out_len)
94 out[j++] = (triple >> 0 * 8) & 0xFF;
95 }
96
97 return out;
98}
static unsigned char * b64_decode(const char *data, size_t *out_len)
Definition fuzz_regression_helpers.h:47