aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


client/runtime/guest_format.c (11833B)


      1 #include "guest_format.h"
      2 #include <limits.h>
      3 #include <stdarg.h>
      4 
      5 struct output_buffer {
      6     char *bytes;
      7     size_t length;
      8 };
      9 
     10 static void append(struct output_buffer *output, const char *bytes, size_t length)
     11 {
     12     if (length > INT_MAX - output->length) abort();
     13     char *grown = realloc(output->bytes, output->length + length + 1);
     14     if (!grown) abort();
     15     output->bytes = grown;
     16     memcpy(output->bytes + output->length, bytes, length);
     17     output->length += length;
     18 }
     19 
     20 /* Host varargs contain real typed values, never the guest's 32-bit va_list. */
     21 static void append_value(struct output_buffer *output, const char *format, ...)
     22 {
     23     va_list arguments, copy;
     24     va_start(arguments, format);
     25     va_copy(copy, arguments);
     26     int length = vsnprintf(NULL, 0, format, copy);
     27     va_end(copy);
     28     if (length < 0) abort();
     29     char *text = malloc((size_t)length + 1);
     30     if (!text) abort();
     31     vsnprintf(text, (size_t)length + 1, format, arguments);
     32     va_end(arguments);
     33     append(output, text, length);
     34     free(text);
     35 }
     36 
     37 static void unsupported(const char *format)
     38 {
     39     fprintf(stderr, "Unsupported guest printf conversion: %s\n", format);
     40     abort();
     41 }
     42 
     43 static int field_width(const char **cursor, uint32_t *arguments)
     44 {
     45     if (**cursor == '*') {
     46         ++*cursor;
     47         int value = (int32_t)MEM32(*arguments);
     48         *arguments += 4;
     49         if (value == INT_MIN) unsupported(*cursor);
     50         return value;
     51     }
     52     char *end;
     53     long value = strtol(*cursor, &end, 10);
     54     if (value < 0 || value > INT_MAX) unsupported(*cursor);
     55     *cursor = end;
     56     return (int)value;
     57 }
     58 
     59 static void format_output(struct output_buffer *output, const char *format, uint32_t arguments)
     60 {
     61     char *native = malloc(strlen(format) + 16);
     62     if (!native) abort();
     63     while (*format) {
     64         const char *start = format;
     65         while (*format && *format != '%') ++format;
     66         append(output, start, format - start);
     67         if (!*format) break;
     68         start = format++;
     69         if (*format == '%') {
     70             append(output, format++, 1);
     71             continue;
     72         }
     73 
     74         /* Preserve flags; normalize both field arguments for typed host calls. */
     75         char *end = native;
     76         *end++ = '%';
     77         while (*format && strchr("-+ #0", *format)) *end++ = *format++;
     78         int width = field_width(&format, &arguments), precision = -1;
     79         if (*format == '.') {
     80             ++format;
     81             precision = field_width(&format, &arguments);
     82         }
     83         *end++ = '*';
     84         *end++ = '.';
     85         *end++ = '*';
     86 
     87         /* Windows long and pointers are 32 bits; I64/ll consume two stack words. */
     88         int bits = 32, wide = 0;
     89         if (*format == 'h') {
     90             bits = 16;
     91             /* Legacy MSVCRT treats repeated h as short, not C99 signed char. */
     92             if (*++format == 'h') ++format;
     93         } else if (*format == 'l') {
     94             wide = 1;
     95             if (*++format == 'l') { bits = 64; ++format; }
     96         } else if (!strncmp(format, "I64", 3)) { bits = 64; format += 3; }
     97         else if (!strncmp(format, "I32", 3)) format += 3;
     98         else if (*format == 'I') ++format;
     99         char type = *format;
    100         if (!type) unsupported(start);
    101         ++format;
    102         if (strchr("diuoxX", type)) {
    103             uint64_t value = MEM32(arguments);
    104             arguments += 4;
    105             if (bits == 64) {
    106                 value |= (uint64_t)MEM32(arguments) << 32;
    107                 arguments += 4;
    108             }
    109             *end++ = 'l';
    110             *end++ = 'l';
    111             *end++ = type;
    112             *end = 0;
    113             if (type == 'd' || type == 'i') {
    114                 int64_t signed_value = bits == 16 ? (int16_t)value :
    115                                        bits == 32 ? (int32_t)value : (int64_t)value;
    116                 append_value(output, native, width, precision, (long long)signed_value);
    117             } else {
    118                 if (bits == 16) value = (uint16_t)value;
    119                 append_value(output, native, width, precision, (unsigned long long)value);
    120             }
    121         } else if (type == 'f' && bits == 32) {
    122             double value = MEMD(arguments);
    123             arguments += 8;
    124             if (!isfinite(value)) unsupported(start);
    125             *end++ = type;
    126             *end = 0;
    127             append_value(output, native, width, precision, value);
    128 
    129             /* MSVCRT rounds halfway away from zero; libc rounds to even. A
    130              * decimal halfway value has an odd significand times 2^(-digits-1).
    131              * Multiplication by 5^digits leaves its low two bits unchanged. */
    132             uint64_t bits;
    133             memcpy(&bits, &value, sizeof(bits));
    134             int exponent = (bits >> 52) & 0x7ff;
    135             uint64_t significand = bits & 0xfffffffffffffull;
    136             if (exponent) significand |= 0x10000000000000ull;
    137             exponent = exponent ? exponent - 1075 : -1074;
    138             if (significand) {
    139                 while (!(significand & 1)) { significand >>= 1; ++exponent; }
    140                 if ((int64_t)exponent + (precision < 0 ? 6 : precision) == -1 && (significand & 3) == 1) {
    141                     size_t digit = output->length;
    142                     while (output->bytes[digit - 1] < '0' || output->bytes[digit - 1] > '9') --digit;
    143                     ++output->bytes[digit - 1]; /* The rounded-down final digit is even, so no carry. */
    144                 }
    145             }
    146         } else if (type == 'g' && bits == 32) {
    147             double value = MEMD(arguments);
    148             arguments += 8;
    149             if (!isfinite(value) || precision > 17) unsupported(start);
    150             int digits = precision < 0 ? 6 : precision ? precision : 1;
    151             char scientific[64];
    152             snprintf(scientific, sizeof(scientific), "%.17e", value);
    153             int decimal_exponent = atoi(strchr(scientific, 'e') + 1);
    154             int64_t places = (int64_t)digits - 1 - decimal_exponent;
    155             int round_away = 0;
    156 
    157             /* Detect exact halfway cases where MSVCRT rounds away from zero. */
    158             uint64_t representation;
    159             memcpy(&representation, &value, sizeof(value));
    160             int exponent = (representation >> 52) & 0x7ff;
    161             uint64_t significand = representation & 0xfffffffffffffull;
    162             if (exponent) significand |= 0x10000000000000ull;
    163             exponent = exponent ? exponent - 1075 : -1074;
    164             if (significand) {
    165                 while (!(significand & 1)) { significand >>= 1; ++exponent; }
    166                 int64_t remaining = places;
    167                 while (remaining < 0 && !(significand % 5)) { significand /= 5; ++remaining; }
    168                 round_away = remaining >= 0 && exponent + places == -1 && (significand & 3) == 1;
    169             }
    170 
    171             *end++ = 'g';
    172             *end = 0;
    173             struct output_buffer number = {NULL, 0};
    174             append_value(&number, native, 0, precision, value);
    175             number.bytes[number.length] = 0;
    176             char *power = strchr(number.bytes, 'e');
    177             if (round_away) {
    178                 /* Scientific %g can omit trailing zeroes that must become nonzero. */
    179                 if (places < 0) {
    180                     unsigned present = 0;
    181                     int point = 0;
    182                     for (char *p = number.bytes; p < power; ++p) {
    183                         present += *p >= '0' && *p <= '9';
    184                         point |= *p == '.';
    185                     }
    186                     if (present < (unsigned)digits) {
    187                         size_t offset = power - number.bytes, old_length = number.length;
    188                         size_t missing = digits - present, added = missing + !point;
    189                         for (size_t i = 0; i < added; ++i) append(&number, "0", 1);
    190                         memmove(number.bytes + offset + added, number.bytes + offset, old_length - offset);
    191                         power = number.bytes + offset + added;
    192                         if (!point) number.bytes[offset++] = '.';
    193                         memset(number.bytes + offset, '0', missing);
    194                     }
    195                 }
    196                 char *last = power ? power : number.bytes + number.length;
    197                 ++last[-1]; /* The rounded-down digit is even, so there is no carry. */
    198                 number.bytes[number.length] = 0;
    199             }
    200             if (power && strlen(power + 2) == 2) {
    201                 /* Legacy MSVCRT uses at least three exponent digits. */
    202                 size_t offset = power - number.bytes + 2;
    203                 append(&number, "", 1);
    204                 memmove(number.bytes + offset + 1, number.bytes + offset, number.length - offset - 1);
    205                 number.bytes[offset] = '0';
    206             }
    207 
    208             int left = width < 0 || strchr(native, '-') != NULL;
    209             size_t field = width < 0 ? -(int64_t)width : width;
    210             size_t padding = field > number.length ? field - number.length : 0;
    211             int zero = !left && strchr(native, '0') != NULL;
    212             size_t sign = zero && (number.bytes[0] == '+' || number.bytes[0] == '-' || number.bytes[0] == ' ');
    213             if (sign) append(output, number.bytes, 1);
    214             if (!left) for (size_t i = 0; i < padding; ++i) append(output, zero ? "0" : " ", 1);
    215             append(output, number.bytes + sign, number.length - sign);
    216             if (left) for (size_t i = 0; i < padding; ++i) append(output, " ", 1);
    217             free(number.bytes);
    218         } else if ((type == 's' || type == 'c') && !wide && bits != 64) {
    219             uint32_t value = MEM32(arguments);
    220             arguments += 4;
    221             *end++ = type;
    222             *end = 0;
    223             if (type == 's') append_value(output, native, width, precision,
    224                                          value ? (const char *)ADDR(value) : "(null)");
    225             else append_value(output, native, width, precision, (int)(unsigned char)value);
    226         } else if (type == 'p') {
    227             /* MSVCRT prints eight uppercase digits and ignores explicit precision. */
    228             *end++ = 'X';
    229             *end = 0;
    230             append_value(output, native, width, 8, (unsigned int)MEM32(arguments));
    231             arguments += 4;
    232         } else unsupported(start);
    233     }
    234     free(native);
    235 }
    236 
    237 char *guest_format_string(uint32_t format, uint32_t arguments, uint32_t *length)
    238 {
    239     struct output_buffer output = {malloc(1), 0};
    240     if (!output.bytes) abort();
    241     format_output(&output, (const char *)ADDR(format), arguments);
    242     output.bytes[output.length] = 0;
    243     *length = output.length;
    244     return output.bytes;
    245 }
    246 
    247 static void buffer_format(int bounded, int list)
    248 {
    249     uint32_t destination = MEM32(g_esp + 4);
    250     uint32_t capacity = bounded ? MEM32(g_esp + 8) : UINT32_MAX;
    251     uint32_t format_slot = g_esp + (bounded ? 12 : 8);
    252     uint32_t arguments = list ? MEM32(format_slot + 4) : format_slot + 4;
    253     uint32_t length;
    254     char *output = guest_format_string(MEM32(format_slot), arguments, &length);
    255     uint32_t copied = length < capacity ? length : capacity;
    256     if (copied) memcpy((void *)ADDR(destination), output, copied);
    257     free(output);
    258 
    259     /* Legacy _snprintf writes no terminator when the result fills the buffer. */
    260     if (length < capacity) MEM8(destination + length) = 0;
    261     g_eax = destination && length > capacity ? UINT32_MAX : length;
    262     g_esp += 4;
    263 }
    264 
    265 static void format_sprintf(void) { buffer_format(0, 0); }
    266 static void format_vsprintf(void) { buffer_format(0, 1); }
    267 static void format_snprintf(void) { buffer_format(1, 0); }
    268 static void format_vsnprintf(void) { buffer_format(1, 1); }
    269 
    270 recomp_func_t guest_format_lookup(const char *name)
    271 {
    272     if (!strcmp(name, "sprintf")) return format_sprintf;
    273     if (!strcmp(name, "vsprintf")) return format_vsprintf;
    274     if (!strcmp(name, "_snprintf")) return format_snprintf;
    275     if (!strcmp(name, "_vsnprintf")) return format_vsnprintf;
    276     return NULL;
    277 }