// EntryPoint will return the process entry point address, useful for
// debugging PIEs.
769188
func (p *Process) EntryPoint() (uint64, error) {
	var entryPoint uint64
	if auxv, err := p.conn.readAuxv(); err == nil {
		// If we can't read the auxiliary vector it just means it's not supported
		// by the OS or by the stub. If we are debugging a PIE and the entry point
		// is needed proc.LoadBinaryInfo will complain about it.
		entryPoint = linutil.EntryPointFromAuxvAMD64(auxv)
	}
	return entryPoint, nil
}
797448
func (p Publisher) Endpoint() endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		ctx, cancel := context.WithTimeout(ctx, p.timeout)
		defer cancel()

		pub := amqp.Publishing{
			ReplyTo:       p.q.Name,
			CorrelationId: randomString(randInt(5, maxCorrelationIdLength)),
		}

		if err := p.enc(ctx, &pub, request); err != nil {
			return nil, err
		}

		for _, f := range p.before {
			// Affect only amqp.Publishing
			ctx = f(ctx, &pub, nil)
		}

		deliv, err := p.deliverer(ctx, p, &pub)
		if err != nil {
			return nil, err
		}

		for _, f := range p.after {
			ctx = f(ctx, deliv)
		}
		response, err := p.dec(ctx, deliv)
		if err != nil {
			return nil, err
		}

		return response, nil
	}
}
596258
func (c *command) Start() error {
	cmd := endpointToCommand(c.command, c.endpoint)

	e := pktline.NewEncoder(c.conn)
	return e.Encode([]byte(cmd))
}
458755
func (ce CrossingEntrypoint) Run() error {
	enterCmd, err := getStage1Entrypoint(ce.PodPath, enterEntrypoint)
	if err != nil {
		return errwrap.Wrap(errors.New("error determining 'enter' entrypoint"), err)
	}

	previousDir, err := os.Getwd()
	if err != nil {
		return err
	}

	if err := os.Chdir(ce.PodPath); err != nil {
		return errwrap.Wrap(errors.New("failed changing to dir"), err)
	}

	ep, err := getStage1Entrypoint(ce.PodPath, ce.EntrypointName)
	if err != nil {
		return fmt.Errorf("%q not implemented for pod's stage1: %v", ce.EntrypointName, err)
	}
	execArgs := []string{filepath.Join(common.Stage1RootfsPath(ce.PodPath), ep)}
	execArgs = append(execArgs, ce.EntrypointArgs...)

	pathEnv := os.Getenv("PATH")
	if pathEnv == "" {
		pathEnv = common.DefaultPath
	}
	execEnv := []string{
		fmt.Sprintf("%s=%s", common.CrossingEnterCmd, filepath.Join(common.Stage1RootfsPath(ce.PodPath), enterCmd)),
		fmt.Sprintf("%s=%d", common.CrossingEnterPID, ce.PodPID),
		fmt.Sprintf("PATH=%s", pathEnv),
	}

	c := exec.Cmd{
		Path: execArgs[0],
		Args: execArgs,
		Env:  execEnv,
	}

	if ce.Interactive {
		c.Stdin = os.Stdin
		c.Stdout = os.Stdout
		c.Stderr = os.Stderr
		if err := c.Run(); err != nil {
			return fmt.Errorf("error executing stage1 entrypoint: %v", err)
		}
	} else {
		out, err := c.CombinedOutput()
		if len(out) > 0 {
			debug("%s\n", out)
		}

		if err != nil {
			return errwrap.Wrapf("error executing stage1 entrypoint", err)
		}
	}

	if err := os.Chdir(previousDir); err != nil {
		return errwrap.Wrap(errors.New("failed changing to dir"), err)
	}

	return nil
}
1277350
func (p Publisher) Endpoint() endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		ctx, cancel := context.WithTimeout(context.Background(), p.timeout)
		defer cancel()

		msg := nats.Msg{Subject: p.subject}

		if err := p.enc(ctx, &msg, request); err != nil {
			return nil, err
		}

		for _, f := range p.before {
			ctx = f(ctx, &msg)
		}

		resp, err := p.publisher.RequestWithContext(ctx, msg.Subject, msg.Data)
		if err != nil {
			return nil, err
		}

		for _, f := range p.after {
			ctx = f(ctx, resp)
		}

		response, err := p.dec(ctx, resp)
		if err != nil {
			return nil, err
		}

		return response, nil
	}
}
726830
func StartProcess(label string, dir string, execPath string, args []string, inFile io.Reader, outFile io.WriteCloser) (*Process, error) {
	cmd := exec.Command(execPath, args...)
	cmd.Dir = dir
	cmd.Stdout = outFile
	cmd.Stderr = outFile
	cmd.Stdin = inFile
	if err := cmd.Start(); err != nil {
		return nil, err
	}
	proc := &Process{
		Label:      label,
		ExecPath:   execPath,
		Args:       args,
		Pid:        cmd.Process.Pid,
		StartTime:  time.Now(),
		Cmd:        cmd,
		ExitState:  nil,
		InputFile:  inFile,
		OutputFile: outFile,
		WaitCh:     make(chan struct{}),
	}
	go func() {
		err := proc.Cmd.Wait()
		if err != nil {
			// fmt.Printf("Process exit: %v\n", err)
			if exitError, ok := err.(*exec.ExitError); ok {
				proc.ExitState = exitError.ProcessState
			}
		}
		proc.ExitState = proc.Cmd.ProcessState
		proc.EndTime = time.Now() // TODO make this goroutine-safe
		err = proc.OutputFile.Close()
		if err != nil {
			fmt.Printf("Error closing output file for %v: %v\n", proc.Label, err)
		}
		close(proc.WaitCh)
	}()
	return proc, nil
}
898681
func Main() int {
	return ParseAndRun(os.Stdout, os.Stderr, os.Stdin, os.Args[1:])
}
1190988
func init() {
	ps := endpoints.ProdService{}

	r := router.New()

	// Setup Cloud Endpoints.
	svr := prpc.Server{
		UnaryServerInterceptor: grpcmon.NewUnaryServerInterceptor(nil),
	}
	servicesPb.RegisterServicesServer(&svr, services.New())
	registrationPb.RegisterRegistrationServer(&svr, registration.New())

	// Standard HTTP endpoints.
	base := standard.Base().Extend(ps.Base)
	svr.InstallHandlers(r, base)
	standard.InstallHandlers(r)

	http.Handle("/", r)
}
616018
func (p *Process) Checkpoint(where string) (int, error) {
	if p.tracedir == "" {
		return -1, proc.ErrNotRecorded
	}
	resp, err := p.conn.qRRCmd("checkpoint", where)
	if err != nil {
		return -1, err
	}

	if !strings.HasPrefix(resp, checkpointPrefix) {
		return -1, fmt.Errorf("can not parse checkpoint response %q", resp)
	}

	idstr := resp[len(checkpointPrefix):]
	space := strings.Index(idstr, " ")
	if space < 0 {
		return -1, fmt.Errorf("can not parse checkpoint response %q", resp)
	}
	idstr = idstr[:space]

	cpid, err := strconv.Atoi(idstr)
	if err != nil {
		return -1, err
	}
	return cpid, nil
}
295262
func MiddlePoint(a, b *Point) *Point {
	return NewPoint((a.x+b.x)/2, (a.y+b.y)/2)
}
912173
func WriteEndpoint(f EndpointFrontend) error {
	info, err := f.GetBPFValue()
	if err != nil {
		return err
	}

	// FIXME: Revert on failure
	for _, v := range f.GetBPFKeys() {
		if err := LXCMap.Update(v, info); err != nil {
			return err
		}
	}

	return nil
}
882077
func main() {
	var modelName, outName string
	flag.StringVar(&modelName, "model", "", "Endpoints definition model")
	flag.StringVar(&outName, "out", "", "File to write generated endpoints to.")
	flag.Parse()

	if len(modelName) == 0 || len(outName) == 0 {
		exitErrorf("model and out both required.")
	}

	modelFile, err := os.Open(modelName)
	if err != nil {
		exitErrorf("failed to open model definition, %v.", err)
	}
	defer modelFile.Close()

	outFile, err := os.Create(outName)
	if err != nil {
		exitErrorf("failed to open out file, %v.", err)
	}
	defer func() {
		if err := outFile.Close(); err != nil {
			exitErrorf("failed to successfully write %q file, %v", outName, err)
		}
	}()

	if err := endpoints.CodeGenModel(modelFile, outFile, func(o *endpoints.CodeGenOptions) {
		o.DisableGenerateServiceIDs = true
	}); err != nil {
		exitErrorf("failed to codegen model, %v", err)
	}
}
717253
func (p *Polygon) ReferencePoint() ReferencePoint {
	containsOrigin := false
	for _, l := range p.loops {
		containsOrigin = containsOrigin != l.ContainsOrigin()
	}
	return OriginReferencePoint(containsOrigin)
}
519390
func main() {
	if len(os.Args) < 2 {
		processes()
		return
	}

	cmd := os.Args[1]

	// See if it is a PID.
	pid, err := strconv.Atoi(cmd)
	if err == nil {
		processInfo(pid)
		return
	}

	if cmd == "help" {
		usage("")
	}

	if cmd == "tree" {
		displayProcessTree()
		return
	}

	fn, ok := cmds[cmd]
	if !ok {
		usage("unknown subcommand")
	}
	if len(os.Args) < 3 {
		usage("Missing PID or address.")
		os.Exit(1)
	}
	addr, err := targetToAddr(os.Args[2])
	if err != nil {
		fmt.Fprintf(os.Stderr, "Couldn't resolve addr or pid %v to TCPAddress: %v\n", os.Args[2], err)
		os.Exit(1)
	}
	var params []string
	if len(os.Args) > 3 {
		params = append(params, os.Args[3:]...)
	}
	if err := fn(*addr, params); err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		os.Exit(1)
	}
}
306612
func (c Client) Endpoint() endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		ctx, cancel := context.WithCancel(ctx)

		var (
			resp *http.Response
			err  error
		)
		if c.finalizer != nil {
			defer func() {
				if resp != nil {
					ctx = context.WithValue(ctx, ContextKeyResponseHeaders, resp.Header)
					ctx = context.WithValue(ctx, ContextKeyResponseSize, resp.ContentLength)
				}
				for _, f := range c.finalizer {
					f(ctx, err)
				}
			}()
		}

		req, err := http.NewRequest(c.method, c.tgt.String(), nil)
		if err != nil {
			cancel()
			return nil, err
		}

		if err = c.enc(ctx, req, request); err != nil {
			cancel()
			return nil, err
		}

		for _, f := range c.before {
			ctx = f(ctx, req)
		}

		resp, err = c.client.Do(req.WithContext(ctx))

		if err != nil {
			cancel()
			return nil, err
		}

		// If we expect a buffered stream, we don't cancel the context when the endpoint returns.
		// Instead, we should call the cancel func when closing the response body.
		if c.bufferedStream {
			resp.Body = bodyWithCancel{ReadCloser: resp.Body, cancel: cancel}
		} else {
			defer resp.Body.Close()
			defer cancel()
		}

		for _, f := range c.after {
			ctx = f(ctx, resp)
		}

		response, err := c.dec(ctx, resp)
		if err != nil {
			return nil, err
		}

		return response, nil
	}
}
503063
func EntryPointFromAuxvAMD64(auxv []byte) uint64 {
	rd := bytes.NewBuffer(auxv)

	for {
		var tag, val uint64
		err := binary.Read(rd, binary.LittleEndian, &tag)
		if err != nil {
			return 0
		}
		err = binary.Read(rd, binary.LittleEndian, &val)
		if err != nil {
			return 0
		}

		switch tag {
		case _AT_NULL_AMD64:
			return 0
		case _AT_ENTRY_AMD64:
			return val
		}
	}
}
869491
func (p *Process) Start() (err error) {
	if p.command, err = p.startProcess(); err != nil {
		return err
	}
	p.log.Debugf("New process %s was started (PID: %d)", p.GetName(), p.GetPid())

	return nil
}