Golang 將改變常見的 closure 地雷

在「Fixing for loops in Go 1.22 (go.dev)」看到的,原文在「Fixing For Loops in Go 1.22」這邊。

算是各種有 closure 的程式語言會遇到的經典問題,下面的 Golang 程式在撰寫時會預期輸出 abc (不保證順序),但實際上會輸出 ccc,因為變數的 scope 設計原因:

func main() {
    done := make(chan bool)

    values := []string{"a", "b", "c"}
    for _, v := range values {
        go func() {
            fmt.Println(v)
            done <- true
        }()
    }

    // wait for all goroutines to complete before exiting
    for _ = range values {
        <-done
    }
}

這在 JavaScript 也是個經典的問題,搜「javascript closure loop」就可以看到「JavaScript closure inside loops – simple practical example」這個例子,對應的答案則是有提到 ES6let 因為改變了變數的 scope,可以用來解決這個問題。

剛好 let 也是 best practice 了,所以現在 JavaScript 這邊遇到這個問題的情況會少一些。

回到 Golang 這邊,Golang 是打算改變在 for loop 時,對應變數的 scope 來解決:

For Go 1.22, we plan to change for loops to make these variables have per-iteration scope instead of per-loop scope. This change will fix the examples above, so that they are no longer buggy Go programs; it will end the production problems caused by such mistakes; and it will remove the need for imprecise tools that prompt users to make unnecessary changes to their code.

另外因為這是 breaking compatibility 的改變 (畢竟有些程式碼是清楚知道這個特性而刻意這樣寫的),所以會有對應的措施,只有在有指定 Golang 1.22 或是更新的版本才會用新的 scope 編譯:

To ensure backwards compatibility with existing code, the new semantics will only apply in packages contained in modules that declare go 1.22 or later in their go.mod files. This per-module decision provides developer control of a gradual update to the new semantics throughout a codebase. It is also possible to use //go:build lines to control the decision on a per-file basis.

用統計方法反推 JavaScript 壓縮程式的變數名稱

JavaScript 在正式提供服務時一般都會使用「YUI Compressor」、「UglifyJS」或是「Closure Compiler」壓縮後再拿到正式環境上使用,最主要的目的是為了降低網路傳輸量。

這些工具其中一個特點是,local function 與 local variable 會被較短的名字取代掉,這可以讓想要反組譯的人比較麻煩。

不過今天看到的這個工具可以解決「困擾」:「JSNice」。(在 Slashdot 上的「Machine Learning Used For JavaScript Code De-obfuscation」這篇看到的)

用統計方法去「猜測」這些 local function 與 local variable 應該叫什麼名字,讓人比較好理解。官方對準確度的說法是超過 60%:

In our experiments, we found JSNice to be effective for deobfuscating minified code. On average, more than 60% of the identifiers are recovered to the same name as before the minification process.

接下來會想辦法提供 UI 讓使用者可以選擇另外的名字:

Further, as JSNice computes multiple ranked suggestions, we provide a UI to navigate through these suggestions and select alternative identifier names.

先記錄起來,這網站很有趣,之後要 trace 別人的程式碼應該常常會用到 XDDD