From dd1fc4ed87882b35b9e17ecda6c8d168ccaf13f1 Mon Sep 17 00:00:00 2001 From: lu4p Date: Sat, 13 Jun 2020 00:44:57 +0200 Subject: [PATCH] don't replace all consts with vars In some cases, such as iotas or when constants are later required to be constants, we could break compilation. Be more conservative. Fixes #32. --- strings.go | 25 +++++++++++++++++++++---- testdata/scripts/strings.txt | 28 +++++++++++++++++++++++++++- 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/strings.go b/strings.go index 3799b37..a8dbc57 100644 --- a/strings.go +++ b/strings.go @@ -18,11 +18,28 @@ func obfuscateLiterals(files []*ast.File) []*ast.File { return true } - // constants are not possibly if we want to obfuscate literals, therfore - // remove all constants and replace them by variables - if t.Tok == token.CONST { - t.Tok = token.VAR + if t.Tok != token.CONST { + return true } + + for _, spec := range t.Specs { + spec, ok := spec.(*ast.ValueSpec) + if !ok { + // cannot happen because ast.GenDecl with token.Const are always of type ast.ValueSpec + return false + } + + for _, val := range spec.Values { + if v, ok := val.(*ast.BasicLit); !ok || v.Kind != token.STRING { + return false // skip the block if it contains non basic literals + } + } + } + + // constants are not possible if we want to obfuscate literals, therefore + // move all constant blocks which only contain strings to variables + t.Tok = token.VAR + return true } diff --git a/testdata/scripts/strings.txt b/testdata/scripts/strings.txt index 9ac2c40..40f686c 100644 --- a/testdata/scripts/strings.txt +++ b/testdata/scripts/strings.txt @@ -4,6 +4,8 @@ exec ./main cmp stdout main.stdout ! binsubstr main$exe 'Lorem' 'ipsum' 'dolor' 'first assign' 'second assign' 'First Line' 'Second Line' 'map value' 'to obfuscate' 'also obfuscate' +binsubstr main$exe 'Skip this block,' 'also skip this' + [short] stop # checking that the build is reproducible is slow # Also check that the binary is reproducible. @@ -28,6 +30,24 @@ const ( Second Line` ) +const ( + skip1 = "Skip this block," + i = 1 +) + +const ( + foo = iota + bar + + skip2 = "also skip this" +) + +const arrayLen = 4 + +var array [arrayLen]byte + +type typeAlias [arrayLen]byte + var variable = "ipsum" func main() { @@ -57,6 +77,10 @@ func main() { fmt.Println(testMap["map key"]) fmt.Println("another literal") + + fmt.Println(skip1, skip2) + + fmt.Println(i, foo, bar) } -- main.stdout -- @@ -70,4 +94,6 @@ second assign to obfuscate also obfuscate map value -another literal \ No newline at end of file +another literal +Skip this block, also skip this +1 0 1 \ No newline at end of file