Skip to content

Commit

Permalink
binout: reinstate checks for truncated values
Browse files Browse the repository at this point in the history
  • Loading branch information
rasky committed Nov 15, 2024
1 parent b804c93 commit c9c142a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
6 changes: 3 additions & 3 deletions tools/common/binout.c
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,18 @@ struct {
struct placeholder_data value;
} *placeholder_hash = NULL;

void w8(FILE *f, uint8_t v)
void _w8(FILE *f, uint8_t v)
{
fputc(v, f);
}

void w16(FILE *f, uint16_t v)
void _w16(FILE *f, uint16_t v)
{
w8(f, v >> 8);
w8(f, v & 0xff);
}

void w32(FILE *f, uint32_t v)
void _w32(FILE *f, uint32_t v)
{
w16(f, v >> 16);
w16(f, v & 0xffff);
Expand Down
23 changes: 19 additions & 4 deletions tools/common/binout.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@

#define BITCAST_F2I(f) ({ uint32_t __i; float __f = (f); memcpy(&__i, &(__f), 4); __i; })

#define _wconv(type, v) ({ \
typeof(v) _v = (v); \
if (sizeof(type) < sizeof(_v)) { \
int64_t ext = (int64_t)_v >> (sizeof(type) * 8); \
if (ext != 0 && ext != (uint64_t)-1) { \
fprintf(stderr, "fatal: truncating value %lld to %s (ext=%lld)\n", (long long)_v, #type, ext); \
assert(ext == 0 || ext == (uint64_t)-1); \
} \
} \
(type)_v; \
})

#ifdef __cplusplus
extern "C" {
#endif
Expand All @@ -24,10 +36,13 @@ void placeholder_setv_offset(FILE *file, int offset, const char *format, va_list
void placeholder_set_offset(FILE *file, int offset, const char *format, ...);
void placeholder_clear();

void w8(FILE *f, uint8_t v);
void w16(FILE *f, uint16_t v);
void w32(FILE *f, uint32_t v);
#define wf32(f, v) w32(f, BITCAST_F2I(v))
void _w8(FILE *f, uint8_t v);
void _w16(FILE *f, uint16_t v);
void _w32(FILE *f, uint32_t v);
#define w8(f, v) _w8(f, _wconv(uint8_t, v))
#define w16(f, v) _w16(f, _wconv(uint16_t, v))
#define w32(f, v) _w32(f, _wconv(uint32_t, v))
#define wf32(f, v) _w32(f, BITCAST_F2I(v))
#define wf32approx(f, v, prec) wf32(f, roundf((v)/(prec))*(prec))

int w32_placeholder(FILE *f);
Expand Down

0 comments on commit c9c142a

Please sign in to comment.