c-for-go icon indicating copy to clipboard operation
c-for-go copied to clipboard

Go Integer overflows translated from large C enum numbers

Open hxy9243 opened this issue 2 years ago • 5 comments

In C, some legit enum definitions can generate problematic generations in Go. For example:

typedef enum
{
    STATUS_INIT = 0,
    STATUS_STARTED = 1,
    STATUS_RUNNING = 2,
    ...
    STATUS_FAILED = 0xFFFFFFFF,
} example_status_t;

The STATUS_FAILED can be translated to unsigned integer in Go, which for a int32, STATUS_FAILED should really be a -1.

The generated code with configuration TRANSLATOR.ConstRules.enum: eval.

// Status_t as declared in large-const/large-const.h:17
type Status_t int32

// Status_t enumeration from large-const/large-const.h:17
const (
        ...
	STATUS_FAILED   Status_t = 4294967295
)

With the rule expand, it'll generate a similar problem:

	STATUS_FAILED   Status_t = C.STATUS_FAILED

which throws Go compile error: cannot use (_Ciconst_STATUS_FAILED) (untyped int constant 4294967295) as Status_t value in constant declaration (overflows).

A viable solution might be:

  • Generate uint32 for C enums.
  • Eval the C evals as signed integers and interpreter them with signs.

This can happen in many libraries that uses large constant numbers like 0x10000000 or 0xFFFF0000.

hxy9243 avatar Oct 30 '22 04:10 hxy9243