Example #1
0
func (this *Processor) loadInstructionsMemory(assemblyFileName string) error {

	logger.Print(" => Reading hex file: %s", assemblyFileName)
	lines, err := utils.ReadLines(assemblyFileName)
	if err != nil {
		return err
	}

	address := uint32(0)
	for _, line := range lines {

		// Split hex value and humand readable comment
		parts := strings.Split(line, "//")

		// Save human readable for debugging purposes
		if len(parts) > 1 {
			this.InstructionsMap()[address] = strings.TrimSpace(parts[1])
		}

		// Reach pre-filled memory data lines
		if strings.Contains(line, "@0x") {
			parts := strings.Split(strings.Replace(line, "@0x", "", -1), ":")
			err = this.processPreFilledDataMemoryLine(parts[0], strings.Split(parts[1], " "))
			if err != nil {
				return errors.New(fmt.Sprintf("Failed parsing memory macro. %s", err.Error()))
			}
			continue
		}

		// Save hex value into instructions memory
		bytes, err := hex.DecodeString(strings.TrimSpace(parts[0]))
		if err != nil {
			return errors.New(fmt.Sprintf("Failed parsing instruction (hex) value: %s. %s", parts[0], err.Error()))
		}
		this.InstructionsMemory().Store(address, bytes...)

		// Increment address
		address += uint32(len(bytes))
	}
	for i := address; i < this.InstructionsMemory().Size(); i++ {
		this.InstructionsMemory().Store(i, []byte{consts.ENDING_BYTE}...)
	}
	return nil
}
func TranslateFromFile(filename string, outputFilename string) (string, error) {

	// Read lines from file
	logger.Print(" => Reading assembly file: %s", filename)
	lines, err := utils.ReadLines(filename)
	if err != nil {
		return "", err
	}

	// Create output file
	f, err := os.Create(outputFilename)
	if err != nil {
		return "", err
	}
	defer f.Close()

	// Clean lines, remove labels and get map of labels
	memory, lines, labels := getLinesAndMapLabels(lines)

	// Print pre-filled memory macros
	for _, line := range memory {
		f.WriteString(fmt.Sprintf("%s\n", line))
	}

	// Translate instructions
	instructionSet := set.Init()
	for i, line := range lines {
		instruction, err := instructionSet.GetInstructionFromString(line, uint32(i)*consts.BYTES_PER_WORD, labels)
		if err != nil {
			return "", errors.New(fmt.Sprintf("Failed translating line %d: %s. %s", i, line, err.Error()))
		}
		hex := fmt.Sprintf("%08X", instruction.ToUint32())
		f.WriteString(fmt.Sprintf("%s // 0x%04X => %s\n", hex, i*consts.BYTES_PER_WORD, strings.Replace(line, "\t", " ", -1)))
	}
	logger.Print(" => Output hex file: %s", outputFilename)
	return outputFilename, nil
}