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.
Этот коммит содержится в:
Ayke van Laethem 2020-08-26 09:26:51 +02:00 коммит произвёл Ron Evans
родитель a21a039ac7
коммит 2194d447e9

Просмотреть файл

@ -10,13 +10,11 @@ import (
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"math/rand"
"os" "os"
"os/exec" "os/exec"
"path" "path"
"path/filepath" "path/filepath"
"runtime" "runtime"
"strconv"
"github.com/tinygo-org/tinygo/compileopts" "github.com/tinygo-org/tinygo/compileopts"
"github.com/tinygo-org/tinygo/goenv" "github.com/tinygo-org/tinygo/goenv"
@ -50,7 +48,8 @@ func GetCachedGoroot(config *compileopts.Config) (string, error) {
fmt.Fprintln(hash, tinygoroot) fmt.Fprintln(hash, tinygoroot)
gorootsHash := hash.Sum(nil) gorootsHash := hash.Sum(nil)
gorootsHashHex := hex.EncodeToString(gorootsHash[:]) 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()) { if needsSyscallPackage(config.BuildTags()) {
cachedgoroot += "-syscall" cachedgoroot += "-syscall"
} }
@ -58,8 +57,11 @@ func GetCachedGoroot(config *compileopts.Config) (string, error) {
if _, err := os.Stat(cachedgoroot); err == nil { if _, err := os.Stat(cachedgoroot); err == nil {
return cachedgoroot, nil return cachedgoroot, nil
} }
tmpgoroot := cachedgoroot + ".tmp" + strconv.Itoa(rand.Int()) err = os.MkdirAll(goenv.Get("GOCACHE"), 0777)
err = os.MkdirAll(tmpgoroot, 0777) if err != nil {
return "", err
}
tmpgoroot, err := ioutil.TempDir(goenv.Get("GOCACHE"), cachedgorootName+".tmp")
if err != nil { if err != nil {
return "", err return "", err
} }