API Documentation

This section is about the internals of the msp430.asm module. It may be interesting for developers that work on this module or who are interested in using the functions the module provides in their own code.

Object file format

The file format of .o4 files is a bit unusual. It actually contains something that could be labeled as (specialized) Forth code. So the linker is some sort of Forth interpreter. This has the advantage that the object files can be debugged without any special tools, just a text editor. It also makes the format quite universal; it could produce binaries for all sorts of CPUs (single special case: the directive JMP is MSP430 specific).

A list of supported words can be found in the following document:

For more details also take a look at the sources of ld.py.

MCU Definition file format

MCU memory definitions can be provided in a file with Forth like syntax.

A list of supported words can be found in the following document:

For more details also take a look at the sources of mcu_definition_parser.py.



This module implements the MSP430(X) assembler. When the module is executed (e.g. using python -m msp430.asm.as), it acts as a command line tool.

class msp430.asm.as.MSP430Assembler
__init__(msp430x=False, debug=False)
  • msp430x – Set to true to enable MSP430X instruction set.
  • debug – When set to true dump some internal data so sys.stderr while compiling.

Create an instance of the assembler.

assemble(f, filename=None, output=sys.stdout)
  • f – A file like object that supports iterating over lines.
  • filename – An optional string that is used in error messages.
  • output – File like object used to write the object code to.

This method takes assembler source and transforms it to object code that can be forwarded to the linker.

exception msp430.asm.as.AssemblerError

This instances of this class are raised by the MSP430Assembler in case of errors in the source. It may be annotated with the source filename and line number where the error occurred.



This module implements the linker. When the module is executed (e.g. using python -m msp430.asm.ld), it acts as a command line tool.

class msp430.asm.ld.Segment
__init__(name, start_address=None, end_address=None, align=True, programmable=False, little_endian=True, parent=None, mirror_of=None)
Parameters:segment_name – name of an sub segment.
Raises:KeyError – when no segment with given name is found

Easy access to subsegment by name.

Parameters:by_address – Sort by address if true, otherwise sort by name.

Sort list of subsegments either by order of definition or by order of start address.


Clear data. Recursively with all subsegments. Segments are not removed, just their data.


Get the number of data bytes contained in the segment.


Compare function that allows to sort segments by their start_address.


Compare function that allows to sort segments by their start_address.

print_tree(output, indent='', hide_empty=False)
  • output – a file like object (supporting write)
  • indent – a prefix put before each line.
  • hide_empty – when set to true omit empty segments (no data) in output.

Output segment and subsegments.


Modify start- and end_address of segment to fit the data that it contains. Recursively applied to the tree of segments. Typically called with address=None.

Parameters:value – an integer (8 significant bits)

Write one byte.

Parameters:value – an integer (16 significant bits)

Write two bytes. Order in memory depends on endianness of segment.

Parameters:value – an integer (32 significant bits)

Write four bytes. Order in memory depends on endianness of segment.

class msp430.asm.ld.Linker
Parameters:instructions – list of directives for the linker

Initialize a linker instance. The given instructions are essentially what is read from a .o4 file as sequence of words.

Parameters:segment_definitions – dictionary describing the memory map

This sets the memory map used for linking. See mcu_definition_parser for a way to load this description.


Called before writing the final output. In case the memory map contains segments that mirror the contents of other segments, they are updated. This is typically used for .data_init which contains the initial values that are copied by startup code to the .data segment in RAM.


Run the linkers 1st pass. It iterates through the instructions and places the data into segments.


Run the linkers 2nd pass. It iterates through the instructions and finds all the labels and saves their position.


Run the linkers 3rd pass. It iterates through the instructions and creates the final binary with all known labels set to their target address.

exception msp430.asm.ld.LinkError

Exception object raised when errors during linking occur. May be annotated with the location of the line within the original source file causing the error.



This module implements the preprocessor. When the module is executed (e.g. using python -m msp430.asm.cpp), it acts as a command line tool.


Given an iterator for lines, yield lines. It joins consecutive lines with the continuation marker (\\) to a single line.

class msp430.asm.cpp.AnnoatatedLineWriter

This object is used by the preprocessor to write out the preprocessed text. It adds notes in the form #line <line> "<filename>". These notes are used by the assembler to know where a source line originally came from (as preprocessed text may contain additional lines etc.)

__init__(output, filename)
  • output – file like object to write to
  • filename – the filename used in the notes
write(lineno, text)
  • linno – line number being written
  • text – the actual contents of the line
class msp430.asm.cpp.Preprocessor
preprocess(infile, outfile, filename)
  • infile – file like object to read from
  • outfile – file like object to write to
  • filename – original file name of the input (infile)

This runs the preprocessor over the given input.

exception msp430.asm.cpp.PreprocessorError

Exception object raised when errors during preprocessing occur.


This module implements the disassembler. When the module is executed (e.g. using python -m msp430.asm.disassemble), it acts as a command line tool.

class msp430.asm.disassemble.MSP430Disassembler
__init__(memory, msp430x=False, named_symbols=None)
  • memory – A msp43.memory.Memory instance containing the binary.
  • msp430x – Set to true to enable MSP430X instruction set.
  • named_symbols – An (optional) instance of NamedSymbols which is used to label peripherals and bits.

Initialize the disassembler with data.

disassemble(output, source_only=False)
  • output – A file like object used for the resulting text.
  • source_only – When set to true, the address and data columns are omitted from the output.

Run the disassembler, result is written to output.


This module implements the an RPN calculator. The calculator can be tested by executing the module (e.g. using python -m msp430.asm.rpn).

class msp430.asm.rpn.Word(unicode)

This class is used to wrap words so that their source location can be tracked. This is useful for error messages.

__new__(cls, word, filename, lineno, text)
  • cls – Class for __new__
  • word – The word (unicode)
  • filename (unicode or None) – Filename where the word was read from.
  • lineno (int or None) – Line number within the file.
  • text (unicode or None) – The complete line (or context).

Create new instance with a word that was read from given location.

class msp430.asm.rpn.RPN

An RPN calculator. It provides a data stack and implements a number of basic operations (arithmetical and stack)

Parameters:next_word – A function return the next word from input when called.

Interpret a sequence of words given by the iterator next_word.

msp430.asm.rpn.annotated_words(sequence, filename=None, lineno=None, offset=None, text=None)

Create an generator for Word, all annotated with the given information.

msp430.asm.rpn.words_in_string(data, name='<string>')
  • data – String with (lines) of text.
  • name – Optional name, used in error messages.

Create a generator for annotated Word in string (splitlines() is used).

Parameters:filename – Name of a file to read from.

Create a generator for annotated Word read from file given by name.

Parameters:code – A string in RPN notation
Returns:A Python function.

Return a wrapper - a function that evaluates the given RPN code when called. This can be used to insert functions implemented as RPN into the name space.


Function decorator used to tag methods that will be visible in the RPN built-in name space.

msp430.asm.rpn.val(words, stack=[], namespace={})
  • words – Sequence of words.
  • stack – Optional initial stack.
  • namespace – Optional namespace.

The top element from the stack

Evaluate sequence of words.

msp430.asm.rpn.python_function(code, namespace={})
  • code – RPN code to execute.
  • namespace – Optional namespace.

A python function that executes code when called.

Create a Python function that will execute given code when called. All parameters given to the Python function will be placed on the stack and the top of stack will be returned.

msp430.asm.rpn.interpreter_loop(namespace={}, debug=False)

Run an interactive loop. Can be used as calculator.

exception msp430.asm.rpn.RPNError

Exception type used for errors when parsing or executing RPN code. It may be annotated with the source position where the word causing the error came from.



This module implements a parser for a file format describing the peripherals and their bits of a MCU. The module can be executed (e.g. using python -m msp430.asm.peripherals) to test definition files.

class msp430.asm.peripherals.SymbolDefinitions(msp430.asm.rpn.RPN)

This class implements the parser and keeps the result. It inherits from RPN.

Parameters:filename – Load symbols from a file named like this.
Returns:instance of SymbolDefinitions

Load definitions from a file of given name.

Parameters:name – Name of an internal file.
Returns:instance of SymbolDefinitions

This tries to load internal data (using pkgutil).

exception msp430.asm.peripherals.SymbolError

Exception object used for errors in the definition file.


This module implements the a parser for files describing the memory map of a CPU. The module can be executed (e.g. using python -m msp430.asm.mcu_definition_parser) to test definition files.

class msp430.asm.mcu_definition_parser.MCUDefintitions(msp430.asm.rpn.RPN)

This class implements the parser and keeps the result. It inherits from msp430.asm.rpn.RPN. Loaded definitions may contain the memory maps of many MCUs and also partial maps (that may depend on each other).

Parameters:filename – Load definitions from file of given name.
Returns:instance of MCUDefintitions
Returns:instance of MCUDefintitions

Load internal list. The default list is included in msp430/asm/definitions/msp430-mcu-list.txt

msp430.asm.mcu_definition_parser.expand_definition(memory_maps, name)
  • memory_maps (MCUDefintitions) – Memory map descriptions.
  • name – Name of an MCU that should be extracted

Dictionary with recursively expanded memory map.

Return the memory map of a specific MCU. If the definition depends on others, it is expanded so that a single, complete description is returned.


This module implements a converter that can translate infix (arithmetical) notation to postfix notation (RPN). It is used by the preprocessor and assembler when evaluating expressions.

msp430.asm.infix2postfix.infix2postfix(expression, variable_prefix='', scanner=Scanner, precedence=default_precedence)
  • expression – Input string in infix notation.
  • variable_prefix – A string that is prepended to symbols found in the expression.
  • scanner – The class that is used to parse the expression.
  • precedence – A dictionary returning the priority given an operator as key.

A string with the expression in postfix notation.

Parameters:precedence_list – A list of lists that defines operator priorities.
Returns:A dictionary mapping operators to priorities.

Input will look like this:

default_precedence_list = [
        # lowest precedence
        ['<', '<=', '>', '>=', '==', '!='],
        ['|', '^', '&'],
        ['<<', '>>'],
        ['+', '-'],
        ['*', '/', '%'],
        ['~', 'neg', '0 +'],
        ['(', ')'],
        # highest precedence