view python/ppci/objectfile.py @ 368:d2ddfe134c48

Remove yield from for python < 3.3
author Windel Bouwman
date Fri, 21 Mar 2014 11:21:50 +0100
parents 86b02c98a717
children 9667d78ba79e
line wrap: on
line source


"""
Object files are used to store assembled code. Information contained
is code, symbol table and relocation information.
"""

from . import CompilerError

class Symbol:
    def __init__(self, name, value, section):
        self.name = name
        self.value = value
        self.section = section

    def __repr__(self):
        return 'SYM {}, val={} sec={}'.format(self.name, self.value, self.section)


class Relocation:
    """ Represents a relocation entry. A relocation always has a symbol to refer to
     and a relocation type """
    def __init__(self, sym, offset, typ, section):
        self.sym = sym
        self.offset = offset
        self.typ = typ
        self.section = section

    def __repr__(self):
        return 'RELOC {} off={} t={} sec={}'.format(self.sym, self.offset, self.typ, self.section)


class Section:
    def __init__(self, name):
        self.name = name
        self.address = 0
        self.data = bytearray()

    def add_data(self, data):
        self.data += data

    @property
    def Size(self):
        return len(self.data)

    def __repr__(self):
        return 'SECTION {}'.format(self.name)


class ObjectFile:
    """ Container for sections with compiled code or data.
        Also contains symbols and relocation entries """
    def __init__(self):
        self.symbols = {}
        self.sections = {}
        self.relocations = []

    def find_symbol(self, name):
        return self.symbols[name]

    def add_symbol(self, name, value, section):
        if name in self.symbols:
            raise CompilerError('{} already defined'.format(name))
        assert section in self.sections
        sym = Symbol(name, value, section)
        self.symbols[name] = sym
        return sym

    def add_relocation(self, sym_name, offset, typ, section):
        assert type(sym_name) is str, str(sym_name)
        assert section in self.sections
        reloc = Relocation(sym_name, offset, typ, section)
        self.relocations.append(reloc)
        return reloc

    def get_section(self, name):
        if not name in self.sections:
            self.sections[name] = Section(name)
        return self.sections[name]