Files
mars-tinyldap/bstr_diff2.c
leitner 7586973f9f ubsan triggered for a unit test in mduptab_add because blen was SIZE_MAX
and adding it overflowed the pointer. So add a check for that in
bstr_diff2.
2025-04-17 12:15:20 +00:00

66 lines
1.9 KiB
C

#include <string.h>
#include <libowfat/str.h>
#include <libowfat/uint32.h>
#include "bstr.h"
int bstr_diff2(const char* a,const char* b,size_t blen) {
const char* A,* B;
int j;
/* like str_diff, just for bstrs */
if (*a)
A=a+str_len(a);
else {
A=a+5+uint32_read(a+1);
a+=5;
}
// If adding blen to b would overflow, reduce blen.
// The comparison can never get that far because the end of the
// address space is reserved for the kernel. Make sure to revisit this
// if you want to use this function in kernel space.
uintptr_t c = ~(uintptr_t)b;
if (blen > c) blen = c;
B=b+blen;
for (;;) {
if (a==A) {
if (b==B)
return 0;
else
return -1;
} else
if (b==B)
return 1;
if ((j=((unsigned char)*a-(unsigned char)*b))) break;
++a; ++b;
}
return j;
}
#ifdef UNITTEST
#include <assert.h>
int main() {
assert(bstr_diff2("bar","foo",3) < 0);
assert(bstr_diff2("foo","bar",3) > 0);
assert(bstr_diff2("foo1","foo",3) > 0);
assert(bstr_diff2("foo","foo1",4) < 0);
assert(bstr_diff2("foo","foo",3) == 0);
assert(bstr_diff2("\x00\x03\x00\x00\x00""bar","foo",3) < 0);
assert(bstr_diff2("\x00\x03\x00\x00\x00""foo","bar",3) > 0);
assert(bstr_diff2("\x00\x04\x00\x00\x00""foo1","foo",3) > 0);
assert(bstr_diff2("\x00\x03\x00\x00\x00""foo","foo1",4) < 0);
assert(bstr_diff2("\x00\x03\x00\x00\x00""foo","foo",3) == 0);
assert(bstr_diff2("\x00\x03\x00\x00\x00""bar","foo",3) < 0);
assert(bstr_diff2("\x00\x03\x00\x00\x00""foo","bar",3) > 0);
assert(bstr_diff2("\x00\x04\x00\x00\x00""foo1","foo",3) > 0);
assert(bstr_diff2("\x00\x03\x00\x00\x00""foo","foo1",4) < 0);
assert(bstr_diff2("\x00\x03\x00\x00\x00""foo","foo",3) == 0);
assert(bstr_diff2("\x00\x05\x00\x00\x00""f\x00ord","fnord",5) < 0);
assert(bstr_diff2("\x00\x05\x00\x00\x00""f\x00ord","f\x00ort",5) < 0);
assert(bstr_diff2("\x00\x03\x00\x00\x00""f\xf6o","foo",3) > 0);
}
#endif