gotranspile / cxgo

Tool for transpiling C to Go.
https://gotranspile.dev
MIT License
328 stars 22 forks source link

Return Statement Reachability #60

Open redbow-kimee opened 1 year ago

redbow-kimee commented 1 year ago

Possibly related to #10

Go enforces a syntactic reachability analysis for returns, while C never required that returns be reachable and C compilers which do reachability use more sophisticated algorighms. Some situations where the return statement is considered reachable (or at least not an issue) by C are not considered reachable by Go.

It appears that cxgo has implemented a bit of checking to implicitly add missing returns (see postproc.go:fixImplicitReturnStmts). However, I've found a test case which is improperly handled.

#include <stdio.h>

#define TRUE 1
#define FALSE 0

int implicit_return(char* str)
{
    while(TRUE)
    {
        while(TRUE)
        {
            if(*str == '\0') { return 0; }
            else if(*str != 'a') { break; }
            str++;
        }

        printf("%c is not a\n", *str);
        str++;
    }
}

int main()
{
    return implicit_return("aaabaababaaaaa");
}

I believe the last line of this function should have an (actually unreachable) return 0 added to fool Go into believing there is a reachable return 0.

DISTRIBUTION STATEMENT “A”. (Approved for public release. Distribution is unlimited.)

This material is based upon work supported by DARPA under Contract No. HR001122C0047. Any opinions, findings and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of DARPA. DISTRIBUTION STATEMENT “A”. (Approved for public release. Distribution is unlimited.)

dennwc commented 1 year ago

Thank you for providing a reproducer, I will check why reachability analysis fails for this case.