github.com/google/syzkaller@v0.0.0-20240517125934-c0f1611a36d6/pkg/tool/tool.go (about)

     1  // Copyright 2020 syzkaller project authors. All rights reserved.
     2  // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
     3  
     4  // Package tool contains various helper utilitites useful for implementation of command line tools.
     5  package tool
     6  
     7  import (
     8  	"flag"
     9  	"fmt"
    10  	"os"
    11  )
    12  
    13  // Init handles common tasks for command line tools:
    14  //   - invokes flag.Parse
    15  //   - adds support for optional flags (see OptionalFlags)
    16  //   - adds support for cpu/mem profiling (-cpuprofile/memprofile flags)
    17  //
    18  // Use as defer tool.Init()().
    19  func Init() func() {
    20  	flagCPUProfile := flag.String("cpuprofile", "", "write CPU profile to this file")
    21  	flagMEMProfile := flag.String("memprofile", "", "write memory profile to this file")
    22  	if err := ParseFlags(flag.CommandLine, os.Args[1:]); err != nil {
    23  		Fail(err)
    24  	}
    25  	return installProfiling(*flagCPUProfile, *flagMEMProfile)
    26  }
    27  
    28  func Failf(msg string, args ...interface{}) {
    29  	fmt.Fprintf(os.Stderr, msg+"\n", args...)
    30  	os.Exit(1)
    31  }
    32  
    33  func Fail(err error) {
    34  	Failf("%v", err)
    35  }