//go:generate go run ../../mksyscall_windows.go -output zsyscall_windows.go interop.go
//sys coTaskMemFree(buffer unsafe.Pointer) = api_ms_win_core_com_l1_1_0.CoTaskMemFree
484604
func ConvertAndFreeCoTaskMemString(buffer *uint16) string {
	str := syscall.UTF16ToString((*[1 << 29]uint16)(unsafe.Pointer(buffer))[:])
	coTaskMemFree(unsafe.Pointer(buffer))
	return str
}
697982
func main() {
	p := params{Timestamp: time.Now(), Name: "codegen"}
	for i := 0; i < numTypes; i++ {
		p.StringTypeNames = append(p.StringTypeNames, fmt.Sprintf("Test%03d", i))
	}

	baseDir, err := os.Getwd()
	die(err)
	baseDir = filepath.Join(baseDir, "..")

	fmt.Printf("Generating test files in %v\n", filepath.Join(baseDir, "_gen"))
	apath := filepath.Join(baseDir, "_gen", "A")

	_ = os.MkdirAll(apath, 0755)

	instantiateTemplate(modelTemplate, p, filepath.Join(apath, "codegen_model.go"))
	instantiateTemplate(schemaTemplate, p, filepath.Join(apath, "codegen_schema.go"))
	instantiateTemplate(dataTemplate, p, filepath.Join(apath, "codegen_data.go"))
}
696286
func (prog *Program) Write(out io.Writer) error {
	out.Write([]byte(magic))

	gobIdents := func(idents []Ident) []gobIdent {
		res := make([]gobIdent, len(idents))
		for i, id := range idents {
			res[i].Name = id.Name
			res[i].Line = id.Pos.Line
			res[i].Col = id.Pos.Col
		}
		return res
	}

	gobFunc := func(fn *Funcode) gobFunction {
		return gobFunction{
			Id: gobIdent{
				Name: fn.Name,
				Line: fn.Pos.Line,
				Col:  fn.Pos.Col,
			},
			Code:       fn.Code,
			Pclinetab:  fn.pclinetab,
			Locals:     gobIdents(fn.Locals),
			Freevars:   gobIdents(fn.Freevars),
			MaxStack:   fn.MaxStack,
			NumParams:  fn.NumParams,
			HasVarargs: fn.HasVarargs,
			HasKwargs:  fn.HasKwargs,
		}
	}

	gp := &gobProgram{
		Version:   Version,
		Filename:  prog.Toplevel.Pos.Filename(),
		Loads:     gobIdents(prog.Loads),
		Names:     prog.Names,
		Constants: prog.Constants,
		Functions: make([]gobFunction, len(prog.Functions)),
		Globals:   gobIdents(prog.Globals),
		Toplevel:  gobFunc(prog.Toplevel),
	}
	for i, f := range prog.Functions {
		gp.Functions[i] = gobFunc(f)
	}

	return gob.NewEncoder(out).Encode(gp)
}
655427
func RunCompiled(inv Invocation, exePath string, errlog *log.Logger) int {
	debug.Println("running binary", exePath)
	c := exec.Command(exePath, inv.Args...)
	c.Stderr = inv.Stderr
	c.Stdout = inv.Stdout
	c.Stdin = inv.Stdin
	c.Dir = inv.Dir
	// intentionally pass through unaltered os.Environ here.. your magefile has
	// to deal with it.
	c.Env = os.Environ()
	if inv.Verbose {
		c.Env = append(c.Env, "MAGEFILE_VERBOSE=1")
	}
	if inv.List {
		c.Env = append(c.Env, "MAGEFILE_LIST=1")
	}
	if inv.Help {
		c.Env = append(c.Env, "MAGEFILE_HELP=1")
	}
	if inv.Debug {
		c.Env = append(c.Env, "MAGEFILE_DEBUG=1")
	}
	if inv.GoCmd != "" {
		c.Env = append(c.Env, fmt.Sprintf("MAGEFILE_GOCMD=%s", inv.GoCmd))
	}
	if inv.Timeout > 0 {
		c.Env = append(c.Env, fmt.Sprintf("MAGEFILE_TIMEOUT=%s", inv.Timeout.String()))
	}
	debug.Print("running magefile with mage vars:\n", strings.Join(filter(c.Env, "MAGEFILE"), "\n"))
	err := c.Run()
	if !sh.CmdRan(err) {
		errlog.Printf("failed to run compiled magefile: %v", err)
	}
	return sh.ExitStatus(err)
}
835039
func runGoFmt(filePath string) error {
	args := []string{
		"-w",
		filePath,
	}

	if out, err := exec.Command("gofmt", args...).CombinedOutput(); err != nil {
		log.Errorf("Error running go fmt on '%s' failed:\n%s", filePath, string(out))
		return errors.New("go fmt failed")
	}
	return nil
}
887609
func (ds *DataSource) tryToGetMemTask(prop *property.PhysicalProperty) (task task, err error) {
	if !prop.IsEmpty() {
		return nil, nil
	}
	if !infoschema.IsMemoryDB(ds.DBName.L) {
		return nil, nil
	}

	memTable := PhysicalMemTable{
		DBName:      ds.DBName,
		Table:       ds.tableInfo,
		Columns:     ds.Columns,
		TableAsName: ds.TableAsName,
	}.Init(ds.ctx, ds.stats)
	memTable.SetSchema(ds.schema)

	// Stop to push down these conditions.
	var retPlan PhysicalPlan = memTable
	if len(ds.pushedDownConds) > 0 {
		sel := PhysicalSelection{
			Conditions: ds.pushedDownConds,
		}.Init(ds.ctx, ds.stats)
		sel.SetChildren(memTable)
		retPlan = sel
	}
	return &rootTask{p: retPlan}, nil
}
564257
func run() error {
	// Reduce noise in logging output.
	log.SetFlags(0)

	// Check the command-line arguments.
	flag.Parse()

	cmdLineArgs := flag.Args()
	if len(cmdLineArgs) < 2 {
		return errors.New("Usage: createmock [package] [interface ...]")
	}

	// Create a temporary directory inside of $GOPATH to hold generated code.
	buildPkg, err := build.Import("github.com/jacobsa/oglemock", "", build.FindOnly)
	if err != nil {
		return errors.New(fmt.Sprintf("Couldn't find oglemock in $GOPATH: %v", err))
	}

	tmpDir, err := ioutil.TempDir(buildPkg.SrcRoot, "tmp-createmock-")
	if err != nil {
		return errors.New(fmt.Sprintf("Creating temp dir: %v", err))
	}

	defer os.RemoveAll(tmpDir)

	// Create a file to hold generated code.
	codeFile, err := os.Create(path.Join(tmpDir, "tool.go"))
	if err != nil {
		return errors.New(fmt.Sprintf("Couldn't create a file to hold code: %v", err))
	}

	// Create an appropriate path for the built binary.
	binaryPath := path.Join(tmpDir, "tool")

	// Create an appropriate template argument.
	arg := tmplArg{
		InterfacePkgPath: cmdLineArgs[0],
		TypeNames:        cmdLineArgs[1:],
	}

	if *fSamePackage {
		arg.OutputPkgPath = arg.InterfacePkgPath
	} else {
		arg.OutputPkgPath = "mock_" + path.Base(arg.InterfacePkgPath)
	}

	arg.Imports = make(importMap)
	arg.Imports[path.Base(arg.InterfacePkgPath)] = arg.InterfacePkgPath
	arg.Imports["generate"] = "github.com/jacobsa/oglemock/generate"
	arg.Imports["log"] = "log"
	arg.Imports["os"] = "os"
	arg.Imports["reflect"] = "reflect"

	// Execute the template to generate code that will itself generate the mock
	// code. Write the code to the temp file.
	tmpl := template.Must(
		template.New("code").Funcs(
			template.FuncMap{
				"pathBase": path.Base,
			}).Parse(tmplStr))
	if err := tmpl.Execute(codeFile, arg); err != nil {
		return errors.New(fmt.Sprintf("Error executing template: %v", err))
	}

	codeFile.Close()

	// Attempt to build the code.
	cmd := exec.Command("go", "build", "-o", binaryPath)
	cmd.Dir = tmpDir
	buildOutput, err := cmd.CombinedOutput()

	if err != nil {
		// Did the compilation fail due to the user-specified package not being found?
		pkg := findUnknownPackage(buildOutput)
		if pkg != nil && *pkg == arg.InterfacePkgPath {
			return errors.New(fmt.Sprintf("Unknown package: %s", *pkg))
		}

		// Did the compilation fail due to an unknown interface?
		if in := findUndefinedInterface(buildOutput); in != nil {
			return errors.New(fmt.Sprintf("Unknown interface: %s", *in))
		}

		// Otherwise return a generic error.
		return errors.New(fmt.Sprintf(
			"%s\n\nError building generated code:\n\n"+
				"    %v\n\nPlease report this oglemock bug.",
			buildOutput,
			err))
	}

	// Run the binary.
	cmd = exec.Command(binaryPath)
	binaryOutput, err := cmd.CombinedOutput()

	if err != nil {
		return errors.New(fmt.Sprintf(
			"%s\n\nError running generated code:\n\n"+
				"    %v\n\n Please report this oglemock bug.",
			binaryOutput,
			err))
	}

	// Copy its output.
	_, err = os.Stdout.Write(binaryOutput)
	if err != nil {
		return errors.New(fmt.Sprintf("Error copying binary output: %v", err))
	}

	return nil
}
843327
func (s *Simple) run() {
	for {
		select {
		case <-time.After(s.config.GCPeriodicity):
			s.GC()
		case <-s.halt:
			s.closeError <- nil
			// there is no cleanup required, so we just return
			return
		}
	}
}
1105187
func (s *StepCreateInstance) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	c := state.Get("config").(*Config)
	d := state.Get("driver").(Driver)

	ui := state.Get("ui").(packer.Ui)

	sourceImage, err := getImage(c, d)
	if err != nil {
		err := fmt.Errorf("Error getting source image for instance creation: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	ui.Say(fmt.Sprintf("Using image: %s", sourceImage.Name))

	if sourceImage.IsWindows() && c.Comm.Type == "winrm" && c.Comm.WinRMPassword == "" {
		state.Put("create_windows_password", true)
	}

	ui.Say("Creating instance...")
	name := c.InstanceName

	var errCh <-chan error
	var metadata map[string]string
	metadata, err = c.createInstanceMetadata(sourceImage, string(c.Comm.SSHPublicKey))
	errCh, err = d.RunInstance(&InstanceConfig{
		AcceleratorType:              c.AcceleratorType,
		AcceleratorCount:             c.AcceleratorCount,
		Address:                      c.Address,
		Description:                  "New instance created by Packer",
		DisableDefaultServiceAccount: c.DisableDefaultServiceAccount,
		DiskSizeGb:                   c.DiskSizeGb,
		DiskType:                     c.DiskType,
		Image:                        sourceImage,
		Labels:                       c.Labels,
		MachineType:                  c.MachineType,
		Metadata:                     metadata,
		MinCpuPlatform:               c.MinCpuPlatform,
		Name:                         name,
		Network:                      c.Network,
		NetworkProjectId:             c.NetworkProjectId,
		OmitExternalIP:               c.OmitExternalIP,
		OnHostMaintenance:            c.OnHostMaintenance,
		Preemptible:                  c.Preemptible,
		Region:                       c.Region,
		ServiceAccountEmail:          c.ServiceAccountEmail,
		Scopes:                       c.Scopes,
		Subnetwork:                   c.Subnetwork,
		Tags:                         c.Tags,
		Zone:                         c.Zone,
	})

	if err == nil {
		ui.Message("Waiting for creation operation to complete...")
		select {
		case err = <-errCh:
		case <-time.After(c.stateTimeout):
			err = errors.New("time out while waiting for instance to create")
		}
	}

	if err != nil {
		err := fmt.Errorf("Error creating instance: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	ui.Message("Instance has been created!")

	if s.Debug {
		if name != "" {
			ui.Message(fmt.Sprintf("Instance: %s started in %s", name, c.Zone))
		}
	}

	// Things succeeded, store the name so we can remove it later
	state.Put("instance_name", name)

	return multistep.ActionContinue
}
16771
func AppRun(appID, command string) error {
	c, appID, err := load(appID)

	if err != nil {
		return err
	}

	fmt.Printf("Running '%s'...\n", command)

	out, err := apps.Run(c, appID, command)

	if err != nil {
		return err
	}

	fmt.Print(out.Output)
	os.Exit(out.ReturnCode)
	return nil
}
522355
func (sc *Client) GenerateSymmetricKeyFromPassword(ctx context.Context, passwd string) (string, error) {
	var id string
	return id, sc.c.CallContext(ctx, &id, "shh_generateSymKeyFromPassword", passwd)
}
1085296
func (s *selector) Go(genomeArray []IGenome, totalFitness int) *IGenome {
	for {
		for _, config := range s.selectorConfig {
			if rand.Float32() < config.P {
				return config.F(genomeArray, totalFitness)
			}
		}
	}
}
1149731
func (g *Generator) generateImports() {
	// We almost always need a proto import.  Rather than computing when we
	// do, which is tricky when there's a plugin, just import it and
	// reference it later. The same argument applies to the fmt and math packages.
	if gogoproto.ImportsGoGoProto(g.file.FileDescriptorProto) {
		g.PrintImport(g.Pkg["proto"], g.ImportPrefix+"github.com/gogo/protobuf/proto")
		if gogoproto.RegistersGolangProto(g.file.FileDescriptorProto) {
			g.PrintImport(g.Pkg["golang_proto"], g.ImportPrefix+"github.com/golang/protobuf/proto")
		}
	} else {
		g.PrintImport(g.Pkg["proto"], g.ImportPrefix+"github.com/golang/protobuf/proto")
	}
	g.PrintImport(g.Pkg["fmt"], "fmt")
	g.PrintImport(g.Pkg["math"], "math")

	for i, s := range g.file.Dependency {
		fd := g.fileByName(s)
		// Do not import our own package.
		if fd.PackageName() == g.packageName {
			continue
		}
		filename := fd.goFileName()
		// By default, import path is the dirname of the Go filename.
		importPath := path.Dir(filename)
		if substitution, ok := g.ImportMap[s]; ok {
			importPath = substitution
		}
		importPath = g.ImportPrefix + importPath
		// Skip weak imports.
		if g.weak(int32(i)) {
			g.P("// skipping weak import ", fd.PackageName(), " ", strconv.Quote(importPath))
			continue
		}
		// We need to import all the dependencies, even if we don't reference them,
		// because other code and tools depend on having the full transitive closure
		// of protocol buffer types in the binary.
		if _, ok := g.usedPackages[fd.PackageName()]; ok {
			g.PrintImport(fd.PackageName(), importPath)
		} else {
			g.P("import _ ", strconv.Quote(importPath))
		}
	}
	g.P()
	for _, s := range g.customImports {
		s1 := strings.Map(badToUnderscore, s)
		g.PrintImport(s1, s)
	}
	g.P()
	g.P("// Reference imports to suppress errors if they are not otherwise used.")
	g.P("var _ = ", g.Pkg["proto"], ".Marshal")
	if gogoproto.ImportsGoGoProto(g.file.FileDescriptorProto) && gogoproto.RegistersGolangProto(g.file.FileDescriptorProto) {
		g.P("var _ = ", g.Pkg["golang_proto"], ".Marshal")
	}
	g.P("var _ = ", g.Pkg["fmt"], ".Errorf")
	g.P("var _ = ", g.Pkg["math"], ".Inf")
	for _, cimport := range g.customImports {
		if cimport == "time" {
			g.P("var _ = time.Kitchen")
			break
		}
	}
	g.P()
}
274446
func Run(
	ctx context.Context,
	appName, appDescription, appUsage string,
	sp StoragePluginProvider) {

	// Check for the debug value.
	if v, ok := csictx.LookupEnv(ctx, EnvVarDebug); ok {
		if ok, _ := strconv.ParseBool(v); ok {
			csictx.Setenv(ctx, EnvVarLogLevel, "debug")
			csictx.Setenv(ctx, EnvVarReqLogging, "true")
			csictx.Setenv(ctx, EnvVarRepLogging, "true")
		}
	}

	// Adjust the log level.
	lvl := log.InfoLevel
	if v, ok := csictx.LookupEnv(ctx, EnvVarLogLevel); ok {
		var err error
		if lvl, err = log.ParseLevel(v); err != nil {
			lvl = log.InfoLevel
		}
	}
	log.SetLevel(lvl)

	printUsage := func() {
		// app is the information passed to the printUsage function
		app := struct {
			Name        string
			Description string
			Usage       string
			BinPath     string
		}{
			appName,
			appDescription,
			appUsage,
			os.Args[0],
		}

		t, err := template.New("t").Parse(usage)
		if err != nil {
			log.WithError(err).Fatalln("failed to parse usage template")
		}
		if err := t.Execute(os.Stderr, app); err != nil {
			log.WithError(err).Fatalln("failed emitting usage")
		}
		return
	}

	// Check for a help flag.
	fs := flag.NewFlagSet("csp", flag.ExitOnError)
	fs.Usage = printUsage
	var help bool
	fs.BoolVar(&help, "?", false, "")
	err := fs.Parse(os.Args)
	if err == flag.ErrHelp || help {
		printUsage()
		os.Exit(1)
	}

	// If no endpoint is set then print the usage.
	if os.Getenv(EnvVarEndpoint) == "" {
		printUsage()
		os.Exit(1)
	}

	l, err := utils.GetCSIEndpointListener()
	if err != nil {
		log.WithError(err).Fatalln("failed to listen")
	}

	// Define a lambda that can be used in the exit handler
	// to remove a potential UNIX sock file.
	var rmSockFileOnce sync.Once
	rmSockFile := func() {
		rmSockFileOnce.Do(func() {
			if l == nil || l.Addr() == nil {
				return
			}
			if l.Addr().Network() == netUnix {
				sockFile := l.Addr().String()
				os.RemoveAll(sockFile)
				log.WithField("path", sockFile).Info("removed sock file")
			}
		})
	}

	trapSignals(func() {
		sp.GracefulStop(ctx)
		rmSockFile()
		log.Info("server stopped gracefully")
	}, func() {
		sp.Stop(ctx)
		rmSockFile()
		log.Info("server aborted")
	})

	if err := sp.Serve(ctx, l); err != nil {
		rmSockFile()
		log.WithError(err).Fatal("grpc failed")
	}
}
1090410
func Generate() (files []string, err error) {
	var outDir, target, appPkg, ver string

	set := flag.NewFlagSet("gorma", flag.PanicOnError)
	set.String("design", "", "")
	set.StringVar(&outDir, "out", "", "")
	set.StringVar(&ver, "version", "", "")
	set.StringVar(&target, "pkg", "models", "")
	set.StringVar(&appPkg, "app", "app", "")
	set.Parse(os.Args[2:])

	// First check compatibility
	if err := codegen.CheckVersion(ver); err != nil {
		return nil, err
	}

	// Now proceed
	appPkgPath, err := codegen.PackagePath(filepath.Join(outDir, appPkg))
	if err != nil {
		return nil, fmt.Errorf("invalid app package: %s", err)
	}
	outDir = filepath.Join(outDir, target)

	g := &Generator{outDir: outDir, target: target, appPkg: appPkg, appPkgPath: appPkgPath}

	return g.Generate(design.Design)
}
1208891
func (g *Generator) funcMap() template.FuncMap {
	return template.FuncMap{
		"EscapeMD":       escapeMD,
		"Symbol":         g.symbol,
		"LinkifySymbols": g.linkifySymbols,
	}
}
231522
func (a Application) Run(c context.Context) error {
	if err := resolveExecutable(&a.genPath); err != nil {
		return fmt.Errorf("invalid API generator path (-google-api-go-generator): %s", err)
	}

	apiDst, err := getPackagePath(a.apiPackage)
	if err != nil {
		return fmt.Errorf("failed to find package path for [%s]: %s", a.apiPackage, err)
	}
	if a.apiSubproject != "" {
		apiDst = augPath(apiDst, a.apiSubproject)
		a.apiPackage = strings.Join([]string{a.apiPackage, a.apiSubproject}, "/")
	}
	log.Fields{
		"package": a.apiPackage,
		"path":    apiDst,
	}.Debugf(c, "Identified API destination package path.")

	// Compile our Chromium license.
	a.license, err = compileChromiumLicense(c)
	if err != nil {
		return fmt.Errorf("failed to compile Chromium license: %s", err)
	}

	c, cancelFunc := context.WithCancel(c)
	sigC := make(chan os.Signal, 1)
	signal.Notify(sigC, os.Interrupt)
	go func() {
		for range sigC {
			cancelFunc()
		}
	}()
	defer signal.Stop(sigC)

	// (1) Execute our service. Capture its discovery API.
	svc, err := loadService(c, a.servicePath)
	if err != nil {
		return fmt.Errorf("failed to load service [%s]: %s", a.servicePath, err)
	}

	err = svc.run(c, func(c context.Context, discoveryURL url.URL) error {
		discoveryURL.Path = safeURLPathJoin(discoveryURL.Path, a.serviceAPIRoot, "discovery", "v1", "apis")

		data, err := retryHTTP(c, discoveryURL, "GET", "")
		if err != nil {
			return fmt.Errorf("discovery server did not come online: %s", err)
		}

		dir := directoryList{}
		if err := json.Unmarshal(data, &dir); err != nil {
			return fmt.Errorf("failed to load directory list: %s", err)
		}

		// Ensure that our target API base directory exists.
		if err := ensureDirectory(apiDst); err != nil {
			return fmt.Errorf("failed to create destination directory: %s", err)
		}

		// Run "google-api-go-generator" against the hosted service.
		err = parallel.FanOutIn(func(taskC chan<- func() error) {
			for i, item := range dir.Items {
				item := item
				c := log.SetFields(c, log.Fields{
					"index": i,
					"api":   item.ID,
				})

				if !a.isWhitelisted(item.ID) {
					log.Infof(c, "API is not whitelisted; skipping.")
					continue
				}

				taskC <- func() error {
					return a.generateAPI(c, item, &discoveryURL, apiDst)
				}
			}
		})
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		log.Fields{
			log.ErrorKey: err,
		}.Errorf(c, "Failed to extract APIs.")
	}

	return nil
}