# Copyright (c) 2011, Peter A. Bigot, licensed under New BSD (see COPYING)
# This file is part of msp430mcu (http://sourceforge.net/projects/mspgcc/)
#
# Generate linker scripts to define the memory regions supported on
# particular MSP430 chips.

import sys
import csv
import os
import msp430mcu

msp430mcu.load_devices()

def writeMemory (mcu, mdir):
    try:
        os.makedirs(mdir)
    except OSError, e:
        pass

    mpath = os.path.join(mdir, 'memory.x')
    outf = file(mpath, 'w')
    outf.write(mcu.regionSection())
    outf.write('''
REGION_ALIAS("REGION_TEXT", rom);
REGION_ALIAS("REGION_DATA", ram);
REGION_ALIAS("REGION_FAR_ROM", far_rom); /* Legacy name, no longer used */
REGION_ALIAS("REGION_FAR_TEXT", far_rom);
REGION_ALIAS("REGION_FAR_DATA", ram2);
''')

    if 0 < mcu.infomem.segment_size:
        outf.write('PROVIDE (__info_segment_size = 0x%x);\n' % (mcu.infomem.segment_size,))
        if 0 < mcu.infod.origin:
            outf.write('PROVIDE (__infod = 0x%04x);\n' % (mcu.infod.origin,))
        if 0 < mcu.infoc.origin:
            outf.write('PROVIDE (__infoc = 0x%04x);\n' % (mcu.infoc.origin,))
        if 0 < mcu.infob.origin:
            outf.write('PROVIDE (__infob = 0x%04x);\n' % (mcu.infob.origin,))
        if 0 < mcu.infoa.origin:
            outf.write('PROVIDE (__infoa = 0x%04x);\n' % (mcu.infoa.origin,))

for mcu in msp430mcu.KnownDevices:
    mdir = os.path.join(msp430mcu.analysis_dir, 'ldscripts', mcu.mcu)
    writeMemory(mcu, mdir)
    if mcu.mergeRegions(mcu.usbram, mcu.ram):
        writeMemory(mcu, os.path.join(mdir, 'nousb'))


