Skip to content

Commit b228c46

Browse files
aykevlsago35
authored andcommitted
loader: use ioutil.TempDir to create a temporary directory
... instead of generating one with math/rand. The problem was that math/rand is deterministic across runs, resulting in a possible race when trying to create the same directory between two processes. Additionally, because I used `os.MkdirAll`, no error was reported when the directory already existed. The solution to this is to use the stdlib function designed for this: ioutil.TempDir.
1 parent 882ac0a commit b228c46

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

loader/goroot.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,11 @@ import (
1010
"fmt"
1111
"io"
1212
"io/ioutil"
13-
"math/rand"
1413
"os"
1514
"os/exec"
1615
"path"
1716
"path/filepath"
1817
"runtime"
19-
"strconv"
2018

2119
"github.com/tinygo-org/tinygo/compileopts"
2220
"github.com/tinygo-org/tinygo/goenv"
@@ -50,16 +48,20 @@ func GetCachedGoroot(config *compileopts.Config) (string, error) {
5048
fmt.Fprintln(hash, tinygoroot)
5149
gorootsHash := hash.Sum(nil)
5250
gorootsHashHex := hex.EncodeToString(gorootsHash[:])
53-
cachedgoroot := filepath.Join(goenv.Get("GOCACHE"), "goroot-"+version+"-"+gorootsHashHex)
51+
cachedgorootName := "goroot-" + version + "-" + gorootsHashHex
52+
cachedgoroot := filepath.Join(goenv.Get("GOCACHE"), cachedgorootName)
5453
if needsSyscallPackage(config.BuildTags()) {
5554
cachedgoroot += "-syscall"
5655
}
5756

5857
if _, err := os.Stat(cachedgoroot); err == nil {
5958
return cachedgoroot, nil
6059
}
61-
tmpgoroot := cachedgoroot + ".tmp" + strconv.Itoa(rand.Int())
62-
err = os.MkdirAll(tmpgoroot, 0777)
60+
err = os.MkdirAll(goenv.Get("GOCACHE"), 0777)
61+
if err != nil {
62+
return "", err
63+
}
64+
tmpgoroot, err := ioutil.TempDir(goenv.Get("GOCACHE"), cachedgorootName+".tmp")
6365
if err != nil {
6466
return "", err
6567
}

0 commit comments

Comments
 (0)