Esempio n. 1
0
// Generates a dependency Makefile (.d) for the specified source C file.
//
// @param file                  The name of the source file.
func (c *Compiler) GenDepsForFile(file string) error {
	if util.NodeNotExist(c.dstDir) {
		os.MkdirAll(c.dstDir, 0755)
	}

	depFile := c.dstDir + "/" +
		strings.TrimSuffix(file, filepath.Ext(file)) + ".d"
	depFile = filepath.ToSlash(depFile)

	var cmd string
	var err error

	cmd = c.ccPath + " " + c.cflagsString() + " " + c.includesString() +
		" -MM -MG " + file + " > " + depFile
	o, err := util.ShellCommand(cmd)
	if err != nil {
		return util.NewNewtError(string(o))
	}

	// Append the extra dependencies (.yml files) to the .d file.
	f, err := os.OpenFile(depFile, os.O_APPEND|os.O_WRONLY, 0666)
	if err != nil {
		return util.NewNewtError(err.Error())
	}
	defer f.Close()

	objFile := strings.TrimSuffix(file, filepath.Ext(file)) + ".o"
	if _, err := f.WriteString(objFile + ": " + c.depsString()); err != nil {
		return util.NewNewtError(err.Error())
	}

	return nil
}
Esempio n. 2
0
func ResolveNewTargetName(name string) (string, error) {
	repoName, pkgName, err := newtutil.ParsePackageString(name)
	if err != nil {
		return "", err
	}

	if repoName != "" {
		return "", util.NewNewtError("Target name cannot contain repo; " +
			"must be local")
	}

	if pkgName == TARGET_KEYWORD_ALL {
		return "", util.NewNewtError("Target name " + TARGET_KEYWORD_ALL +
			" is reserved")
	}

	// "Naked" target names translate to "targets/<name>".
	if !strings.Contains(pkgName, "/") {
		pkgName = TARGET_DEFAULT_DIR + "/" + pkgName
	}

	if target.GetTargets()[pkgName] != nil {
		return "", util.NewNewtError("Target already exists: " + pkgName)
	}

	return pkgName, nil
}
func (cc *CoreConvert) readTlv() (*CoreDumpTlv, error) {
	var tlv CoreDumpTlv

	tlv_buf := make([]byte, binary.Size(tlv))
	if tlv_buf == nil {
		return nil, util.NewNewtError("Out of memory")
	}

	cnt, err := cc.Source.Read(tlv_buf)
	if err == io.EOF {
		return nil, nil
	}
	if err != nil {
		return nil, util.NewNewtError(fmt.Sprintf("Error reading: %s",
			err.Error()))
	}
	if cnt == 0 {
		return nil, nil
	}
	if cnt != binary.Size(tlv) {
		return nil, util.NewNewtError("Short read")
	}

	tlv.Type = uint8(tlv_buf[0])
	tlv.pad = uint8(tlv_buf[1])
	tlv.Len = binary.LittleEndian.Uint16(tlv_buf[2:4])
	tlv.Off = binary.LittleEndian.Uint32(tlv_buf[4:8])

	return &tlv, nil
}
Esempio n. 4
0
func cleanRunCmd(cmd *cobra.Command, args []string) {
	if len(args) < 1 {
		NewtUsage(cmd, util.NewNewtError("Must specify target"))
	}

	InitProject()

	cleanAll := false
	targets := []*target.Target{}
	for _, arg := range args {
		if arg == TARGET_KEYWORD_ALL {
			cleanAll = true
		} else {
			t := ResolveTarget(arg)
			if t == nil {
				NewtUsage(cmd, util.NewNewtError("invalid target name: "+arg))
			}
			targets = append(targets, t)
		}
	}

	if cleanAll {
		cleanDir(builder.BinRoot())
	} else {
		for _, t := range targets {
			cleanDir(builder.TargetBinDir(t.Name()))
		}
	}
}
Esempio n. 5
0
func EnsureWritten(pkgs []*pkg.LocalPackage, srcDir string, targetName string,
	isLoader bool) error {

	buf := bytes.Buffer{}
	write(pkgs, isLoader, &buf)

	var path string
	if isLoader {
		path = fmt.Sprintf("%s/%s-sysinit-loader.c", srcDir, targetName)
	} else {
		path = fmt.Sprintf("%s/%s-sysinit-app.c", srcDir, targetName)
	}

	writeReqd, err := writeRequired(buf.Bytes(), path)
	if err != nil {
		return err
	}

	if !writeReqd {
		log.Debugf("sysinit unchanged; not writing src file (%s).", path)
		return nil
	}

	log.Debugf("sysinit changed; writing src file (%s).", path)

	if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
		return util.NewNewtError(err.Error())
	}

	if err := ioutil.WriteFile(path, buf.Bytes(), 0644); err != nil {
		return util.NewNewtError(err.Error())
	}

	return nil
}
func DecodeFileDownloadResponse(data []byte) (*FileDownload, error) {
	type DownloadResp struct {
		Off        uint32 `json:"off"`
		Size       uint32 `json:"len"`
		Data       []byte `json:"data"`
		ReturnCode int    `json:"rc"`
	}
	resp := &DownloadResp{}

	dec := codec.NewDecoderBytes(data, new(codec.CborHandle))
	err := dec.Decode(&resp)
	if err != nil {
		return nil, util.NewNewtError(fmt.Sprintf("Invalid incoming cbor: %s",
			err.Error()))
	}
	if resp.ReturnCode != 0 {
		return nil, util.NewNewtError(fmt.Sprintf("Target error: %d",
			resp.ReturnCode))
	}
	if err != nil {
		return nil, util.NewNewtError(fmt.Sprintf("Invalid incoming json: %s",
			err.Error()))
	}
	f := &FileDownload{
		Offset: resp.Off,
		Data:   resp.Data,
		Size:   resp.Size,
	}
	return f, nil
}
Esempio n. 7
0
func (e *Echo) EncodeEchoCtrl() (*NmgrReq, error) {
	type SerialEchoCtl struct {
		Echo int `codec:"echo"`
	}

	integer, err := strconv.Atoi(e.Message)
	if err != nil {
		return nil, util.NewNewtError(fmt.Sprintf("Invalid echo ctrl setting %s",
			err.Error()))
	}
	echoCtl := &SerialEchoCtl{
		Echo: integer,
	}

	nmr, err := NewNmgrReq()
	if err != nil {
		return nil, err
	}

	nmr.Op = NMGR_OP_WRITE
	nmr.Flags = 0
	nmr.Group = NMGR_GROUP_ID_DEFAULT
	nmr.Id = NMGR_ID_CONS_ECHO_CTRL

	data := make([]byte, 0)
	enc := codec.NewEncoderBytes(&data, new(codec.CborHandle))
	if err := enc.Encode(echoCtl); err != nil {
		return nil, util.NewNewtError(fmt.Sprintf("Failed to encode message %s",
			err.Error()))
	}
	nmr.Len = uint16(len(data))
	nmr.Data = data

	return nmr, nil
}
Esempio n. 8
0
func (proj *Project) ResolvePackage(
	dfltRepo interfaces.RepoInterface, name string) (*pkg.LocalPackage, error) {
	// Trim trailing slash from name.  This is necessary when tab
	// completion is used to specify the name.
	name = strings.TrimSuffix(name, "/")

	repoName, pkgName, err := newtutil.ParsePackageString(name)
	if err != nil {
		return nil, util.FmtNewtError("invalid package name: %s (%s)", name,
			err.Error())
	}

	var repo interfaces.RepoInterface
	if repoName == "" {
		repo = dfltRepo
	} else {
		repo = proj.repos[repoName]
	}

	dep, err := pkg.NewDependency(repo, pkgName)
	if err != nil {
		return nil, util.FmtNewtError("invalid package name: %s (%s)", name,
			err.Error())
	}
	if dep == nil {
		return nil, util.NewNewtError("invalid package name: " + name)
	}
	pack := proj.ResolveDependency(dep)
	if pack == nil {
		return nil, util.NewNewtError("unknown package: " + name)
	}

	return pack.(*pkg.LocalPackage), nil
}
func (lpkg *LocalPackage) SaveSyscfgVals() error {
	dirpath := lpkg.BasePath()
	if err := os.MkdirAll(dirpath, 0755); err != nil {
		return util.NewNewtError(err.Error())
	}

	filepath := dirpath + "/" + SYSCFG_YAML_FILENAME

	syscfgVals := lpkg.SyscfgV.GetStringMapString("syscfg.vals")
	if syscfgVals == nil || len(syscfgVals) == 0 {
		os.Remove(filepath)
		return nil
	}

	file, err := os.Create(filepath)
	if err != nil {
		return util.NewNewtError(err.Error())
	}
	defer file.Close()

	names := make([]string, 0, len(syscfgVals))
	for k, _ := range syscfgVals {
		names = append(names, k)
	}
	sort.Strings(names)

	fmt.Fprintf(file, "### Package: %s\n", lpkg.Name())
	fmt.Fprintf(file, "\n")
	fmt.Fprintf(file, "syscfg.vals:\n")
	for _, name := range names {
		fmt.Fprintf(file, "    %s: %s\n", name, syscfgVals[name])
	}

	return nil
}
Esempio n. 10
0
func (r *Repo) Sync(vers *Version, force bool) (error, bool) {
	var exists bool
	var err error

	if err, exists = r.checkForceInstall(force); err != nil {
		return err, exists
	}
	if exists && !force {
		return nil, exists
	}

	// Update the repo description
	if _, updated, err := r.UpdateDesc(); updated != true || err != nil {
		return util.NewNewtError("Cannot update repository description."), exists
	}

	branchName, vers, found := r.rdesc.MatchVersion(vers)
	if found == false {
		return util.NewNewtError(fmt.Sprintf("Branch description for %s not found",
			r.Name())), exists
	}

	if err := r.downloadRepo(branchName); err != nil {
		return err, exists
	}

	return nil, exists
}
Esempio n. 11
0
func (r *Repo) Install(force bool) (*Version, error) {
	if err, exists := r.checkForceInstall(force); err != nil || exists {
		if err == nil {
			if !force {
				return nil, util.NewNewtError(fmt.Sprintf(
					"Repository %s already exists, provide the -f option "+
						"to overwrite", r.Name()))
			}
		} else {
			return nil, err
		}
	}

	branchName, vers, found := r.rdesc.Match(r)
	if !found {
		return nil, util.NewNewtError(fmt.Sprintf("No repository matching description %s found",
			r.rdesc.String()))
	}

	if err := r.downloadRepo(branchName); err != nil {
		return nil, err
	}

	return vers, nil
}
Esempio n. 12
0
/* this create a new library combining all of the other libraries */
func createSplitArchiveLinkerFile(archiveFile string,
	archFiles []string) error {

	/* create a name for this script */
	ar_script_name := linkerScriptFileName(archiveFile)

	// open the file and write out the script
	f, err := os.OpenFile(ar_script_name, os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		return util.NewNewtError(err.Error())
	}
	defer f.Close()

	if _, err := f.WriteString("CREATE " + archiveFile + "\n"); err != nil {
		return util.NewNewtError(err.Error())
	}

	for _, arch := range archFiles {
		if _, err := f.WriteString("ADDLIB " + arch + "\n"); err != nil {
			return util.NewNewtError(err.Error())
		}
	}

	if _, err := f.WriteString("SAVE\n"); err != nil {
		return util.NewNewtError(err.Error())
	}

	if _, err := f.WriteString("END\n"); err != nil {
		return util.NewNewtError(err.Error())
	}

	return nil
}
Esempio n. 13
0
func (proj *Project) loadConfig() error {
	v, err := util.ReadConfig(proj.BasePath,
		strings.TrimSuffix(PROJECT_FILE_NAME, ".yml"))
	if err != nil {
		return util.NewNewtError(err.Error())
	}
	// Store configuration object for access to future values,
	// this avoids keeping every string around as a project variable when
	// we need to process it later.
	proj.v = v

	proj.projState, err = LoadProjectState()
	if err != nil {
		return err
	}

	proj.name = v.GetString("project.name")

	// Local repository always included in initialization
	r, err := repo.NewLocalRepo(proj.name)
	if err != nil {
		return err
	}

	proj.repos[proj.name] = r
	proj.localRepo = r
	for _, ignDir := range ignoreSearchDirs {
		r.AddIgnoreDir(ignDir)
	}

	rstrs := v.GetStringSlice("project.repositories")
	for _, repoName := range rstrs {
		if err := proj.loadRepo(repoName, v); err != nil {
			return err
		}
	}

	ignoreDirs := v.GetStringSlice("project.ignore_dirs")
	for _, ignDir := range ignoreDirs {
		repoName, dirName, err := newtutil.ParsePackageString(ignDir)
		if err != nil {
			return err
		}
		if repoName == "" {
			r = proj.LocalRepo()
		} else {
			r = proj.FindRepo(repoName)
		}
		if r == nil {
			return util.NewNewtError(
				fmt.Sprintf("ignore_dirs: unknown repo %s", repoName))
		}
		r.AddIgnoreDir(dirName)
	}

	return nil
}
Esempio n. 14
0
func (cc *CoreConvert) Convert() error {
	if cc.Source == nil || cc.Target == nil {
		return util.NewNewtError("Missing file parameters")
	}

	err := cc.readHdr()
	if err != nil {
		return err
	}

	for {
		tlv, err := cc.readTlv()
		if err != nil {
			return err
		}
		if tlv == nil {
			break
		}
		data_buf := make([]byte, tlv.Len)
		cnt, err := cc.Source.Read(data_buf)
		if err != nil {
			return util.NewNewtError(fmt.Sprintf("Error reading: %s",
				err.Error()))
		}
		if cnt != int(tlv.Len) {
			return util.NewNewtError("Short file")
		}
		switch tlv.Type {
		case COREDUMP_TLV_MEM:
			cc.makeProgHdr(tlv.Off, data_buf)
		case COREDUMP_TLV_IMAGE:
			cc.ImageHash = data_buf
		case COREDUMP_TLV_REGS:
			if tlv.Len%4 != 0 {
				return util.NewNewtError("Invalid register area size")
			}
			cc.makeRegInfo(data_buf)
		default:
			return util.NewNewtError("Unknown TLV type")
		}
	}
	cc.makeElfHdr()
	if err != nil {
		return err
	}
	cc.setProgHdrOff()

	binary.Write(cc.Target, binary.LittleEndian, cc.elfHdr)
	for _, phdr := range cc.phdrs {
		binary.Write(cc.Target, binary.LittleEndian, phdr)
	}
	for _, data := range cc.data {
		cc.Target.Write(data)
	}
	return nil
}
Esempio n. 15
0
func dateTimeCmd(cmd *cobra.Command, args []string) {
	runner, err := getTargetCmdRunner()
	if err != nil {
		nmUsage(cmd, err)
	}
	defer runner.Conn.Close()

	dateTime, err := protocol.NewDateTime()
	if err != nil {
		nmUsage(cmd, err)
	}

	if len(args) > 0 {
		dateTime.DateTime = args[0]
	}
	nmr, err := dateTime.EncodeRequest()
	if err != nil {
		nmUsage(cmd, err)
	}

	if err := runner.WriteReq(nmr); err != nil {
		nmUsage(cmd, err)
	}

	rsp, err := runner.ReadResp()
	if err != nil {
		nmUsage(cmd, err)
	}

	iRsp, err := protocol.DecodeDateTimeResponse(rsp.Data)
	if err != nil {
		nmUsage(cmd, err)
	}

	err_str := "Command: datetime\n" +
		"For writing datetime <argument>\n" +
		"Need to specify a datetime in RFC 3339 format\n" +
		"2016-03-02T22:44:00                  UTC time (implicit)\n" +
		"2016-03-02T22:44:00Z                 UTC time (explicit)\n" +
		"2016-03-02T22:44:00-08:00            PST timezone\n" +
		"2016-03-02T22:44:00.1                fractional seconds\n" +
		"2016-03-02T22:44:00.101+05:30        fractional seconds with timezone\n"

	if len(args) > 1 {
		nmUsage(cmd, util.NewNewtError(err_str))
	} else if len(args) == 1 {
		if iRsp.Return != 0 {
			nmUsage(cmd, util.NewNewtError(fmt.Sprintf("Return:%d\n%s",
				iRsp.Return, err_str)))
		} else {
			fmt.Println("Return:", iRsp.Return)
		}
	} else if len(args) == 0 {
		fmt.Println("Datetime(RFC 3339 format):", iRsp.DateTime)
	}
}
Esempio n. 16
0
/*
 * Not able to install custom decoder for indefite length objects with the codec.
 * So we need to decode the whole response, and then re-encode the newtmgr response
 * part.
 */
func DeserializeOmgrReq(data []byte) (*NmgrReq, error) {
	req := coap.Message{}
	err := req.UnmarshalBinary(data)
	if err != nil {
		return nil, util.NewNewtError(fmt.Sprintf(
			"Oicmgr request invalid %s", err.Error()))
	}
	if req.Code == coap.GET || req.Code == coap.PUT {
		return nil, nil
	}
	if req.Code != coap.Created && req.Code != coap.Deleted &&
		req.Code != coap.Valid && req.Code != coap.Changed &&
		req.Code != coap.Content {
		return nil, util.NewNewtError(fmt.Sprintf(
			"OIC error rsp: %s", req.Code.String()))
	}

	var rsp OicRsp
	err = codec.NewDecoderBytes(req.Payload, new(codec.CborHandle)).Decode(&rsp)
	if err != nil {
		return nil, util.NewNewtError(fmt.Sprintf("Invalid incoming cbor: %s",
			err.Error()))
	}
	log.Debugf("Deserialized response %+v", rsp)

	nmr := &NmgrReq{}

	var ndata []byte = make([]byte, 0)

	if rsp.Read != nil {
		err = codec.NewEncoderBytes(&ndata,
			new(codec.CborHandle)).Encode(rsp.Read)
		nmr.Op = NMGR_OP_READ_RSP
	} else {
		err = codec.NewEncoderBytes(&ndata,
			new(codec.CborHandle)).Encode(rsp.Write)
		nmr.Op = NMGR_OP_WRITE_RSP
	}
	if err != nil {
		return nil, util.NewNewtError(fmt.Sprintf("Internal error: %s",
			err.Error()))
	}

	nmr.Len = uint16(len(ndata))
	nmr.Flags = 0
	nmr.Group = 0
	nmr.Seq = 0
	nmr.Id = 0

	nmr.Data = ndata

	log.Debugf("Deserialized response %+v", nmr)

	return nmr, nil
}
Esempio n. 17
0
func (b *Builder) Load(imageSlot int, extraJtagCmd string) error {
	if b.appPkg == nil {
		return util.NewNewtError("app package not specified")
	}

	/* Populate the package list and feature sets. */
	err := b.targetBuilder.PrepBuild()
	if err != nil {
		return err
	}

	envSettings := map[string]string{
		"IMAGE_SLOT": strconv.Itoa(imageSlot),
		"FEATURES":   b.FeatureString(),
	}
	if extraJtagCmd != "" {
		envSettings["EXTRA_JTAG_CMD"] = extraJtagCmd
	}
	features := b.cfg.Features()

	var flashTargetArea string
	if _, ok := features["BOOT_LOADER"]; ok {
		envSettings["BOOT_LOADER"] = "1"

		flashTargetArea = "FLASH_AREA_BOOTLOADER"
		util.StatusMessage(util.VERBOSITY_DEFAULT,
			"Loading bootloader\n")
	} else {
		if imageSlot == 0 {
			flashTargetArea = "FLASH_AREA_IMAGE_0"
		} else if imageSlot == 1 {
			flashTargetArea = "FLASH_AREA_IMAGE_1"
		}
		util.StatusMessage(util.VERBOSITY_DEFAULT,
			"Loading %s image into slot %d\n", b.buildName, imageSlot+1)
	}

	bspPkg := b.targetBuilder.bspPkg
	tgtArea := bspPkg.FlashMap.Areas[flashTargetArea]
	if tgtArea.Name == "" {
		return util.NewNewtError(fmt.Sprintf("No flash target area %s\n",
			flashTargetArea))
	}
	envSettings["FLASH_OFFSET"] = "0x" + strconv.FormatInt(int64(tgtArea.Offset), 16)

	if err := Load(b.AppBinBasePath(), b.targetBuilder.bspPkg,
		envSettings); err != nil {

		return err
	}

	util.StatusMessage(util.VERBOSITY_VERBOSE, "Successfully loaded image.\n")

	return nil
}
Esempio n. 18
0
func (proj *Project) upgradeCheck(r *repo.Repo, vers *repo.Version,
	force bool) (bool, error) {
	rdesc, err := r.GetRepoDesc()
	if err != nil {
		return false, err
	}

	branch, newVers, _ := rdesc.Match(r)
	if newVers == nil {
		util.StatusMessage(util.VERBOSITY_DEFAULT,
			"No matching version to upgrade to "+
				"found for %s.  Please check your project requirements.",
			r.Name())
		return false, util.NewNewtError(fmt.Sprintf("Cannot find a "+
			"version of repository %s that matches project requirements.",
			r.Name()))
	}

	// If the change between the old repository and the new repository would cause
	// and upgrade.  Then prompt for an upgrade response, unless the force option
	// is present.
	if vers.CompareVersions(newVers, vers) != 0 ||
		vers.Stability() != newVers.Stability() {
		if !force {
			str := ""
			if newVers.Stability() != repo.VERSION_STABILITY_NONE {
				str += "(" + branch + ")"
			}

			fmt.Printf("Would you like to upgrade repository %s from %s to %s %s? [Yn] ",
				r.Name(), vers.String(), newVers.String(), str)
			line, more, err := bufio.NewReader(os.Stdin).ReadLine()
			if more || err != nil {
				return false, util.NewNewtError(fmt.Sprintf(
					"Couldn't read upgrade response: %s\n", err.Error()))
			}

			// Anything but no means yes.
			answer := strings.ToUpper(strings.Trim(string(line), " "))
			if answer == "N" || answer == "NO" {
				fmt.Printf("User says don't upgrade, skipping upgrade of %s\n",
					r.Name())
				return true, nil
			}
		}
	} else {
		util.StatusMessage(util.VERBOSITY_VERBOSE,
			"Repository %s doesn't need to be upgraded, latest "+
				"version installed.\n", r.Name())
		return true, nil
	}

	return false, nil
}
Esempio n. 19
0
func (cs *ConnUDP) WritePacket(pkt *Packet) error {
	if cs.conn == nil {
		return util.NewNewtError("Connection not open")
	}

	_, err := cs.conn.WriteTo(pkt.GetBytes(), cs.dst)
	if err != nil {
		return util.NewNewtError(fmt.Sprintf("failed to write: %s",
			err.Error()))
	}
	return nil
}
Esempio n. 20
0
func (target *Target) Validate(appRequired bool) error {
	if target.BspName == "" {
		return util.NewNewtError("Target does not specify a BSP package " +
			"(target.bsp)")
	}
	bsp := target.resolvePackageName(target.BspName)
	if bsp == nil {
		return util.FmtNewtError("Could not resolve BSP package: %s",
			target.BspName)
	}

	if bsp.Type() != pkg.PACKAGE_TYPE_BSP {
		return util.FmtNewtError("bsp package (%s) is not of "+
			"type bsp; type is: %s\n", bsp.Name(),
			pkg.PackageTypeNames[bsp.Type()])
	}

	if appRequired {
		if target.AppName == "" {
			return util.NewNewtError("Target does not specify an app " +
				"package (target.app)")
		}
		app := target.resolvePackageName(target.AppName)
		if app == nil {
			return util.FmtNewtError("Could not resolve app package: %s",
				target.AppName)
		}

		if app.Type() != pkg.PACKAGE_TYPE_APP {
			return util.FmtNewtError("target.app package (%s) is not of "+
				"type app; type is: %s\n", app.Name(),
				pkg.PackageTypeNames[app.Type()])
		}

		if target.LoaderName != "" {
			loader := target.resolvePackageName(target.LoaderName)
			if loader == nil {
				return util.FmtNewtError(
					"Could not resolve loader package: %s", target.LoaderName)
			}

			if loader.Type() != pkg.PACKAGE_TYPE_APP {
				return util.FmtNewtError(
					"target.loader package (%s) is not of type app; type "+
						"is: %s\n", loader.Name(),
					pkg.PackageTypeNames[loader.Type()])
			}
		}
	}

	return nil
}
Esempio n. 21
0
// Compiles and archives a package.
func (b *Builder) buildPackage(bpkg *BuildPackage) error {
	c, err := b.newCompiler(bpkg, b.PkgBinDir(bpkg))
	if err != nil {
		return err
	}

	srcDirs := []string{}

	if len(bpkg.SourceDirectories) > 0 {
		for _, relDir := range bpkg.SourceDirectories {
			dir := bpkg.BasePath() + "/" + relDir
			if util.NodeNotExist(dir) {
				return util.NewNewtError(fmt.Sprintf(
					"Specified source directory %s, does not exist.",
					dir))
			}
			srcDirs = append(srcDirs, dir)
		}
	} else {
		srcDir := bpkg.BasePath() + "/src"
		if util.NodeNotExist(srcDir) {
			// Nothing to compile.
			return nil
		}

		srcDirs = append(srcDirs, srcDir)
	}

	// Make sure we restore the current working dir to whatever it was when this function was called
	cwd, err := os.Getwd()
	if err != nil {
		return util.NewNewtError(fmt.Sprintf("Unable to determine current working directory: %v", err))
	}
	defer os.Chdir(cwd)

	for _, dir := range srcDirs {
		if err = buildDir(dir, c, b.targetBuilder.bspPkg.Arch, nil); err != nil {
			return err
		}
	}

	// Create a static library ("archive").
	if err := os.Chdir(bpkg.BasePath() + "/"); err != nil {
		return util.NewNewtError(err.Error())
	}
	archiveFile := b.ArchivePath(bpkg)
	if err = c.CompileArchive(archiveFile); err != nil {
		return err
	}

	return nil
}
Esempio n. 22
0
func LoadVersion(versStr string) (*Version, error) {
	var err error

	// Split to get stability level first
	sparts := strings.Split(versStr, "-")
	stability := VERSION_STABILITY_NONE
	if len(sparts) > 1 {
		stability = strings.Trim(sparts[1], " ")
		switch stability {
		case VERSION_STABILITY_STABLE:
			fallthrough
		case VERSION_STABILITY_DEV:
			fallthrough
		case VERSION_STABILITY_LATEST:
		default:
			return nil, util.NewNewtError(
				fmt.Sprintf("Unknown stability (%s) in version ", stability) + versStr)
		}
	}

	parts := strings.Split(sparts[0], ".")
	if len(parts) > 3 {
		return nil, util.NewNewtError(fmt.Sprintf("Invalid version string: %s", versStr))
	}

	if strings.Trim(parts[0], " ") == "" || strings.Trim(parts[0], " ") == "none" {
		return nil, nil
	}

	vers := &Version{}
	vers.stability = stability

	// convert first string to an int
	if vers.major, err = strconv.ParseInt(parts[0], 10, 64); err != nil {
		return nil, util.NewNewtError(err.Error())
	}
	if len(parts) >= 2 {
		if vers.minor, err = strconv.ParseInt(parts[1], 10, 64); err != nil {
			return nil, util.NewNewtError(err.Error())
		}
	}
	if len(parts) == 3 {
		if vers.revision, err = strconv.ParseInt(parts[2], 10, 64); err != nil {
			return nil, util.NewNewtError(err.Error())
		}
	}

	return vers, nil
}
func DecodeFileUploadResponse(data []byte) (*FileUpload, error) {
	f := &FileUpload{}

	dec := codec.NewDecoderBytes(data, new(codec.CborHandle))
	err := dec.Decode(&f)
	if err != nil {
		return nil, util.NewNewtError(fmt.Sprintf("Invalid incoming cbor: %s",
			err.Error()))
	}
	if f.ReturnCode != 0 {
		return nil, util.NewNewtError(fmt.Sprintf("Target error: %d",
			f.ReturnCode))
	}
	return f, nil
}
Esempio n. 24
0
func (gd *GithubDownloader) FetchFile(name string, dest string) error {
	url := fmt.Sprintf("https://api.github.com/repos/%s/%s/contents/%s?ref=%s",
		gd.User, gd.Repo, name, gd.Branch())

	req, err := http.NewRequest("GET", url, nil)
	req.Header.Add("Accept", "application/vnd.github.v3.raw")

	if gd.Token != "" {
		// XXX: Add command line option to include token in log.
		log.Debugf("Using authorization token")
		req.Header.Add("Authorization", "token "+gd.Token)
	} else if gd.Login != "" && gd.Password != "" {
		// XXX: Add command line option to include password in log.
		log.Debugf("Using basic auth; login=%s", gd.Login)
		req.SetBasicAuth(gd.Login, gd.Password)
	}

	log.Debugf("Fetching file %s (url: %s) to %s", name, url, dest)
	client := &http.Client{}
	rsp, err := client.Do(req)
	if err != nil {
		return util.NewNewtError(err.Error())
	}
	defer rsp.Body.Close()

	if rsp.StatusCode != http.StatusOK {
		errMsg := fmt.Sprintf("Failed to download '%s'; status=%s",
			url, rsp.Status)
		switch rsp.StatusCode {
		case http.StatusNotFound:
			errMsg += "; URL incorrect or repository private?"
		case http.StatusUnauthorized:
			errMsg += "; credentials incorrect?"
		}

		return util.NewNewtError(errMsg)
	}

	handle, err := os.Create(dest)
	if err != nil {
		return util.NewNewtError(err.Error())
	}
	defer handle.Close()

	_, err = io.Copy(handle, rsp.Body)

	return nil
}
Esempio n. 25
0
// Save the target's configuration elements
func (t *Target) Save() error {
	if err := t.basePkg.Save(); err != nil {
		return err
	}

	dirpath := t.basePkg.BasePath()
	filepath := dirpath + "/" + TARGET_FILENAME
	file, err := os.Create(filepath)
	if err != nil {
		return util.NewNewtError(err.Error())
	}
	defer file.Close()

	file.WriteString("### Target: " + t.Name() + "\n")

	keys := []string{}
	for k, _ := range t.Vars {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	for _, k := range keys {
		file.WriteString(k + ": " + yaml.EscapeString(t.Vars[k]) + "\n")
	}

	if err := t.basePkg.SaveSyscfgVals(); err != nil {
		return err
	}

	return nil
}
Esempio n. 26
0
func newConn(cp config.NewtmgrConnProfile, readTimeout time.Duration) (Conn, error) {
	// Based on ConnProfile, instantiate the right type of conn object, that
	// implements the conn interface.
	var c Conn
	switch cp.Type() {
	case "serial":
		c = &ConnSerial{}
		c.SetOICEncoded(false)
	case "oic_serial":
		c = &ConnSerial{}
		c.SetOICEncoded(true)
	case "ble":
		c = &ConnBLE{}
		c.SetOICEncoded(false)
	case "oic_ble":
		c = &ConnBLE{}
		c.SetOICEncoded(true)
	case "udp":
		c = &ConnUDP{}
		c.SetOICEncoded(false)
	case "oic_udp":
		c = &ConnUDP{}
		c.SetOICEncoded(true)
	default:
		return nil, util.NewNewtError("Invalid conn profile " + cp.Type() +
			" not implemented")
	}

	if err := c.Open(cp, readTimeout); err != nil {
		return nil, err
	}
	return c, nil
}
Esempio n. 27
0
func (t *TargetBuilder) PrepBuild() error {
	cfgResolution, err := t.ExportCfg()
	if err != nil {
		return err
	}

	flashErrText := t.bspPkg.FlashMap.ErrorText()
	if flashErrText != "" {
		return util.NewNewtError(flashErrText)
	}

	if err := t.validateAndWriteCfg(cfgResolution); err != nil {
		return err
	}

	loaderPkgs, appPkgs, err := t.resolvePkgs(cfgResolution)
	if err != nil {
		return err
	}

	if loaderPkgs != nil {
		t.LoaderBuilder, err = NewBuilder(t, BUILD_NAME_LOADER, loaderPkgs,
			cfgResolution.ApiMap, cfgResolution.Cfg)
		if err != nil {
			return err
		}
		if err := t.LoaderBuilder.PrepBuild(); err != nil {
			return err
		}

		loaderFlags := toolchain.NewCompilerInfo()
		loaderFlags.Cflags = append(loaderFlags.Cflags, "-DSPLIT_LOADER")
		t.LoaderBuilder.AddCompilerInfo(loaderFlags)

		t.LoaderList = project.ResetDeps(nil)
	}

	t.AppBuilder, err = NewBuilder(t, BUILD_NAME_APP, appPkgs,
		cfgResolution.ApiMap, cfgResolution.Cfg)
	if err != nil {
		return err
	}
	if err := t.AppBuilder.PrepBuild(); err != nil {
		return err
	}

	if loaderPkgs != nil {
		appFlags := toolchain.NewCompilerInfo()
		appFlags.Cflags = append(appFlags.Cflags, "-DSPLIT_APPLICATION")
		t.AppBuilder.AddCompilerInfo(appFlags)
	}

	t.AppList = project.ResetDeps(nil)

	if err := t.generateCode(cfgResolution); err != nil {
		return err
	}

	return nil
}
Esempio n. 28
0
// Merge - merges given maps into 1 map
// values will be overridden by last matching key - value
func (s1 *SymbolMap) Merge(s2 *SymbolMap) (*SymbolMap, error) {

	for k, v := range *s2 {

		if val, ok := (*s1)[k]; ok {
			/* We already have this in the MAP */
			if val.IsWeak() && !v.IsWeak() {
				(*s1)[k] = v
			} else if v.IsWeak() && !val.IsWeak() {
				/* nothing to do here as this is OK not to replace */
			} else if v.IsLocal() && val.IsLocal() {
				/* two locals that must conflict with name */
				/* have to have separate instances of these */
				util.StatusMessage(util.VERBOSITY_VERBOSE,
					"Local Symbol Conflict: %s from packages %s and %s \n",
					v.Name, v.Bpkg, val.Bpkg)
				(*s2).Remove(k)
			} else {
				util.StatusMessage(util.VERBOSITY_QUIET,
					"Global Symbol Conflict: %s from packages %s and %s \n",
					v.Name, v.Bpkg, val.Bpkg)
				return nil, util.NewNewtError("Global Symbol Conflict")
			}
		} else {
			(*s1)[k] = v
		}

	}
	return s1, nil
}
Esempio n. 29
0
func Read(ymlFlashMap map[string]interface{}) (FlashMap, error) {
	flashMap := newFlashMap()

	ymlAreas := ymlFlashMap["areas"]
	if ymlAreas == nil {
		return flashMap, util.NewNewtError(
			"\"areas\" mapping missing from flash map definition")
	}

	areaMap := cast.ToStringMap(ymlAreas)
	for k, v := range areaMap {
		if _, ok := flashMap.Areas[k]; ok {
			return flashMap, flashAreaErr(k, "name conflict")
		}

		ymlArea := cast.ToStringMap(v)
		area, err := parseFlashArea(k, ymlArea)
		if err != nil {
			return flashMap, flashAreaErr(k, err.Error())
		}

		flashMap.Areas[k] = area
	}

	flashMap.detectOverlaps()

	return flashMap, nil
}
Esempio n. 30
0
// Links the specified elf file and generates some associated artifacts (lst,
// bin, and map files).
//
// @param binFile               The filename of the destination elf file to
//                                  link.
// @param options               Some build options specifying how the elf file
//                                  gets generated.
// @param objFiles              An array of the source .o and .a filenames.
func (c *Compiler) CompileElf(binFile string, objFiles []string,
	keepSymbols []string, elfLib string) error {
	options := map[string]bool{"mapFile": c.ldMapFile,
		"listFile": true, "binFile": c.ldBinFile}

	// Make sure the compiler package info is added to the global set.
	c.ensureLclInfoAdded()

	linkRequired, err := c.depTracker.LinkRequired(binFile, options,
		objFiles, keepSymbols, elfLib)
	if err != nil {
		return err
	}
	if linkRequired {
		if err := os.MkdirAll(filepath.Dir(binFile), 0755); err != nil {
			return util.NewNewtError(err.Error())
		}
		err := c.CompileBinary(binFile, options, objFiles, keepSymbols, elfLib)
		if err != nil {
			return err
		}
	}

	err = c.generateExtras(binFile, options)
	if err != nil {
		return err
	}

	return nil
}