Source file src/runtime/testdata/testexithooks/testexithooks.go

     1  // Copyright 2022 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"flag"
     9  	"os"
    10  	_ "unsafe"
    11  )
    12  
    13  var modeflag = flag.String("mode", "", "mode to run in")
    14  
    15  func main() {
    16  	flag.Parse()
    17  	switch *modeflag {
    18  	case "simple":
    19  		testSimple()
    20  	case "goodexit":
    21  		testGoodExit()
    22  	case "badexit":
    23  		testBadExit()
    24  	case "panics":
    25  		testPanics()
    26  	case "callsexit":
    27  		testHookCallsExit()
    28  	default:
    29  		panic("unknown mode")
    30  	}
    31  }
    32  
    33  //go:linkname runtime_addExitHook runtime.addExitHook
    34  func runtime_addExitHook(f func(), runOnNonZeroExit bool)
    35  
    36  func testSimple() {
    37  	f1 := func() { println("foo") }
    38  	f2 := func() { println("bar") }
    39  	runtime_addExitHook(f1, false)
    40  	runtime_addExitHook(f2, false)
    41  	// no explicit call to os.Exit
    42  }
    43  
    44  func testGoodExit() {
    45  	f1 := func() { println("apple") }
    46  	f2 := func() { println("orange") }
    47  	runtime_addExitHook(f1, false)
    48  	runtime_addExitHook(f2, false)
    49  	// explicit call to os.Exit
    50  	os.Exit(0)
    51  }
    52  
    53  func testBadExit() {
    54  	f1 := func() { println("blog") }
    55  	f2 := func() { println("blix") }
    56  	f3 := func() { println("blek") }
    57  	f4 := func() { println("blub") }
    58  	f5 := func() { println("blat") }
    59  	runtime_addExitHook(f1, false)
    60  	runtime_addExitHook(f2, true)
    61  	runtime_addExitHook(f3, false)
    62  	runtime_addExitHook(f4, true)
    63  	runtime_addExitHook(f5, false)
    64  	os.Exit(1)
    65  }
    66  
    67  func testPanics() {
    68  	f1 := func() { println("ok") }
    69  	f2 := func() { panic("BADBADBAD") }
    70  	f3 := func() { println("good") }
    71  	runtime_addExitHook(f1, true)
    72  	runtime_addExitHook(f2, true)
    73  	runtime_addExitHook(f3, true)
    74  	os.Exit(0)
    75  }
    76  
    77  func testHookCallsExit() {
    78  	f1 := func() { println("ok") }
    79  	f2 := func() { os.Exit(1) }
    80  	f3 := func() { println("good") }
    81  	runtime_addExitHook(f1, true)
    82  	runtime_addExitHook(f2, true)
    83  	runtime_addExitHook(f3, true)
    84  	os.Exit(1)
    85  }
    86  

View as plain text