Skip to content

Commit

Permalink
loader: use ioutil.TempDir to create a temporary directory
Browse files Browse the repository at this point in the history
... 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.
  • Loading branch information
aykevl authored and sago35 committed Aug 27, 2020
1 parent 882ac0a commit b228c46
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions loader/goroot.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,11 @@ import (
"fmt"
"io"
"io/ioutil"
"math/rand"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strconv"

"github.com/tinygo-org/tinygo/compileopts"
"github.com/tinygo-org/tinygo/goenv"
Expand Down Expand Up @@ -50,16 +48,20 @@ func GetCachedGoroot(config *compileopts.Config) (string, error) {
fmt.Fprintln(hash, tinygoroot)
gorootsHash := hash.Sum(nil)
gorootsHashHex := hex.EncodeToString(gorootsHash[:])
cachedgoroot := filepath.Join(goenv.Get("GOCACHE"), "goroot-"+version+"-"+gorootsHashHex)
cachedgorootName := "goroot-" + version + "-" + gorootsHashHex
cachedgoroot := filepath.Join(goenv.Get("GOCACHE"), cachedgorootName)
if needsSyscallPackage(config.BuildTags()) {
cachedgoroot += "-syscall"
}

if _, err := os.Stat(cachedgoroot); err == nil {
return cachedgoroot, nil
}
tmpgoroot := cachedgoroot + ".tmp" + strconv.Itoa(rand.Int())
err = os.MkdirAll(tmpgoroot, 0777)
err = os.MkdirAll(goenv.Get("GOCACHE"), 0777)
if err != nil {
return "", err
}
tmpgoroot, err := ioutil.TempDir(goenv.Get("GOCACHE"), cachedgorootName+".tmp")
if err != nil {
return "", err
}
Expand Down

0 comments on commit b228c46

Please sign in to comment.