##############################################################################
# Australian Public Licence B (OZPLB)
# 
# Version 1-0
# 
# Copyright (c) 2007, Open Kernel Labs, Inc.
# 
# All rights reserved. 
# 
# Developed by: Embedded, Real-time and Operating Systems Program (ERTOS)
#               National ICT Australia
#               http://www.ertos.nicta.com.au
# 
# Permission is granted by National ICT Australia, free of charge, to
# any person obtaining a copy of this software and any associated
# documentation files (the "Software") to deal with the Software without
# restriction, including (without limitation) the rights to use, copy,
# modify, adapt, merge, publish, distribute, communicate to the public,
# sublicense, and/or sell, lend or rent out copies of the Software, and
# to permit persons to whom the Software is furnished to do so, subject
# to the following conditions:
# 
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimers.
# 
#     * Redistributions in binary form must reproduce the above
#       copyright notice, this list of conditions and the following
#       disclaimers in the documentation and/or other materials provided
#       with the distribution.
# 
#     * Neither the name of National ICT Australia, nor the names of its
#       contributors, may be used to endorse or promote products derived
#       from this Software without specific prior written permission.
# 
# EXCEPT AS EXPRESSLY STATED IN THIS LICENCE AND TO THE FULL EXTENT
# PERMITTED BY APPLICABLE LAW, THE SOFTWARE IS PROVIDED "AS-IS", AND
# NATIONAL ICT AUSTRALIA AND ITS CONTRIBUTORS MAKE NO REPRESENTATIONS,
# WARRANTIES OR CONDITIONS OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
# BUT NOT LIMITED TO ANY REPRESENTATIONS, WARRANTIES OR CONDITIONS
# REGARDING THE CONTENTS OR ACCURACY OF THE SOFTWARE, OR OF TITLE,
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT,
# THE ABSENCE OF LATENT OR OTHER DEFECTS, OR THE PRESENCE OR ABSENCE OF
# ERRORS, WHETHER OR NOT DISCOVERABLE.
# 
# TO THE FULL EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL
# NATIONAL ICT AUSTRALIA OR ITS CONTRIBUTORS BE LIABLE ON ANY LEGAL
# THEORY (INCLUDING, WITHOUT LIMITATION, IN AN ACTION OF CONTRACT,
# NEGLIGENCE OR OTHERWISE) FOR ANY CLAIM, LOSS, DAMAGES OR OTHER
# LIABILITY, INCLUDING (WITHOUT LIMITATION) LOSS OF PRODUCTION OR
# OPERATION TIME, LOSS, DAMAGE OR CORRUPTION OF DATA OR RECORDS; OR LOSS
# OF ANTICIPATED SAVINGS, OPPORTUNITY, REVENUE, PROFIT OR GOODWILL, OR
# OTHER ECONOMIC LOSS; OR ANY SPECIAL, INCIDENTAL, INDIRECT,
# CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES, ARISING OUT OF OR IN
# CONNECTION WITH THIS LICENCE, THE SOFTWARE OR THE USE OF OR OTHER
# DEALINGS WITH THE SOFTWARE, EVEN IF NATIONAL ICT AUSTRALIA OR ITS
# CONTRIBUTORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH CLAIM, LOSS,
# DAMAGES OR OTHER LIABILITY.
# 
# If applicable legislation implies representations, warranties, or
# conditions, or imposes obligations or liability on National ICT
# Australia or one of its contributors in respect of the Software that
# cannot be wholly or partly excluded, restricted or modified, the
# liability of National ICT Australia or the contributor is limited, to
# the full extent permitted by the applicable legislation, at its
# option, to:
# a.  in the case of goods, any one or more of the following:
# i.  the replacement of the goods or the supply of equivalent goods;
# ii.  the repair of the goods;
# iii. the payment of the cost of replacing the goods or of acquiring
#  equivalent goods;
# iv.  the payment of the cost of having the goods repaired; or
# b.  in the case of services:
# i.  the supplying of the services again; or
# ii.  the payment of the cost of having the services supplied again.
# 
# The construction, validity and performance of this licence is governed
# by the laws in force in New South Wales, Australia.

"""
The modify subcommand of elfweaver.

This subcommand is designed to make changes to an existing ELF file to
accommodate the limitations of various boot-loaders.
"""

import optparse
from elf.core import ElfFile

class UnknownField(Exception):
    """Exception thrown when an unknown field is encountered."""
    pass

def adjust(elf, field_designator, offset, absolute):
    if field_designator[0] == "segment":
        # We do something for every segment
        for segment in elf.get_segments():
            if field_designator[1] == "paddr":
                if absolute:
                    segment.set_paddr(offset)
                else:
                    segment.set_paddr(segment.get_paddr() + offset)
            else:
                print "don't know about field_designator %s" % field_designator[1]
    else:
        raise UnknownField, "Don't know about field %s" % field_designator[0]

def change(elf, field_designator, old, new):
    if field_designator[0] == "segment":
        for segment in elf.get_segments():
            if field_designator[1] == "paddr":
                if segment.get_paddr() == old:
                    segment.set_paddr(new)
    else:
        raise UnknownField, "Don't know about field %s" % field_designator[0]

def merge_sections(elf, name):
    print "Merging elf sections", name
    base_section = None
    del_list = []
    for section in elf.get_sections()[:]:
#        print section.get_name()
        if base_section:
            if section.get_name().startswith(name):
                base_section.data_append(section.get_data())
                elf.remove_section(section)
            else:
                break
        if not base_section and section.get_name().startswith(name):
            base_section = section
            base_section.set_name(name)
            base_section.set_in_segment_offset(0)

    del_list.reverse()
    for d in del_list:
        del elf.get_sections()[d]

#     for section in elf.get_sections():
#         print section, section.get_name()
            

def modify_cmd(args):
    """Merge command call from main. This parses command line
    arguments and calls merge, which does all the main work."""
    parser = optparse.OptionParser("%prog modify file [options]",
                                   add_help_option=0)

    parser.add_option("-H", "--help", action="help")
    parser.add_option("--adjust", nargs=2, dest="adjust",
                      action="append", default=[])
    parser.add_option("--physical", dest="physical",
                      action="store_true")
    parser.add_option("--physical_entry", dest="physical_entry",
                      action="store_true")
    parser.add_option("--change", dest="change",
                      action="append", nargs=2, default=[])
    parser.add_option("--merge_sections", dest="merge_sections",
                      action="append", default=[])
    parser.add_option("--remove_nobits", dest="remove_nobits",
                      action="store_true")
    parser.add_option("--no-section-headers", dest="remove_section_headers",
                      action="store_true")
    parser.add_option("-o", "--output", dest="output", metavar="FILE",
                      help="Display the ELF file header")

    (options, args) = parser.parse_args(args)

    if len(args) != 1:
        parser.error("Must supply a file to operate on.")

    filename = args[0]

    elf = ElfFile.from_filename(filename)
    elf.unprepare()

    for (field_desc, offset) in options.adjust:
        absolute = True
        if offset.startswith("+") or offset.startswith("-"):
            absolute = False
        offset = long(offset, 0)
        field_desc = field_desc.split(".")
        adjust(elf, field_desc, offset, absolute)

    for (field_desc, mod) in options.change:
        field_desc = field_desc.split(".")
        (old, new) = [long(x, 0) for x in mod.split("=")]
        change(elf, field_desc, old, new)
            
    for section_name in options.merge_sections:
        merge_sections(elf, section_name)

    if options.physical_entry:
        entry = elf.get_entry_point()
        for segment in elf.get_segments():
            if segment.contains_vaddr(entry):
                offset = segment.get_vaddr() - segment.get_paddr()
                elf.set_entry_point(entry - offset)

    if options.physical:
        for segment in elf.get_segments():
            offset = segment.get_vaddr() - segment.get_paddr()
            segment.set_vaddr(segment.get_paddr())
            if segment.has_sections():
                for section in segment.get_sections():
                    section.set_address(section.get_address() - offset)

    if options.remove_nobits:
        elf.remove_nobits()

    if options.remove_section_headers:
        elf.remove_section_headers()

    elf.prepare()
    outfile = filename

    if options.output:
        outfile = options.output

    elf.to_filename(outfile)
