gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/tools/embeddedbinary/test/helloworld_bundler.go (about)

     1  // Copyright 2023 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // helloworld_bundler bundles helloworld_bundlee and executes it.
    16  package main
    17  
    18  import (
    19  	"fmt"
    20  	"os"
    21  
    22  	syscall "golang.org/x/sys/unix"
    23  	"gvisor.dev/gvisor/tools/embeddedbinary/test/helloworld"
    24  )
    25  
    26  func doExec() {
    27  	if err := helloworld.Exec(helloworld.Options{}); err != nil {
    28  		fmt.Fprintf(os.Stderr, "Failed to exec embedded binary: %v\n", err)
    29  		os.Exit(1)
    30  	}
    31  	fmt.Fprintf(os.Stderr, "Unreachable\n")
    32  	os.Exit(1)
    33  }
    34  
    35  func doForkExec() {
    36  	childPID, err := helloworld.ForkExec(helloworld.Options{
    37  		// Share stdin/stdout/stderr with child process.
    38  		Files: []uintptr{os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd()},
    39  	})
    40  	if err != nil {
    41  		fmt.Fprintf(os.Stderr, "Failed to fork+exec embedded binary: %v\n", err)
    42  		os.Exit(1)
    43  	}
    44  	var waitStatus syscall.WaitStatus
    45  	if _, err := syscall.Wait4(childPID, &waitStatus, 0, nil); err != nil {
    46  		fmt.Fprintf(os.Stderr, "Failed to wait for child embedded binary: %v\n", err)
    47  		os.Exit(1)
    48  	}
    49  	if status := waitStatus.ExitStatus(); status != 0 {
    50  		fmt.Fprintf(os.Stderr, "Child embedded binary returned code %d\n", status)
    51  		os.Exit(status)
    52  	}
    53  	os.Exit(0)
    54  }
    55  
    56  func main() {
    57  	for _, arg := range os.Args {
    58  		switch arg {
    59  		case "--mode=exec":
    60  			doExec()
    61  		case "--mode=fork":
    62  			doForkExec()
    63  		}
    64  	}
    65  	fmt.Fprintf(os.Stderr, "Must specify either --mode=exec or --mode=fork.\n")
    66  	os.Exit(1)
    67  }