Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Commit

Permalink
Kernel: Prevent sign extension in itoa/ltoa
Browse files Browse the repository at this point in the history
  • Loading branch information
byteduck committed Sep 9, 2024
1 parent 0d39647 commit 301d6b6
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions kernel/kstd/kstdlib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,18 +60,31 @@ uint8_t parse_hex_char(char c) {
}

char* itoa(int i, char* p, int base) {
return lltoa(i, p, base);
if (base != 10)
return lltoa((long long) (i & ~0x0u), p, base);
else
return lltoa(i, p, base);
}



extern void serial_putch(char);

char* ltoa(long i, char* p, int base) {
return lltoa(i, p, base);
if (base != 10)
return lltoa((long long) (i & ~0x0ul), p, base);
else
return lltoa(i, p, base);
}

char *lltoa(long long i, char *p, int base) {
char const digit[] = "0123456789";
int nbcount = 0;
bool flag = 0;
int ind;
if (i & 0xfffffff00000000ULL) {
serial_putch('!');
}
switch(base){
case 10: {
bool neg = i < 0;
Expand Down Expand Up @@ -102,7 +115,8 @@ char *lltoa(long long i, char *p, int base) {
uint8_t shift = base == 16 ? 4 : 1;
constexpr auto hexmask = (unsigned long long) 0xF << (sizeof(long long) * 8 - 8);
constexpr auto binmask = (unsigned long long) 0x8 << (sizeof(long long) * 8 - 8);
for(unsigned long long a = (base == 16 ? hexmask : binmask); a > 0; a = a >> shift) {
auto mask = (base == 16 ? hexmask : binmask);
for(unsigned long long a = mask; a > 0; a = a >> shift) {
if (((unsigned long long) i & a) != 0 || flag) {
nbcount++;
flag = true;
Expand Down

0 comments on commit 301d6b6

Please sign in to comment.