Merge "Support Make rewriting APP-*"
diff --git a/android/paths.go b/android/paths.go
index a23dd74..26b72d1 100644
--- a/android/paths.go
+++ b/android/paths.go
@@ -584,10 +584,10 @@
var vndkOrNdkDir string
var ext string
if isSourceDump {
- ext = ".lsdump"
+ ext = ".lsdump.gz"
sourceOrBinaryDir = "source-based"
} else {
- ext = ".bdump"
+ ext = ".bdump.gz"
sourceOrBinaryDir = "binary-based"
}
if vndkOrNdk {
diff --git a/android/variable.go b/android/variable.go
index 666d729..05f50b5 100644
--- a/android/variable.go
+++ b/android/variable.go
@@ -138,6 +138,7 @@
EnableCFI *bool `json:",omitempty"`
Device_uses_hwc2 *bool `json:",omitempty"`
Treble *bool `json:",omitempty"`
+ Pdk *bool `json:",omitempty"`
VendorPath *string `json:",omitempty"`
diff --git a/cc/androidmk.go b/cc/androidmk.go
index 3ce01d2..2a3b344 100644
--- a/cc/androidmk.go
+++ b/cc/androidmk.go
@@ -149,6 +149,7 @@
fmt.Fprintln(w, "LOCAL_ADDITIONAL_DEPENDENCIES += ", library.sAbiOutputFile.String())
if library.sAbiDiff.Valid() && !library.static() {
fmt.Fprintln(w, "LOCAL_ADDITIONAL_DEPENDENCIES += ", library.sAbiDiff.String())
+ fmt.Fprintln(w, "HEADER_ABI_DIFFS += ", library.sAbiDiff.String())
}
}
diff --git a/cc/builder.go b/cc/builder.go
index f8b3e02..51c4ce9 100644
--- a/cc/builder.go
+++ b/cc/builder.go
@@ -158,9 +158,10 @@
_ = pctx.SourcePathVariable("sAbiDumper", "prebuilts/build-tools/${config.HostPrebuiltTag}/bin/header-abi-dumper")
+ // -w has been added since header-abi-dumper does not need to produce any sort of diagnostic information.
sAbiDump = pctx.AndroidStaticRule("sAbiDump",
blueprint.RuleParams{
- Command: "rm -f $out && $sAbiDumper -o ${out} $in $exportDirs -- $cFlags -Wno-packed -Qunused-arguments -isystem ${config.RSIncludePath}",
+ Command: "rm -f $out && $sAbiDumper -o ${out} $in $exportDirs -- $cFlags -w -isystem ${config.RSIncludePath}",
CommandDeps: []string{"$sAbiDumper"},
},
"cFlags", "exportDirs")
@@ -177,6 +178,7 @@
"symbolFile", "arch", "api", "exportedHeaderFlags")
_ = pctx.SourcePathVariable("sAbiDiffer", "prebuilts/build-tools/${config.HostPrebuiltTag}/bin/header-abi-diff")
+
// Abidiff check turned on in advice-only mode. Builds will not fail on abi incompatibilties / extensions.
sAbiDiff = pctx.AndroidStaticRule("sAbiDiff",
blueprint.RuleParams{
@@ -184,6 +186,11 @@
CommandDeps: []string{"$sAbiDiffer"},
},
"referenceDump", "libName", "arch")
+
+ unzipRefSAbiDump = pctx.AndroidStaticRule("unzipRefSAbiDump",
+ blueprint.RuleParams{
+ Command: "gunzip -c $in > $out",
+ })
)
func init() {
@@ -631,6 +638,17 @@
return android.OptionalPathForPath(outputFile)
}
+func UnzipRefDump(ctx android.ModuleContext, zippedRefDump android.Path, baseName string) android.Path {
+ outputFile := android.PathForModuleOut(ctx, baseName+"_ref.lsdump")
+ ctx.ModuleBuild(pctx, android.ModuleBuildParams{
+ Rule: unzipRefSAbiDump,
+ Description: "gunzip" + outputFile.Base(),
+ Output: outputFile,
+ Input: zippedRefDump,
+ })
+ return outputFile
+}
+
func SourceAbiDiff(ctx android.ModuleContext, inputDump android.Path, referenceDump android.Path,
baseName string) android.OptionalPath {
outputFile := android.PathForModuleOut(ctx, baseName+".abidiff")
diff --git a/cc/cc.go b/cc/cc.go
index 8069a90..43825ca 100644
--- a/cc/cc.go
+++ b/cc/cc.go
@@ -429,8 +429,7 @@
// Create source abi dumps if the module belongs to the list of VndkLibraries.
func (ctx *moduleContextImpl) createVndkSourceAbiDump() bool {
- return ctx.ctx.Device() && (inList(ctx.baseModuleName(), config.LLndkLibraries())) ||
- (inList(ctx.baseModuleName(), config.VndkLibraries()))
+ return ctx.ctx.Device() && ((Bool(ctx.mod.Properties.Vendor_available)) || (inList(ctx.baseModuleName(), config.LLndkLibraries())))
}
func (ctx *moduleContextImpl) selectedStl() string {
@@ -920,6 +919,9 @@
depPaths.ReexportedFlags = append(depPaths.ReexportedFlags, flags)
depPaths.ReexportedFlagsDeps = append(depPaths.ReexportedFlagsDeps,
genRule.GeneratedSourceFiles()...)
+ // Add these re-exported flags to help header-abi-dumper to infer the abi exported by a library.
+ c.sabi.Properties.ReexportedIncludeFlags = append(c.sabi.Properties.ReexportedIncludeFlags, flags)
+
}
} else {
ctx.ModuleErrorf("module %q is not a genrule", name)
@@ -969,6 +971,12 @@
if t.reexportFlags {
depPaths.ReexportedFlags = append(depPaths.ReexportedFlags, flags...)
depPaths.ReexportedFlagsDeps = append(depPaths.ReexportedFlagsDeps, deps...)
+ // Add these re-exported flags to help header-abi-dumper to infer the abi exported by a library.
+ // Re-exported flags from shared library dependencies are not included as those shared libraries
+ // will be included in the vndk set.
+ if tag == staticExportDepTag || tag == headerExportDepTag {
+ c.sabi.Properties.ReexportedIncludeFlags = append(c.sabi.Properties.ReexportedIncludeFlags, flags...)
+ }
}
}
diff --git a/cc/config/global.go b/cc/config/global.go
index 997256e..195b482 100644
--- a/cc/config/global.go
+++ b/cc/config/global.go
@@ -175,6 +175,7 @@
"-isystem bionic/libc/include",
"-isystem bionic/libc/kernel/uapi",
"-isystem bionic/libc/kernel/uapi/asm-" + kernelArch,
+ "-isystem bionic/libc/kernel/android/scsi",
"-isystem bionic/libc/kernel/android/uapi",
}, " ")
}
diff --git a/cc/library.go b/cc/library.go
index d6a85e9..997344c 100644
--- a/cc/library.go
+++ b/cc/library.go
@@ -317,6 +317,27 @@
return library.baseCompiler.compilerFlags(ctx, flags)
}
+func extractExportIncludesFromFlags(flags []string) []string {
+ // This method is used in the generation of rules which produce
+ // abi-dumps for source files. Exported headers are needed to infer the
+ // abi exported by a library and filter out the rest of the abi dumped
+ // from a source. We extract the include flags exported by a library.
+ // This includes the flags exported which are re-exported from static
+ // library dependencies, exported header library dependencies and
+ // generated header dependencies. Re-exported shared library include
+ // flags are not in this set since shared library dependencies will
+ // themselves be included in the vndk. -isystem headers are not included
+ // since for bionic libraries, abi-filtering is taken care of by version
+ // scripts.
+ var exportedIncludes []string
+ for _, flag := range flags {
+ if strings.HasPrefix(flag, "-I") {
+ exportedIncludes = append(exportedIncludes, flag)
+ }
+ }
+ return exportedIncludes
+}
+
func (library *libraryDecorator) compile(ctx ModuleContext, flags Flags, deps PathDeps) Objects {
if !library.buildShared() && !library.buildStatic() {
if len(library.baseCompiler.Properties.Srcs) > 0 {
@@ -330,13 +351,15 @@
}
return Objects{}
}
- if ctx.createVndkSourceAbiDump() || (library.sabi.Properties.CreateSAbiDumps && ctx.Device()) {
+ if (ctx.createVndkSourceAbiDump() || (library.sabi.Properties.CreateSAbiDumps && ctx.Device())) && !ctx.Vendor() {
exportIncludeDirs := android.PathsForModuleSrc(ctx, library.flagExporter.Properties.Export_include_dirs)
var SourceAbiFlags []string
for _, dir := range exportIncludeDirs.Strings() {
- SourceAbiFlags = append(SourceAbiFlags, "-I "+dir)
+ SourceAbiFlags = append(SourceAbiFlags, "-I"+dir)
}
-
+ for _, reexportedInclude := range extractExportIncludesFromFlags(library.sabi.Properties.ReexportedIncludeFlags) {
+ SourceAbiFlags = append(SourceAbiFlags, reexportedInclude)
+ }
flags.SAbiFlags = SourceAbiFlags
total_length := len(library.baseCompiler.Properties.Srcs) + len(deps.GeneratedSources) + len(library.Properties.Shared.Srcs) +
len(library.Properties.Static.Srcs)
@@ -573,7 +596,7 @@
func (library *libraryDecorator) linkSAbiDumpFiles(ctx ModuleContext, objs Objects, fileName string) {
//Also take into account object re-use.
- if len(objs.sAbiDumpFiles) > 0 && ctx.createVndkSourceAbiDump() {
+ if len(objs.sAbiDumpFiles) > 0 && ctx.createVndkSourceAbiDump() && !ctx.Vendor() {
refSourceDumpFile := android.PathForVndkRefAbiDump(ctx, "current", fileName, vndkVsNdk(ctx), true)
versionScript := android.OptionalPathForModuleSrc(ctx, library.Properties.Version_script)
var symbolFile android.OptionalPath
@@ -583,12 +606,16 @@
exportIncludeDirs := android.PathsForModuleSrc(ctx, library.flagExporter.Properties.Export_include_dirs)
var SourceAbiFlags []string
for _, dir := range exportIncludeDirs.Strings() {
- SourceAbiFlags = append(SourceAbiFlags, "-I "+dir)
+ SourceAbiFlags = append(SourceAbiFlags, "-I"+dir)
+ }
+ for _, reexportedInclude := range extractExportIncludesFromFlags(library.sabi.Properties.ReexportedIncludeFlags) {
+ SourceAbiFlags = append(SourceAbiFlags, reexportedInclude)
}
exportedHeaderFlags := strings.Join(SourceAbiFlags, " ")
library.sAbiOutputFile = TransformDumpToLinkedDump(ctx, objs.sAbiDumpFiles, symbolFile, "current", fileName, exportedHeaderFlags)
if refSourceDumpFile.Valid() {
- library.sAbiDiff = SourceAbiDiff(ctx, library.sAbiOutputFile.Path(), refSourceDumpFile.Path(), fileName)
+ unzippedRefDump := UnzipRefDump(ctx, refSourceDumpFile.Path(), fileName)
+ library.sAbiDiff = SourceAbiDiff(ctx, library.sAbiOutputFile.Path(), unzippedRefDump, fileName)
}
}
}
diff --git a/cc/makevars.go b/cc/makevars.go
index 8bf034a..a1e97a5 100644
--- a/cc/makevars.go
+++ b/cc/makevars.go
@@ -42,6 +42,7 @@
ctx.Strict("RS_LLVM_PREBUILTS_VERSION", "${config.RSClangVersion}")
ctx.Strict("RS_LLVM_PREBUILTS_BASE", "${config.RSClangBase}")
ctx.Strict("RS_LLVM_PREBUILTS_PATH", "${config.RSLLVMPrebuiltsPath}")
+ ctx.Strict("RS_LLVM_INCLUDES", "${config.RSIncludePath}")
ctx.Strict("RS_CLANG", "${config.RSLLVMPrebuiltsPath}/clang")
ctx.Strict("RS_LLVM_AS", "${config.RSLLVMPrebuiltsPath}/llvm-as")
ctx.Strict("RS_LLVM_LINK", "${config.RSLLVMPrebuiltsPath}/llvm-link")
diff --git a/cc/sabi.go b/cc/sabi.go
index 7ae31c9..01ef737 100644
--- a/cc/sabi.go
+++ b/cc/sabi.go
@@ -22,7 +22,8 @@
)
type SAbiProperties struct {
- CreateSAbiDumps bool `blueprint:"mutated"`
+ CreateSAbiDumps bool `blueprint:"mutated"`
+ ReexportedIncludeFlags []string
}
type sabi struct {
@@ -45,7 +46,7 @@
func sabiDepsMutator(mctx android.TopDownMutatorContext) {
if c, ok := mctx.Module().(*Module); ok &&
- ((inList(c.Name(), config.VndkLibraries())) || (inList(c.Name(), config.LLndkLibraries())) ||
+ (Bool(c.Properties.Vendor_available) || (inList(c.Name(), config.LLndkLibraries())) ||
(c.sabi != nil && c.sabi.Properties.CreateSAbiDumps)) {
mctx.VisitDirectDeps(func(m blueprint.Module) {
tag := mctx.OtherModuleDependencyTag(m)
diff --git a/ui/build/Android.bp b/ui/build/Android.bp
index 8f5250b..25520da 100644
--- a/ui/build/Android.bp
+++ b/ui/build/Android.bp
@@ -30,6 +30,7 @@
"kati.go",
"make.go",
"ninja.go",
+ "proc_sync.go",
"signal.go",
"soong.go",
"util.go",
@@ -37,6 +38,7 @@
testSrcs: [
"environment_test.go",
"util_test.go",
+ "proc_sync_test.go",
],
darwin: {
srcs: [
diff --git a/ui/build/build.go b/ui/build/build.go
index 51dce05..83dbcb6 100644
--- a/ui/build/build.go
+++ b/ui/build/build.go
@@ -117,6 +117,10 @@
// Start getting java version as early as possible
getJavaVersions(ctx, config)
+ // Make sure that no other Soong process is running with the same output directory
+ buildLock := BecomeSingletonOrFail(ctx, config)
+ defer buildLock.Unlock()
+
SetupOutDir(ctx, config)
checkCaseSensitivity(ctx, config)
diff --git a/ui/build/java.go b/ui/build/java.go
index 481a680..473af01 100644
--- a/ui/build/java.go
+++ b/ui/build/java.go
@@ -66,9 +66,19 @@
var required_java_version string
var java_version_regexp *regexp.Regexp
var javac_version_regexp *regexp.Regexp
- required_java_version = "1.8"
- java_version_regexp = regexp.MustCompile(`[ "]1\.8[\. "$]`)
- javac_version_regexp = java_version_regexp
+
+ oj9_env, _ := config.Environment().Get("EXPERIMENTAL_USE_OPENJDK9")
+ experimental_use_openjdk9 := oj9_env != ""
+
+ if experimental_use_openjdk9 {
+ required_java_version = "9"
+ java_version_regexp = regexp.MustCompile(`^java .* "9.*"`)
+ javac_version_regexp = regexp.MustCompile(`^javac 9`)
+ } else {
+ required_java_version = "1.8"
+ java_version_regexp = regexp.MustCompile(`[ "]1\.8[\. "$]`)
+ javac_version_regexp = java_version_regexp
+ }
java_version := javaVersionInfo.java_version_output
javac_version := javaVersionInfo.javac_version_output
@@ -95,7 +105,10 @@
}
if runtime.GOOS == "linux" {
- if !strings.Contains(java_version, "openjdk") {
+ // Early access builds of OpenJDK 9 do not contain the string "openjdk" in the
+ // version name. TODO(tobiast): Reconsider once the OpenJDK 9 toolchain is stable.
+ // http://b/62123342
+ if !strings.Contains(java_version, "openjdk") && !experimental_use_openjdk9 {
ctx.Println("*******************************************************")
ctx.Println("You are attempting to build with an unsupported JDK.")
ctx.Println()
diff --git a/ui/build/proc_sync.go b/ui/build/proc_sync.go
new file mode 100644
index 0000000..857786d
--- /dev/null
+++ b/ui/build/proc_sync.go
@@ -0,0 +1,143 @@
+// Copyright 2017 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package build
+
+import (
+ "errors"
+ "fmt"
+ "math"
+ "os"
+ "path/filepath"
+ "syscall"
+ "time"
+
+ "android/soong/ui/logger"
+)
+
+// This file provides cross-process synchronization methods
+// i.e. making sure only one Soong process is running for a given output directory
+
+func BecomeSingletonOrFail(ctx Context, config Config) (lock *fileLock) {
+ lockingInfo, err := newLock(config.OutDir())
+ if err != nil {
+ ctx.Logger.Fatal(err)
+ }
+ err = lockSynchronous(*lockingInfo, newSleepWaiter(lockfilePollDuration, lockfileTimeout), ctx.Logger)
+ if err != nil {
+ ctx.Logger.Fatal(err)
+ }
+ return lockingInfo
+}
+
+var lockfileTimeout = time.Second * 10
+var lockfilePollDuration = time.Second
+
+type lockable interface {
+ tryLock() error
+ Unlock() error
+ description() string
+}
+
+var _ lockable = (*fileLock)(nil)
+
+type fileLock struct {
+ File *os.File
+}
+
+func (l fileLock) description() (path string) {
+ return l.File.Name()
+}
+func (l fileLock) tryLock() (err error) {
+ return syscall.Flock(int(l.File.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
+}
+func (l fileLock) Unlock() (err error) {
+ return l.File.Close()
+}
+
+func lockSynchronous(lock lockable, waiter waiter, logger logger.Logger) (err error) {
+
+ waited := false
+
+ for {
+ err = lock.tryLock()
+ if err == nil {
+ if waited {
+ // If we had to wait at all, then when the wait is done, we inform the user
+ logger.Printf("Acquired lock on %v; previous Soong process must have completed. Continuing...\n", lock.description())
+ }
+ return nil
+ }
+
+ waited = true
+
+ done, description := waiter.checkDeadline()
+
+ if done {
+ return fmt.Errorf("Tried to lock %s, but timed out %s . Make sure no other Soong process is using it",
+ lock.description(), waiter.summarize())
+ } else {
+ logger.Printf("Waiting up to %s to lock %v to ensure no other Soong process is running in the same output directory\n", description, lock.description())
+ waiter.wait()
+ }
+ }
+}
+
+func newLock(basedir string) (lock *fileLock, err error) {
+ lockPath := filepath.Join(basedir, ".lock")
+
+ os.MkdirAll(basedir, 0777)
+ lockfileDescriptor, err := os.OpenFile(lockPath, os.O_RDWR|os.O_CREATE, 0666)
+ if err != nil {
+ return nil, errors.New("failed to open " + lockPath)
+ }
+ lockingInfo := &fileLock{File: lockfileDescriptor}
+
+ return lockingInfo, nil
+}
+
+type waiter interface {
+ wait()
+ checkDeadline() (done bool, remainder string)
+ summarize() (summary string)
+}
+
+type sleepWaiter struct {
+ sleepInterval time.Duration
+ deadline time.Time
+
+ totalWait time.Duration
+}
+
+var _ waiter = (*sleepWaiter)(nil)
+
+func newSleepWaiter(interval time.Duration, duration time.Duration) (waiter *sleepWaiter) {
+ return &sleepWaiter{interval, time.Now().Add(duration), duration}
+}
+
+func (s sleepWaiter) wait() {
+ time.Sleep(s.sleepInterval)
+}
+func (s *sleepWaiter) checkDeadline() (done bool, remainder string) {
+ remainingSleep := s.deadline.Sub(time.Now())
+ numSecondsRounded := math.Floor(remainingSleep.Seconds()*10+0.5) / 10
+ if remainingSleep > 0 {
+ return false, fmt.Sprintf("%vs", numSecondsRounded)
+ } else {
+ return true, ""
+ }
+}
+func (s sleepWaiter) summarize() (summary string) {
+ return fmt.Sprintf("polling every %v until %v", s.sleepInterval, s.totalWait)
+}
diff --git a/ui/build/proc_sync_test.go b/ui/build/proc_sync_test.go
new file mode 100644
index 0000000..857bea3
--- /dev/null
+++ b/ui/build/proc_sync_test.go
@@ -0,0 +1,241 @@
+// Copyright 2017 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package build
+
+import (
+ "fmt"
+ "io/ioutil"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "syscall"
+ "testing"
+
+ "android/soong/ui/logger"
+)
+
+// some util methods and data structures that aren't directly part of a test
+func makeLockDir() (path string, err error) {
+ return ioutil.TempDir("", "soong_lock_test")
+}
+func lockOrFail(t *testing.T) (lock fileLock) {
+ lockDir, err := makeLockDir()
+ var lockPointer *fileLock
+ if err == nil {
+ lockPointer, err = newLock(lockDir)
+ }
+ if err != nil {
+ os.RemoveAll(lockDir)
+ t.Fatalf("Failed to create lock: %v", err)
+ }
+
+ return *lockPointer
+}
+func removeTestLock(fileLock fileLock) {
+ lockdir := filepath.Dir(fileLock.File.Name())
+ os.RemoveAll(lockdir)
+}
+
+// countWaiter only exists for the purposes of testing lockSynchronous
+type countWaiter struct {
+ numWaitsElapsed int
+ maxNumWaits int
+}
+
+func newCountWaiter(count int) (waiter *countWaiter) {
+ return &countWaiter{0, count}
+}
+
+func (c *countWaiter) wait() {
+ c.numWaitsElapsed++
+}
+func (c *countWaiter) checkDeadline() (done bool, remainder string) {
+ numWaitsRemaining := c.maxNumWaits - c.numWaitsElapsed
+ if numWaitsRemaining < 1 {
+ return true, ""
+ }
+ return false, fmt.Sprintf("%v waits remain", numWaitsRemaining)
+}
+func (c countWaiter) summarize() (summary string) {
+ return fmt.Sprintf("waiting %v times", c.maxNumWaits)
+}
+
+// countLock only exists for the purposes of testing lockSynchronous
+type countLock struct {
+ nextIndex int
+ successIndex int
+}
+
+var _ lockable = (*countLock)(nil)
+
+// returns a countLock that succeeds on iteration <index>
+func testLockCountingTo(index int) (lock *countLock) {
+ return &countLock{nextIndex: 0, successIndex: index}
+}
+func (c *countLock) description() (message string) {
+ return fmt.Sprintf("counter that counts from %v to %v", c.nextIndex, c.successIndex)
+}
+func (c *countLock) tryLock() (err error) {
+ currentIndex := c.nextIndex
+ c.nextIndex++
+ if currentIndex == c.successIndex {
+ return nil
+ }
+ return fmt.Errorf("Lock busy: %s", c.description())
+}
+func (c *countLock) Unlock() (err error) {
+ if c.nextIndex == c.successIndex {
+ return nil
+ }
+ return fmt.Errorf("Not locked: %s", c.description())
+}
+
+// end of util methods
+
+// start of tests
+
+// simple test
+func TestGetLock(t *testing.T) {
+ lockfile := lockOrFail(t)
+ defer removeTestLock(lockfile)
+}
+
+// a more complicated test that spans multiple processes
+var lockPathVariable = "LOCK_PATH"
+var successStatus = 0
+var unexpectedError = 1
+var busyStatus = 2
+
+func TestTrylock(t *testing.T) {
+ lockpath := os.Getenv(lockPathVariable)
+ if len(lockpath) < 1 {
+ checkTrylockMainProcess(t)
+ } else {
+ getLockAndExit(lockpath)
+ }
+}
+
+// the portion of TestTrylock that runs in the main process
+func checkTrylockMainProcess(t *testing.T) {
+ var err error
+ lockfile := lockOrFail(t)
+ defer removeTestLock(lockfile)
+ lockdir := filepath.Dir(lockfile.File.Name())
+ otherAcquired, message, err := forkAndGetLock(lockdir)
+ if err != nil {
+ t.Fatalf("Unexpected error in subprocess trying to lock uncontested fileLock: %v. Subprocess output: %q", err, message)
+ }
+ if !otherAcquired {
+ t.Fatalf("Subprocess failed to lock uncontested fileLock. Subprocess output: %q", message)
+ }
+
+ err = lockfile.tryLock()
+ if err != nil {
+ t.Fatalf("Failed to lock fileLock: %v", err)
+ }
+
+ reacquired, message, err := forkAndGetLock(filepath.Dir(lockfile.File.Name()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if reacquired {
+ t.Fatalf("Permitted locking fileLock twice. Subprocess output: %q", message)
+ }
+
+ err = lockfile.Unlock()
+ if err != nil {
+ t.Fatalf("Error unlocking fileLock: %v", err)
+ }
+
+ reacquired, message, err = forkAndGetLock(filepath.Dir(lockfile.File.Name()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reacquired {
+ t.Fatalf("Subprocess failed to acquire lock after it was released by the main process. Subprocess output: %q", message)
+ }
+}
+func forkAndGetLock(lockDir string) (acquired bool, subprocessOutput []byte, err error) {
+ cmd := exec.Command(os.Args[0], "-test.run=TestTrylock")
+ cmd.Env = append(os.Environ(), fmt.Sprintf("%s=%s", lockPathVariable, lockDir))
+ subprocessOutput, err = cmd.CombinedOutput()
+ exitStatus := successStatus
+ if exitError, ok := err.(*exec.ExitError); ok {
+ if waitStatus, ok := exitError.Sys().(syscall.WaitStatus); ok {
+ exitStatus = waitStatus.ExitStatus()
+ }
+ }
+ if exitStatus == successStatus {
+ return true, subprocessOutput, nil
+ } else if exitStatus == busyStatus {
+ return false, subprocessOutput, nil
+ } else {
+ return false, subprocessOutput, fmt.Errorf("Unexpected status %v", exitStatus)
+ }
+}
+
+// This function runs in a different process. See TestTrylock
+func getLockAndExit(lockpath string) {
+ fmt.Printf("Will lock path %q\n", lockpath)
+ lockfile, err := newLock(lockpath)
+ exitStatus := unexpectedError
+ if err == nil {
+ err = lockfile.tryLock()
+ if err == nil {
+ exitStatus = successStatus
+ } else {
+ exitStatus = busyStatus
+ }
+ }
+ fmt.Printf("Tried to lock path %s. Received error %v. Exiting with status %v\n", lockpath, err, exitStatus)
+ os.Exit(exitStatus)
+}
+
+func TestLockFirstTrySucceeds(t *testing.T) {
+ noopLogger := logger.New(ioutil.Discard)
+ lock := testLockCountingTo(0)
+ waiter := newCountWaiter(0)
+ err := lockSynchronous(lock, waiter, noopLogger)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if waiter.numWaitsElapsed != 0 {
+ t.Fatalf("Incorrect number of waits elapsed; expected 0, got %v", waiter.numWaitsElapsed)
+ }
+}
+func TestLockThirdTrySucceeds(t *testing.T) {
+ noopLogger := logger.New(ioutil.Discard)
+ lock := testLockCountingTo(2)
+ waiter := newCountWaiter(2)
+ err := lockSynchronous(lock, waiter, noopLogger)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if waiter.numWaitsElapsed != 2 {
+ t.Fatalf("Incorrect number of waits elapsed; expected 2, got %v", waiter.numWaitsElapsed)
+ }
+}
+func TestLockTimedOut(t *testing.T) {
+ noopLogger := logger.New(ioutil.Discard)
+ lock := testLockCountingTo(3)
+ waiter := newCountWaiter(2)
+ err := lockSynchronous(lock, waiter, noopLogger)
+ if err == nil {
+ t.Fatalf("Appeared to have acquired lock on iteration %v which should not be available until iteration %v", waiter.numWaitsElapsed, lock.successIndex)
+ }
+ if waiter.numWaitsElapsed != waiter.maxNumWaits {
+ t.Fatalf("Waited an incorrect number of times; expected %v, got %v", waiter.maxNumWaits, waiter.numWaitsElapsed)
+ }
+}