├── CHANGELOG.rst ├── tests ├── __init__.py ├── test_process_map.py ├── vectors.py └── coveralls.py ├── requirements.txt ├── docs ├── _static │ ├── logo.png │ ├── favicon.ico │ ├── logo_icon.png │ ├── logo_packed.png │ └── custom.css ├── api.rst ├── index.rst ├── _templates │ └── about.html ├── installation.rst ├── Makefile ├── usage.rst └── conf.py ├── setup.cfg ├── MANIFEST.in ├── src └── fpvgcc │ ├── profiles │ ├── guess.py │ ├── __init__.py │ ├── gcc_msp430.py │ └── context.py │ ├── __init__.py │ ├── datastructures │ ├── __init__.py │ ├── ntreeSize.py │ └── ntree.py │ ├── cli.py │ ├── gccMemoryMap.py │ └── fpv.py ├── .travis.yml ├── tox.ini ├── .gitignore ├── setup.py ├── README.rst └── LICENSE /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | six 2 | prettytable 3 | sphinx 4 | sphinx-argparse 5 | -------------------------------------------------------------------------------- /docs/_static/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ebs-universe/fpv-gcc/HEAD/docs/_static/logo.png -------------------------------------------------------------------------------- /docs/_static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ebs-universe/fpv-gcc/HEAD/docs/_static/favicon.ico -------------------------------------------------------------------------------- /docs/_static/logo_icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ebs-universe/fpv-gcc/HEAD/docs/_static/logo_icon.png -------------------------------------------------------------------------------- /docs/_static/logo_packed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ebs-universe/fpv-gcc/HEAD/docs/_static/logo_packed.png -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | long_description = file: README.rst 3 | license_file = LICENSE 4 | 5 | [bdist_wheel] 6 | universal = 1 7 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.rst 3 | include docs/*.rst 4 | include docs/Makefile 5 | include docs/_static/* 6 | include docs/_templates/*.html 7 | 8 | include tests/maps/*.map 9 | -------------------------------------------------------------------------------- /tests/test_process_map.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from fpvgcc.fpv import GCCMemoryMapParserSM 4 | from fpvgcc.gccMemoryMap import GCCMemoryMap 5 | from .vectors import example_map 6 | 7 | 8 | def test_process_map(example_map): 9 | mm, vectors = example_map 10 | assert isinstance(mm, GCCMemoryMapParserSM) 11 | assert isinstance(mm.memory_map, GCCMemoryMap) 12 | -------------------------------------------------------------------------------- /src/fpvgcc/profiles/guess.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import re 4 | 5 | 6 | def guess_profile(fpath): 7 | fp = open(fpath, "rb") 8 | fp.seek(-300 - 1, 2) 9 | 10 | rex = r"^OUTPUT\((?P[\S]+)\s(?P[\S]+)\)$" 11 | line = fp.readlines()[-1].strip().decode() 12 | 13 | matches = re.search(rex, line) 14 | if matches: 15 | return matches.group('sig') 16 | return 'default' 17 | -------------------------------------------------------------------------------- /src/fpvgcc/profiles/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from .context import ContextBase 4 | from .gcc_msp430 import ProfileGccMsp430 5 | 6 | 7 | def _load_profiles(): 8 | return { 9 | 'default': ContextBase, 10 | ProfileGccMsp430.id: ProfileGccMsp430, 11 | } 12 | 13 | 14 | profiles = _load_profiles() 15 | 16 | 17 | def get_profile(idn): 18 | if idn in profiles.keys(): 19 | return profiles[idn]() 20 | else: 21 | return profiles['default']() 22 | -------------------------------------------------------------------------------- /tests/vectors.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import pytest 4 | from fpvgcc.fpv import process_map_file 5 | 6 | 7 | EXAMPLE_FILES = { 8 | 'tests/maps/example.arm-none-eabi.basic.0.map': None, 9 | 'tests/maps/example.msp430-elf.basic.0.map': None, 10 | 'tests/maps/example.msp430-elf.0.map': None, 11 | } 12 | 13 | 14 | @pytest.fixture(scope="module", 15 | params=EXAMPLE_FILES.keys()) 16 | def example_map(request): 17 | filename = request.param 18 | vectors = EXAMPLE_FILES[filename] 19 | return process_map_file(filename, profile='auto'), vectors 20 | -------------------------------------------------------------------------------- /src/fpvgcc/profiles/gcc_msp430.py: -------------------------------------------------------------------------------- 1 | 2 | from .context import ContextBase 3 | 4 | 5 | class ProfileGccMsp430(ContextBase): 6 | id = 'elf32-msp430' 7 | 8 | def __init__(self): 9 | super(ProfileGccMsp430, self).__init__() 10 | self._suppressed_names.extend([ 11 | 'debug_line', 12 | 'debug_info', 13 | 'debug_ranges', 14 | 'debug_aranges', 15 | 'debug_loc', 16 | 'debug_str', 17 | 'debug_frame', 18 | 'debug_abbrev', 19 | 'comment', 20 | 'MSP430' 21 | ]) 22 | -------------------------------------------------------------------------------- /src/fpvgcc/profiles/context.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class ContextBase(object): 4 | 5 | def __init__(self): 6 | self._suppressed_names = [] 7 | self._suppressed_regions = ['*default*'] 8 | 9 | @property 10 | def suppressed_names(self): 11 | return self._suppressed_names 12 | 13 | def suppress_name(self, name): 14 | self._suppressed_names.append(name) 15 | 16 | def unsuppress_name(self, name): 17 | while name in self._suppressed_names: 18 | self._suppressed_names.remove(name) 19 | 20 | @property 21 | def suppressed_regions(self): 22 | return self._suppressed_regions 23 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | 2 | language: python 3 | dist: xenial 4 | sudo: false 5 | matrix: 6 | include: 7 | - python: 2.7.16 8 | env: TOX_ENV=py27 9 | - python: 3.5.7 10 | env: TOX_ENV=py35 11 | - python: 3.6.8 12 | env: TOX_ENV=py36 13 | - python: 3.7.3 14 | env: TOX_ENV=py37 15 | - python: pypy2.7-7.0.0 16 | env: TOX_ENV=pypy 17 | - python: pypy3.5 18 | env: TOX_ENV=pypy3 19 | - python: 3.5 20 | env: TOX_ENV=cover 21 | - python: 3.5 22 | env: TOX_ENV=style 23 | - python: 3.5 24 | env: TOX_ENV=docs 25 | 26 | install: 27 | - pip install -U pip wheel 28 | - pip install tox 29 | cache: 30 | directories: 31 | - $HOME/.cache/pip 32 | before_script: 33 | - uname -a 34 | script: 35 | - tox -v -e $TOX_ENV 36 | -------------------------------------------------------------------------------- /src/fpvgcc/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | 4 | # Copyright (C) 2016 Chintalagiri Shashank 5 | # 6 | # This file is part of fpv-gcc. 7 | # 8 | # This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU Affero General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU Affero General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU Affero General Public License 19 | # along with this program. If not, see . 20 | 21 | """ 22 | Docstring for __init__.py 23 | """ 24 | -------------------------------------------------------------------------------- /src/fpvgcc/datastructures/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | 4 | # Copyright (C) 2017 Chintalagiri Shashank 5 | # 6 | # This file is part of fpv-gcc. 7 | # 8 | # This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU Affero General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU Affero General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU Affero General Public License 19 | # along with this program. If not, see . 20 | 21 | """ 22 | Docstring for __init__.py 23 | """ 24 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27, py35, py36, py37, pypy, pypy3, cover, style, docs 3 | 4 | [base] 5 | packagename = fpvgcc 6 | 7 | [testenv] 8 | passenv = TRAVIS TRAVIS_JOB_ID TRAVIS_BRANCH 9 | deps = 10 | setuptools_scm 11 | pytest 12 | commands = 13 | py.test --basetemp={envtmpdir} 14 | 15 | [testenv:cover] 16 | deps = 17 | setuptools_scm 18 | pytest 19 | pytest-cov 20 | coverage 21 | coveralls 22 | commands = 23 | py.test --cov={envsitepackagesdir}/{[base]packagename} --cov-report=term --basetemp={envtmpdir} 24 | python tests/coveralls.py 25 | 26 | [testenv:style] 27 | deps = 28 | pytest 29 | pytest-flake8 30 | commands = 31 | py.test --flake8 src/{[base]packagename} -v 32 | 33 | [testenv:docs] 34 | changedir=docs/ 35 | deps = 36 | setuptools_scm 37 | sphinx 38 | sphinx-argparse 39 | alabaster 40 | commands = 41 | sphinx-build -b linkcheck . _build/linkcheck/ 42 | sphinx-build -b dirhtml -d _build/doctrees . _build/dirhtml/ 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | 3 | ### Python template 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | env/ 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | *.idea 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | 56 | # Sphinx documentation 57 | docs/_build/ 58 | 59 | # PyBuilder 60 | target/ 61 | 62 | *.map 63 | .coveralls.yml 64 | 65 | -------------------------------------------------------------------------------- /docs/api.rst: -------------------------------------------------------------------------------- 1 | 2 | API Documentation 3 | ================= 4 | 5 | Core Application 6 | ---------------- 7 | 8 | .. automodule:: fpvgcc.fpv 9 | :members: 10 | :undoc-members: 11 | :show-inheritance: 12 | 13 | .. automodule:: fpvgcc.gccMemoryMap 14 | :members: 15 | :undoc-members: 16 | :show-inheritance: 17 | 18 | Underlying Data Structures 19 | -------------------------- 20 | 21 | .. automodule:: fpvgcc.datastructures.ntreeSize 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | 26 | .. automodule:: fpvgcc.datastructures.ntree 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | User Interfaces 32 | --------------- 33 | 34 | .. automodule:: fpvgcc.cli 35 | :members: 36 | :undoc-members: 37 | :show-inheritance: 38 | 39 | Toolchain Profiles 40 | ------------------ 41 | 42 | .. automodule:: fpvgcc.profiles.context 43 | :members: 44 | :undoc-members: 45 | :show-inheritance: 46 | 47 | .. automodule:: fpvgcc.profiles.guess 48 | :members: 49 | :undoc-members: 50 | :show-inheritance: 51 | 52 | .. automodule:: fpvgcc.profiles.gcc_msp430 53 | :members: 54 | :undoc-members: 55 | :show-inheritance: 56 | -------------------------------------------------------------------------------- /tests/coveralls.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | 4 | # Copyright (C) 2015 Chintalagiri Shashank 5 | # 6 | # This file is part of tendril. 7 | # 8 | # This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU Affero General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU Affero General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU Affero General Public License 19 | # along with this program. If not, see . 20 | 21 | """ 22 | See http://stackoverflow.com/questions/32757765/conditional-\ 23 | commands-in-tox-tox-travis-ci-and-coveralls/33012308 24 | """ 25 | 26 | 27 | import os 28 | 29 | from subprocess import call 30 | 31 | 32 | if __name__ == '__main__': 33 | if 'TRAVIS' in os.environ: 34 | rc = call('coveralls') 35 | raise SystemExit(rc) 36 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. fpv-gcc documentation master file, created by 2 | sphinx-quickstart on Wed Jul 27 23:12:58 2016. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | 7 | fpvgcc 8 | ====== 9 | 10 | .. include:: ../README.rst 11 | :start-after: inclusion-marker-do-not-remove 12 | 13 | .. raw:: latex 14 | 15 | \vspace*{\fill} 16 | 17 | .. tabularcolumns:: >{\raggedleft\arraybackslash}\Y{0.1} >{\raggedright\arraybackslash}\Y{0.5} 18 | 19 | .. list-table:: 20 | :widths: 8 40 21 | :header-rows: 0 22 | 23 | 24 | * - 25 | .. figure:: _static/logo_packed.png 26 | :align: right 27 | - 28 | .. raw:: latex 29 | 30 | \vspace{-1.5em} 31 | 32 | ``fpvgcc`` is part of the EBS universe of packages and tools for constrained embedded systems 33 | 34 | .. raw:: latex 35 | 36 | \clearpage 37 | 38 | 39 | Documentation 40 | ------------- 41 | 42 | .. toctree:: 43 | :maxdepth: 3 44 | 45 | installation 46 | usage 47 | api 48 | 49 | 50 | .. only:: html 51 | 52 | Indices and tables 53 | ------------------ 54 | 55 | * :ref:`genindex` 56 | * :ref:`modindex` 57 | * :ref:`search` 58 | -------------------------------------------------------------------------------- /docs/_templates/about.html: -------------------------------------------------------------------------------- 1 | {% if theme_logo %} 2 |

{{ project }}

7 | {% endif %} 8 | 9 |

10 | {% else %} 11 |

{{ project }} v{{ version }}

12 | {% endif %} 13 | 14 | {% if theme_description %} 15 |

{{ theme_description }}

16 | {% endif %} 17 | 18 | {% set githubpath = theme_github_user + '/' + theme_github_repo %} 19 | 20 | 21 | Project License 25 | 26 | 27 | 28 | PyPI Package Version 32 | 33 | 34 | 35 | Supported Python Versions 39 | 40 | 41 | 42 | Travis CI Build Status 46 | 47 | 48 | 49 | Coveralls Code Coverage 53 | 54 | 55 | 56 | GitHub watchers 60 | 61 | -------------------------------------------------------------------------------- /src/fpvgcc/datastructures/ntreeSize.py: -------------------------------------------------------------------------------- 1 | 2 | # Copyright (C) 2015 Quazar Technologies Pvt. Ltd. 3 | # 2015 Chintalagiri Shashank 4 | # 5 | # This file is part of fpv-gcc. 6 | # 7 | # fpv-gcc is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # fpv-gcc is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with fpv-gcc. If not, see . 19 | 20 | 21 | import logging 22 | from .ntree import NTreeNode, NTree 23 | 24 | 25 | class SizeNTreeNode(NTreeNode): 26 | def __init__(self, parent=None, node_t=None): 27 | super(SizeNTreeNode, self).__init__(parent, node_t) 28 | self._leafsize = None 29 | 30 | @property 31 | def size(self): 32 | rval = 0 33 | if self.is_leaf: 34 | rval = self.leafsize 35 | else: 36 | for child in self.children: 37 | try: 38 | rval += child.size 39 | except TypeError: 40 | logging.warning("Size information not available for : " 41 | + child.gident) 42 | return "Err" 43 | return rval 44 | 45 | @property 46 | def leafsize(self): 47 | raise NotImplementedError 48 | 49 | @leafsize.setter 50 | def leafsize(self, value): 51 | raise NotImplementedError 52 | 53 | 54 | class SizeNTree(NTree): 55 | node_t = SizeNTreeNode 56 | 57 | def __init__(self): 58 | super(SizeNTree, self).__init__() 59 | 60 | @property 61 | def size(self): 62 | return self.root.size 63 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | 2 | Installation 3 | ============ 4 | 5 | Installation from PyPI 6 | ---------------------- 7 | 8 | ``fpvgcc`` can be installed normally from the Python Package Index. The 9 | ``fpvgcc`` script entry point will also be installed to your ``$PATH`` and 10 | will be available for use from your terminal. 11 | 12 | Note that you will need write access to your python packages folder. This 13 | means you will have to install as root or with sudo on most linux distributions, 14 | unless you are installing to a virtual environment you can write to. 15 | 16 | .. code-block:: console 17 | 18 | $ sudo pip install fpvgcc 19 | $ fpvgcc 20 | usage: fpvgcc [-h] [-v] 21 | (--sar | ... ) 22 | fpvgcc: error: too few arguments 23 | 24 | 25 | Installation from Sources 26 | ------------------------- 27 | 28 | The sources can be downloaded from the project's 29 | `github releases `_. While this 30 | is the least convenient method of installation, it does have the advantage of 31 | making the least assumptions about your environment. 32 | 33 | You will have to ensure the following dependencies are installed and available 34 | in your python environment by whatever means you usually use. 35 | 36 | - six 37 | - prettytable 38 | 39 | 40 | .. code-block:: console 41 | 42 | $ wget https://github.com/ebs-universe/fpv-gcc/archive/v0.9.7.tar.gz 43 | $ unzip fpv-gcc-0.8.2.zip 44 | ... 45 | $ cd fpv-gcc-0.8.2 46 | $ sudo python setup.py install 47 | ... 48 | $ fpvgcc 49 | usage: fpvgcc [-h] [-v] 50 | (--sar | ... ) 51 | fpvgcc: error: too few arguments 52 | 53 | 54 | Installation for Development 55 | ---------------------------- 56 | 57 | Installation from the repository is the most convenient installation method 58 | if you intend to modify the code, either for your own use or to contribute to 59 | ``fpvgcc``. 60 | 61 | .. code-block:: console 62 | 63 | $ git clone https://github.com/chintal/fpv-gcc.git 64 | $ cd fpv-gcc 65 | $ sudo pip install -e . 66 | $ fpvgcc 67 | usage: fpvgcc [-h] [-v] 68 | (--sar | ... ) 69 | fpvgcc: error: too few arguments 70 | -------------------------------------------------------------------------------- /docs/_static/custom.css: -------------------------------------------------------------------------------- 1 | div#changelog > div.section > ul > li > p:only-child { 2 | margin-bottom: 0; 3 | } 4 | 5 | @media screen and (max-width: 768px) { 6 | #fork-gh img, a.github img { 7 | display: none; 8 | } 9 | } 10 | 11 | table.docutils { 12 | background-color: #fafbfc; 13 | border: 0; 14 | } 15 | 16 | table.docutils td, table.docutils th { 17 | border: 0; 18 | } 19 | 20 | table.docutils pre { 21 | background-color: rgba(239, 242, 244, .75); 22 | } 23 | 24 | pre { 25 | background-color: #fafbfc; 26 | border-left: 5px solid #558abb; 27 | padding: 7px 20px !important; 28 | } 29 | 30 | div.sidebar { 31 | border-top: 5px solid #558abb !important; 32 | background-color: #fafbfc !important; 33 | padding: 3px !important; 34 | } 35 | 36 | div.admonition, 37 | div.caution, 38 | div.danger, 39 | div.error, 40 | div.hint, 41 | div.important, 42 | div.note, 43 | div.tip, 44 | div.seealso, /* sphinx directive */ 45 | div.warning { 46 | background-color: #fafbfc; 47 | border-right: 0; 48 | border-top: 0; 49 | border-bottom: 0; 50 | } 51 | 52 | div.seealso { 53 | border-left: 5px solid #8abb55; 54 | } 55 | 56 | div.note { 57 | border-left: 5px solid #6C3082; 58 | } 59 | 60 | div.hint { 61 | border-left: 5px solid #8899a6; 62 | } 63 | 64 | div.tip { 65 | border-left: 5px solid #eef147; 66 | } 67 | 68 | div.caution { 69 | border-left: 5px solid #bb5557; 70 | } 71 | 72 | div.danger, div.error, div.warning { 73 | border-left: 5px solid #bb5557; 74 | } 75 | 76 | div.caution, div.danger, div.error, div.warning { 77 | background: rgba(160, 17, 17, 0.1); 78 | } 79 | 80 | code::before, code::after { 81 | letter-spacing: -0.2em; 82 | content: "\00a0"; 83 | } 84 | 85 | code.literal { 86 | font-size: 75%; 87 | color: #24292e; 88 | box-sizing: border-box; 89 | display: inline-block; 90 | padding: 0; 91 | background: #fafcfc; 92 | border: 1px solid #f0f4f7; 93 | line-height: 18px; 94 | } 95 | 96 | /* BEGIN alabaster.css override for link styling */ 97 | a.reference, a.reference:hover { 98 | border-bottom: 0px !important; 99 | text-decoration-style: solid; 100 | text-decoration-line: underline; 101 | } 102 | 103 | a.reference { 104 | text-decoration-color: rgba(245, 230, 230, 1); 105 | color: rgba(249, 89, 89, 1); 106 | } 107 | 108 | a.reference:hover { 109 | text-decoration-color: rgba(250, 137, 137, 1); 110 | color: rgba(250, 137, 137, 1); 111 | } 112 | /* END alabaster.css override for link styling */ 113 | 114 | /* BEGIN alabaster.css override for fonts */ 115 | 116 | pre, tt, code { 117 | font-family: "Fira Mono", Consolas, Menlo, Monaco, "Courier New", Courier, monospace !important; 118 | } 119 | 120 | body, div.body h1, div.body h2, div.body h3, div.body h4, div.body h5, div.body h6, 121 | div.admonition p.admonition-title, div.sphinxsidebar input, div.sphinxsidebar h3, 122 | div.sphinxsidebar h4 { 123 | font-family: "Roboto", Corbel, Avenir, "Lucida Grande", "Lucida Sans", sans-serif !important; 124 | } 125 | 126 | body { 127 | font-size: 14px !important; 128 | } 129 | /* END alabaster.css override for fonts */ 130 | 131 | /* BEGIN alabaster.css override for logo */ 132 | 133 | div.sphinxsidebarwrapper h1.logo { 134 | text-align: center; 135 | margin-bottom: 20px; 136 | } 137 | 138 | div.sphinxsidebarwrapper p.blurb { 139 | text-align: center; 140 | } 141 | 142 | /* END alabaster.css override for logo styling */ -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- encoding: utf-8 -*- 3 | 4 | from __future__ import absolute_import 5 | from __future__ import print_function 6 | 7 | import os 8 | from setuptools import setup, find_packages 9 | 10 | 11 | # Utility function to read the README file. 12 | # Used for the long_description. It's nice, because now 1) we have a top level 13 | # README file and 2) it's easier to type in the README file than to put a raw 14 | # string in below ... 15 | def read(fname): 16 | orig_content = open(os.path.join(os.path.dirname(__file__), fname)).readlines() 17 | content = "" 18 | in_raw_directive = 0 19 | for line in orig_content: 20 | if in_raw_directive: 21 | if not line.strip(): 22 | in_raw_directive = in_raw_directive - 1 23 | continue 24 | elif line.strip() == '.. raw:: latex': 25 | in_raw_directive = 2 26 | continue 27 | content += line 28 | return content 29 | 30 | 31 | core_dependencies = [ 32 | 'six', 33 | 'prettytable' 34 | ] 35 | 36 | install_requires = core_dependencies + ['wheel'] 37 | 38 | setup_requires = ['setuptools_scm'] 39 | 40 | doc_requires = setup_requires + ['sphinx', 'sphinx-argparse', 'alabaster'] 41 | 42 | test_requires = doc_requires + ['pytest', 'pytest-cov', 'coveralls[yaml]'] 43 | 44 | build_requires = test_requires + ['doit', 'pyinstaller'] 45 | 46 | publish_requires = build_requires + ['twine', 'pygithub'] 47 | 48 | setup( 49 | name="fpvgcc", 50 | use_scm_version={"root": ".", "relative_to": __file__}, 51 | author="Chintalagiri Shashank", 52 | author_email="shashank@chintal.in", 53 | description="Analysing code footprint on embedded microcontrollers " 54 | "using GCC generated Map files", 55 | long_description='\n'.join([read('README.rst'), read('CHANGELOG.rst')]), 56 | long_description_content_type='text/x-rst', 57 | keywords="utilities", 58 | url="https://github.com/ebs-universe/fpv-gcc", 59 | project_urls={ 60 | 'Documentation': 'https://fpvgcc.readthedocs.io/en/latest', 61 | 'Bug Tracker': 'https://github.com/ebs-universe/fpv-gcc/issues', 62 | 'Source Repository': 'https://github.com/ebs-universe/fpv-gcc', 63 | }, 64 | packages=find_packages('src'), 65 | package_dir={'': 'src'}, 66 | classifiers=[ 67 | 'Development Status :: 4 - Beta', 68 | 'Topic :: Utilities', 69 | "Topic :: Software Development :: Embedded Systems", 70 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", 71 | "Programming Language :: Python", 72 | "Intended Audience :: Developers", 73 | "Natural Language :: English", 74 | "Operating System :: OS Independent", 75 | "Environment :: Console", 76 | 'Programming Language :: Python', 77 | 'Programming Language :: Python :: 3 :: Only', 78 | 'Programming Language :: Python :: 3.7', 79 | 'Programming Language :: Python :: 3.8', 80 | 'Programming Language :: Python :: 3.9', 81 | 'Programming Language :: Python :: 3.10', 82 | 'Programming Language :: Python :: 3.11', 83 | 'Programming Language :: Python :: 3.12', 84 | 'Programming Language :: Python :: Implementation :: CPython', 85 | 'Programming Language :: Python :: Implementation :: PyPy', 86 | ], 87 | python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', 88 | install_requires=install_requires, 89 | setup_requires=setup_requires, 90 | extras_require={ 91 | 'docs': doc_requires, 92 | 'tests': test_requires, 93 | 'build': build_requires, 94 | 'publish': publish_requires, 95 | 'dev': build_requires, 96 | }, 97 | platforms='any', 98 | entry_points={ 99 | 'console_scripts': ['fpvgcc=fpvgcc.cli:main'], 100 | }, 101 | include_package_data=True 102 | ) 103 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | 2 | 3 | .. image:: https://img.shields.io/pypi/v/fpvgcc.svg?logo=pypi 4 | :target: https://pypi.org/project/fpvgcc 5 | 6 | .. image:: https://img.shields.io/pypi/pyversions/fpvgcc.svg?logo=pypi 7 | :target: https://pypi.org/project/fpvgcc 8 | 9 | .. image:: https://img.shields.io/travis/ebs-universe/fpv-gcc.svg?logo=travis 10 | :target: https://travis-ci.org/ebs-universe/fpv-gcc 11 | 12 | .. image:: https://img.shields.io/coveralls/github/ebs-universe/fpv-gcc.svg?logo=coveralls 13 | :target: https://coveralls.io/github/ebs-universe/fpv-gcc 14 | 15 | .. image:: https://img.shields.io/requires/github/ebs-universe/fpv-gcc.svg 16 | :target: https://requires.io/github/ebs-universe/fpv-gcc/requirements 17 | 18 | .. image:: https://img.shields.io/pypi/l/fpvgcc.svg 19 | :target: https://www.gnu.org/licenses/gpl-3.0.en.html 20 | 21 | 22 | 23 | .. inclusion-marker-do-not-remove 24 | 25 | .. raw:: latex 26 | 27 | \vspace*{\fill} 28 | 29 | Deprecation Notice 30 | ------------------ 31 | 32 | This (``v1.1.2``) will be the final release of the 1.x series of ``fpvgcc``. 33 | The tool has evolved to the extent possible within the naive framework 34 | it was originally built on, and a number of open issues cannot be resolved 35 | without refactoring big chunks of the code. ``fpvgcc v1.1.2`` is essentially 36 | functional and will remain available in its present form. 37 | 38 | Though I have been unable to find time to maintain and build up the tool 39 | after the original releases, I hope it has been useful to the few people 40 | who've used it. 41 | 42 | A number of other tools are now available which do a similar job. While I 43 | have minor qualms about each of those tools, such qualms are mostly 44 | subjective and aesthetic objections. I am forced to admit that ``fpvgcc`` 45 | would never have been written if some of those tools had existed at the 46 | time of its writing. 47 | 48 | I am considering starting work on a 2.x series of ``fpvgcc``, which will 49 | likely be a page one rewrite. The following are the main planned changes: 50 | 51 | - Reduce the number of assumptions made when parsing map files. For example, 52 | allow multiple object files with the same name. 53 | - Use polars or something suitably performant to store the parsed map 54 | information. 55 | - Add a minimal fastapi interface to be able to provide a GUI using a 56 | webview or similar. 57 | - Remove python 2 support. Minimum python version required will probably 58 | be py37 or py38. 59 | 60 | I expect it will be some time before 2.x will be usable. If and when 61 | development starts, it will be available in the v2 branch of this 62 | repository. When v2.x reaches feature parity with v1.1.2, it will be 63 | merged in to ``main`` and python packages for fpvgcc 2.x will be published 64 | to pypi. 65 | 66 | Please feel free to write to me at ``shashank at chintal dot in`` if any 67 | of the following apply to you: 68 | 69 | - you have been using ``fpvgcc`` or are maintaining a public or private 70 | fork and have any concerns regarding the deprecation or plans for 2.x 71 | - you wish to take over the 1.x codebase and keep it functional and 72 | available in the future 73 | - you have any suggestions for features to include in 2.x 74 | - you wish to contribute to the development of 2.x 75 | 76 | 77 | Introduction 78 | ------------ 79 | 80 | ``fpvgcc`` is a python script/package to help analyse code footprint on 81 | embedded microcontrollers using GCC generated Map files. 82 | 83 | This module uses information contained within ``.map`` files generated by 84 | gcc (when invoked with ``-Wl,-Map,out.map``), to provide easily 85 | readable summaries of static memory usage at various levels of the code 86 | hierarchy. This package generates no information that isn't already contained 87 | within the ``.map`` file. 88 | 89 | The provided outputs can be used to gain insight into the relative sizes of 90 | included code, and aid in prioritizing static memory optimization for very 91 | low memory platforms. Some provided functionality may also deliver minor 92 | usability improvements to the workflow involved in parsing though generated 93 | assembly listings. 94 | 95 | 96 | .. warning:: 97 | This package does not attempt to perform any kind of dynamic analysis. 98 | All memory usage reported refers only to **static** memory usage. This 99 | means the size of actual functions and global variables which are 100 | instantiated in the C code itself. 101 | 102 | Anything on the call stack, such as function locals, will **not** be 103 | accounted for. Similarly, anything in the heap which is allocated at 104 | runtime using ``malloc`` or similar will **not** be accounted for. 105 | 106 | Due to this, the utility of this module is likely limited to code 107 | written for highly memory constrained embedded microcontrollers, where 108 | dynamic memory allocation is anyway avoided when possible. 109 | 110 | .. raw:: latex 111 | 112 | \clearpage 113 | \tableofcontents 114 | \clearpage 115 | 116 | Known Issues 117 | ------------ 118 | 119 | This script was first written based on the format of mapfiles 120 | generated by ``msp430-elf-gcc, v4.9.1``. Over time, it was modifed to 121 | accept elements found in mapfiles generated by later versions and gcc-based 122 | toolchains for other platforms. 123 | 124 | Still, remember that the file parsing was implemented by observing the 125 | content of real mapfiles, and not based on a file format specification. 126 | Even with toolchains it was written to support, there are large sections 127 | of the file that are not actually used. Due to this, the outputs generated 128 | are not always accurate. Various boundary conditions result in minor errors 129 | in size reporting. 130 | 131 | The following more serious issues are known. They should be fixed at some 132 | point, but for the moment I've chosen to work around them : 133 | 134 | - Having two C filenames with the same name (or generating the same 135 | obj name) in your tree will cause parsing to break on some 136 | platforms / toolchains. 137 | 138 | 139 | Project Information 140 | ------------------- 141 | 142 | The latest version of the documentation, including installation, usage, and 143 | API/developer notes can be found at 144 | `ReadTheDocs `_. 145 | 146 | The latest version of the sources can be found at 147 | `GitHub `_. Please use GitHub's features 148 | to report bugs, request features, or submit pull/merge requests. 149 | 150 | The principle author for ``fpvgcc`` is Chintalagiri Shashank. The author can 151 | be contacted if necessary via the information on the 152 | `author's github profile `_ . See the AUTHORS file 153 | for a full list of collaborators and/or contributing authors, if any. 154 | 155 | ``fpvgcc`` is distributed under the terms of the 156 | `GPLv3 license `_ . 157 | A copy of the text of the license is included along with the sources. 158 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help 23 | help: 24 | @echo "Please use \`make ' where is one of" 25 | @echo " html to make standalone HTML files" 26 | @echo " dirhtml to make HTML files named index.html in directories" 27 | @echo " singlehtml to make a single large HTML file" 28 | @echo " pickle to make pickle files" 29 | @echo " json to make JSON files" 30 | @echo " htmlhelp to make HTML files and a HTML help project" 31 | @echo " qthelp to make HTML files and a qthelp project" 32 | @echo " applehelp to make an Apple Help Book" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | @echo " coverage to run coverage check of the documentation (if enabled)" 49 | 50 | .PHONY: clean 51 | clean: 52 | rm -rf $(BUILDDIR)/* 53 | 54 | .PHONY: html 55 | html: 56 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 57 | @echo 58 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 59 | 60 | .PHONY: dirhtml 61 | dirhtml: 62 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 63 | @echo 64 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 65 | 66 | .PHONY: singlehtml 67 | singlehtml: 68 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 69 | @echo 70 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 71 | 72 | .PHONY: pickle 73 | pickle: 74 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 75 | @echo 76 | @echo "Build finished; now you can process the pickle files." 77 | 78 | .PHONY: json 79 | json: 80 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 81 | @echo 82 | @echo "Build finished; now you can process the JSON files." 83 | 84 | .PHONY: htmlhelp 85 | htmlhelp: 86 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 87 | @echo 88 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 89 | ".hhp project file in $(BUILDDIR)/htmlhelp." 90 | 91 | .PHONY: qthelp 92 | qthelp: 93 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 94 | @echo 95 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 96 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 97 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/fpv-gcc.qhcp" 98 | @echo "To view the help file:" 99 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/fpv-gcc.qhc" 100 | 101 | .PHONY: applehelp 102 | applehelp: 103 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 104 | @echo 105 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 106 | @echo "N.B. You won't be able to view it unless you put it in" \ 107 | "~/Library/Documentation/Help or install it in your application" \ 108 | "bundle." 109 | 110 | .PHONY: devhelp 111 | devhelp: 112 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 113 | @echo 114 | @echo "Build finished." 115 | @echo "To view the help file:" 116 | @echo "# mkdir -p $$HOME/.local/share/devhelp/fpv-gcc" 117 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/fpv-gcc" 118 | @echo "# devhelp" 119 | 120 | .PHONY: epub 121 | epub: 122 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 123 | @echo 124 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 125 | 126 | .PHONY: latex 127 | latex: 128 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 129 | @echo 130 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 131 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 132 | "(use \`make latexpdf' here to do that automatically)." 133 | 134 | .PHONY: latexpdf 135 | latexpdf: 136 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 137 | @echo "Running LaTeX files through pdflatex..." 138 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 139 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 140 | 141 | .PHONY: latexpdfja 142 | latexpdfja: 143 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 144 | @echo "Running LaTeX files through platex and dvipdfmx..." 145 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 146 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 147 | 148 | .PHONY: text 149 | text: 150 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 151 | @echo 152 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 153 | 154 | .PHONY: man 155 | man: 156 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 157 | @echo 158 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 159 | 160 | .PHONY: texinfo 161 | texinfo: 162 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 163 | @echo 164 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 165 | @echo "Run \`make' in that directory to run these through makeinfo" \ 166 | "(use \`make info' here to do that automatically)." 167 | 168 | .PHONY: info 169 | info: 170 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 171 | @echo "Running Texinfo files through makeinfo..." 172 | make -C $(BUILDDIR)/texinfo info 173 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 174 | 175 | .PHONY: gettext 176 | gettext: 177 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 178 | @echo 179 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 180 | 181 | .PHONY: changes 182 | changes: 183 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 184 | @echo 185 | @echo "The overview file is in $(BUILDDIR)/changes." 186 | 187 | .PHONY: linkcheck 188 | linkcheck: 189 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 190 | @echo 191 | @echo "Link check complete; look for any errors in the above output " \ 192 | "or in $(BUILDDIR)/linkcheck/output.txt." 193 | 194 | .PHONY: doctest 195 | doctest: 196 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 197 | @echo "Testing of doctests in the sources finished, look at the " \ 198 | "results in $(BUILDDIR)/doctest/output.txt." 199 | 200 | .PHONY: coverage 201 | coverage: 202 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 203 | @echo "Testing of coverage in the sources finished, look at the " \ 204 | "results in $(BUILDDIR)/coverage/python.txt." 205 | 206 | .PHONY: xml 207 | xml: 208 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 209 | @echo 210 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 211 | 212 | .PHONY: pseudoxml 213 | pseudoxml: 214 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 215 | @echo 216 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 217 | -------------------------------------------------------------------------------- /src/fpvgcc/datastructures/ntree.py: -------------------------------------------------------------------------------- 1 | 2 | # Copyright (C) 2015 Quazar Technologies Pvt. Ltd. 3 | # 2015 Chintalagiri Shashank 4 | # 5 | # This file is part of fpv-gcc. 6 | # 7 | # fpv-gcc is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # fpv-gcc is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with fpv-gcc. If not, see . 19 | 20 | 21 | import logging 22 | from functools import cached_property, lru_cache 23 | from os.path import commonprefix 24 | 25 | 26 | class NTreeNode(object): 27 | _leaf_property = None 28 | _ident_property = None 29 | 30 | def __init__(self, parent=None, node_t=None): 31 | self.parent = parent 32 | if node_t is None: 33 | if self.parent is not None: 34 | node_t = self.parent.node_t 35 | else: 36 | node_t = NTreeNode 37 | self.node_t = node_t 38 | self.children = [] 39 | 40 | @cached_property 41 | def tree(self): 42 | if isinstance(self.parent, NTree): 43 | return self.parent 44 | else: 45 | return self.parent.tree 46 | 47 | @property 48 | def is_root(self): 49 | if isinstance(self.parent, NTree): 50 | return True 51 | else: 52 | return False 53 | 54 | @property 55 | def is_toplevelnode(self): 56 | if self.is_root: 57 | return False 58 | if isinstance(self.parent.parent, NTree): 59 | return True 60 | return False 61 | 62 | @property 63 | def is_leaf(self): 64 | if len(self.children) > 0: 65 | return False 66 | else: 67 | return True 68 | 69 | def add_child(self, newchild=None): 70 | if newchild is None: 71 | newchild = self.node_t(parent=self, node_t=self.node_t) 72 | try: 73 | for child in self.children: 74 | if child.ident == newchild.ident: 75 | raise ValueError("Child with that identifier already " 76 | "exists: {0}".format(newchild.ident)) 77 | except NotImplementedError: 78 | pass 79 | if len(self.children) == 0: 80 | try: 81 | if self._is_leaf_property_set is True: 82 | logging.warning( 83 | "Adding children to node which has leaf specific " 84 | "information set : {0}".format(self.gident) 85 | ) 86 | except NotImplementedError: 87 | pass 88 | newchild.parent = self 89 | self.children.append(newchild) 90 | return newchild 91 | 92 | @property 93 | def _is_leaf_property_set(self): 94 | if self._leaf_property is None: 95 | raise NotImplementedError 96 | if getattr(self, self._leaf_property) is not None: 97 | return True 98 | return False 99 | 100 | @property 101 | def _is_ident_property_set(self): 102 | if not self._ident_property: 103 | raise NotImplementedError 104 | if not getattr(self, self._ident_property, None): 105 | return True 106 | return False 107 | 108 | @property 109 | def idx(self): 110 | if self.parent is None: 111 | return 'Root' 112 | else: 113 | return self.parent.children.index(self) 114 | 115 | @property 116 | def ident(self): 117 | if self._ident_property: 118 | return getattr(self, self._ident_property, '') 119 | else: 120 | return str(self.idx) 121 | 122 | @ident.setter 123 | def ident(self, value): 124 | if self._ident_property: 125 | setattr(self, self._ident_property, value) 126 | 127 | @property 128 | def has_ident(self): 129 | return self._ident_property is not None 130 | 131 | @property 132 | def gident(self): 133 | rval = self.ident 134 | walker = self 135 | while not isinstance(walker.parent, NTree): 136 | walker = walker.parent 137 | rval = walker.ident + '.' + rval 138 | return rval 139 | 140 | def get_child_by_ident(self, ident): 141 | for child in self.children: 142 | if child.ident == ident: 143 | return child 144 | raise ValueError 145 | 146 | def get_child_disambig(self, ident, prospective=False): 147 | disambig = None 148 | for child in self.children: 149 | if ':' in child.ident: 150 | name, d = child.ident.split(':') 151 | if name == ident: 152 | disambig = disambig or 0 153 | disambig = max(disambig, int(d)) 154 | elif prospective and child.ident == ident: 155 | # print("Recommending disambig for {0};{1} 156 | # ".format(self.gident, ident)) 157 | disambig = disambig or 0 158 | return disambig 159 | 160 | def get_descendent_by_ident(self, ident): 161 | res = self.get_child_by_ident(ident) 162 | if res is not None: 163 | return res 164 | for child in self.children: 165 | if child.is_leaf is False: 166 | res = child.get_descendent_by_ident(ident) 167 | if res is not None: 168 | return res 169 | return ValueError 170 | 171 | @lru_cache(maxsize=None) 172 | def all_nodes(self): 173 | def iter_all(): 174 | yield self 175 | for child in self.children: 176 | for node in child.all_nodes(): 177 | yield node 178 | 179 | return list(iter_all()) 180 | 181 | @property 182 | def get_top_level_ancestor(self): 183 | walker = self 184 | if walker.is_root: 185 | return None 186 | while not walker.is_toplevelnode: 187 | walker = walker.parent 188 | return walker 189 | 190 | 191 | class NTree(object): 192 | node_t = NTreeNode 193 | 194 | def __init__(self): 195 | self.root = self.node_t(parent=self, node_t=self.node_t) 196 | 197 | @property 198 | def top_level_nodes(self): 199 | return self.root.children 200 | 201 | @property 202 | def top_level_idents(self): 203 | if self.root.has_ident: 204 | return [x.ident for x in self.top_level_nodes] 205 | else: 206 | raise AttributeError 207 | 208 | @property 209 | def top_level_gidents(self): 210 | return [x.gident for x in self.top_level_nodes] 211 | 212 | def get_node_disambig(self, gident, prospective=False): 213 | crumbs = gident.split('.') 214 | if crumbs[0] != self.root.ident: 215 | raise ValueError 216 | walker = self.root 217 | for crumb in crumbs[1:-1]: 218 | if walker.get_child_disambig(crumb) is None: 219 | walker = walker.get_child_by_ident(crumb) 220 | else: 221 | raise ValueError('Deep disambig found at intermediate node : ' 222 | '{0}'.format(crumbs)) 223 | return walker.get_child_disambig(crumbs[-1], prospective) 224 | 225 | def get_node(self, gident, create=False): 226 | crumbs = gident.split('.') 227 | if crumbs[0] != self.root.ident: 228 | raise ValueError 229 | walker = self.root 230 | for crumb in crumbs[1:]: 231 | try: 232 | walker = walker.get_child_by_ident(crumb) 233 | except ValueError: 234 | if create: 235 | # print "Creating Node : " + crumb 236 | newnode = walker.add_child() 237 | if newnode.has_ident: 238 | newnode.ident = crumb 239 | else: 240 | raise ValueError 241 | walker = walker.get_child_by_ident(crumb) 242 | else: 243 | raise ValueError 244 | return walker 245 | 246 | def get_least_common_ancestor(self, nodes): 247 | t = commonprefix([node.gident for node in nodes]) 248 | k = t.rfind('.') 249 | return self.get_node(t[:k]) 250 | -------------------------------------------------------------------------------- /src/fpvgcc/cli.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | 4 | # Copyright (C) 2017 Chintalagiri Shashank 5 | # 6 | # This file is part of fpv-gcc. 7 | # 8 | # This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU Affero General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU Affero General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU Affero General Public License 19 | # along with this program. If not, see . 20 | 21 | """ 22 | Docstring for cli 23 | """ 24 | 25 | import argparse 26 | import logging 27 | from prettytable import PrettyTable 28 | 29 | from .fpv import process_map_file 30 | from .profiles import profiles 31 | from .profiles import get_profile 32 | from .profiles.guess import guess_profile 33 | 34 | 35 | def _build_table_header(cols, rowtitle): 36 | tbl = PrettyTable([rowtitle] + cols + ['TOTAL']) 37 | tbl.align[rowtitle] = 'l' 38 | for heading in cols: 39 | tbl.align[heading] = 'r' 40 | tbl.align['TOTAL'] = 'r' 41 | tbl.padding_width = 1 42 | totals = [0] * (len(cols) + 1) 43 | return tbl, totals 44 | 45 | 46 | def _add_row(tbl, rowtitle, row, totals=None): 47 | total = sum(row) 48 | tbl.add_row([rowtitle] + [x or '' for x in row] + [total]) 49 | if totals: 50 | totals = [totals[idx] + row[idx] for idx in range(len(row))] 51 | return totals 52 | 53 | 54 | def _add_totals_row(tbl, totals): 55 | tbl.add_row(['TOTALS'] + totals + ['']) 56 | 57 | 58 | def _render_table(tbl): 59 | print(tbl.get_string(sortby='TOTAL', reversesort=True, 60 | sort_key=lambda x: x[-1] or 0)) 61 | 62 | 63 | def print_symbol_fp(mm, lfile='all'): 64 | cols = mm.used_regions 65 | tbl, totals = _build_table_header(cols, 'SYMBOL') 66 | 67 | if lfile == 'all': 68 | symbols = mm.all_symbols 69 | else: 70 | symbols = mm.symbols_from_file(lfile) 71 | 72 | for symbol in symbols: 73 | nextrow = mm.get_symbol_fp(symbol) 74 | if not sum(nextrow): 75 | continue 76 | totals = _add_row(tbl, symbol, nextrow, totals) 77 | 78 | _add_totals_row(tbl, totals) 79 | _render_table(tbl) 80 | 81 | 82 | def print_objfile_fp(mm, arfile='all'): 83 | cols = mm.used_regions 84 | tbl, totals = _build_table_header(cols, 'OBJFILE') 85 | 86 | if arfile == 'all': 87 | objfiles = mm.used_objfiles 88 | else: 89 | objfiles = mm.arfile_objfiles(arfile) 90 | 91 | for objfile in objfiles: 92 | nextrow = mm.get_objfile_fp(objfile) 93 | totals = _add_row(tbl, objfile, nextrow, totals) 94 | 95 | _add_totals_row(tbl, totals) 96 | _render_table(tbl) 97 | 98 | 99 | def print_arfile_fp(mm): 100 | cols = mm.used_regions 101 | tbl, totals = _build_table_header(cols, 'ARFILE') 102 | 103 | for arfile in mm.used_arfiles: 104 | nextrow = mm.get_arfile_fp(arfile) 105 | totals = _add_row(tbl, arfile, nextrow, totals) 106 | 107 | _add_totals_row(tbl, totals) 108 | _render_table(tbl) 109 | 110 | 111 | def print_file_fp(mm): 112 | cols = mm.used_regions 113 | tbl, totals = _build_table_header(cols, 'FILE') 114 | 115 | objfiles, arfiles = mm.used_files 116 | 117 | for objfile in objfiles: 118 | nextrow = mm.get_objfile_fp(objfile) 119 | totals = _add_row(tbl, objfile, nextrow, totals) 120 | 121 | for arfile in arfiles: 122 | nextrow = mm.get_arfile_fp(arfile) 123 | totals = _add_row(tbl, arfile, nextrow, totals) 124 | 125 | _add_totals_row(tbl, totals) 126 | _render_table(tbl) 127 | 128 | 129 | def print_sectioned_fp(mm): 130 | cols = mm.used_sections 131 | tbl, totals = _build_table_header(cols, 'FILE') 132 | 133 | arfiles = [] 134 | objfiles = mm.used_objfiles 135 | # objfiles, arfiles = mm.used_files 136 | 137 | for objfile in objfiles: 138 | nextrow = mm.get_objfile_fp_secs(objfile) 139 | totals = _add_row(tbl, objfile, nextrow, totals) 140 | 141 | for arfile in arfiles: 142 | nextrow = mm.get_arfile_fp_secs(arfile) 143 | totals = _add_row(tbl, arfile, nextrow, totals) 144 | 145 | _add_totals_row(tbl, totals) 146 | _render_table(tbl) 147 | 148 | 149 | def print_files_list(fl): 150 | for f in sorted(set(fl)): 151 | if f: 152 | print(f) 153 | 154 | 155 | def print_loaded_files(sm): 156 | for s in sorted(set(sm.loaded_files)): 157 | print(s) 158 | 159 | 160 | def print_aliases(sm): 161 | print(sm.memory_map.aliases) 162 | 163 | 164 | def _get_parser(): 165 | parser = argparse.ArgumentParser() 166 | parser.add_argument('mapfile', 167 | help='GCC generated Map file to analyze.') 168 | parser.add_argument('-v', '--verbose', 169 | help='Include detailed warnings in the output.', 170 | action='count', default=0) 171 | parser.add_argument('-p', '--profile', metavar='PROFILE', 172 | choices=profiles.keys(), default='auto') 173 | action = parser.add_mutually_exclusive_group(required=True) 174 | action.add_argument('--sar', action='store_true', 175 | help='Print summary of usage per included file.') 176 | action.add_argument('--sobj', metavar='ARFILE', 177 | help="Print summary of usage per included object " 178 | "file. Specify '.a' filename or 'all'.") 179 | action.add_argument('--ssym', metavar='FILE', 180 | help="Print summary of usage per included symbol. " 181 | "Specify '.ar' or '.o' filename or 'all'.") 182 | action.add_argument('--ssec', action='store_true', 183 | help='Print sectioned summary of usage.') 184 | action.add_argument('--lmap', metavar='ROOT', 185 | help="Print descendent nodes in the linker map. " 186 | "Specify node for which descendents should be " 187 | "printed, or 'root'.") 188 | action.add_argument('--lobj', metavar='OBJFILE', 189 | help="Print nodes from the specified obj file.") 190 | action.add_argument('--lar', metavar='ARFILE', 191 | help="Print nodes from the specified ar file.") 192 | action.add_argument('--uf', action='store_true', 193 | help='Print list of all used files.') 194 | action.add_argument('--uarf', action='store_true', 195 | help='Print list of used ar files.') 196 | action.add_argument('--uobjf', action='store_true', 197 | help='Print list of used object files.') 198 | action.add_argument('--uregions', action='store_true', 199 | help='Print list of used regions.') 200 | action.add_argument('--usections', action='store_true', 201 | help='Print list of used sections.') 202 | action.add_argument('--lfa', action='store_true', 203 | help='Print list of loaded files.') 204 | action.add_argument('--la', action='store_true', 205 | help='Print list of detected aliases.') 206 | action.add_argument('--addr', metavar='ADDRESS', 207 | help='Describe contents at specified address.') 208 | return parser 209 | 210 | 211 | def main(): 212 | parser = _get_parser() 213 | args = parser.parse_args() 214 | if args.verbose == 0: 215 | logging.basicConfig(level=logging.ERROR) 216 | elif args.verbose == 1: 217 | logging.basicConfig(level=logging.WARNING) 218 | elif args.verbose == 2: 219 | logging.basicConfig(level=logging.INFO) 220 | elif args.verbose == 3: 221 | logging.basicConfig(level=logging.DEBUG) 222 | if args.profile == 'auto': 223 | pname = guess_profile(args.mapfile) 224 | else: 225 | pname = args.profile 226 | profile = get_profile(pname) 227 | state_machine = process_map_file(args.mapfile, profile=profile) 228 | if args.sar: 229 | print_file_fp(state_machine.memory_map) 230 | elif args.sobj: 231 | print_objfile_fp(state_machine.memory_map, arfile=args.sobj) 232 | elif args.ssym: 233 | print_symbol_fp(state_machine.memory_map, lfile=args.ssym) 234 | elif args.ssec: 235 | print_sectioned_fp(state_machine.memory_map) 236 | elif args.uf: 237 | ol, al = state_machine.memory_map.used_files 238 | print_files_list(ol + al) 239 | elif args.uarf: 240 | print_files_list(state_machine.memory_map.used_arfiles) 241 | elif args.uobjf: 242 | print_files_list(state_machine.memory_map.used_objfiles) 243 | elif args.usections: 244 | print_files_list(state_machine.memory_map.used_sections) 245 | elif args.uregions: 246 | print_files_list(state_machine.memory_map.used_regions) 247 | elif args.lfa: 248 | print_files_list(state_machine.loaded_files) 249 | elif args.la: 250 | print_aliases(state_machine) 251 | elif args.lmap: 252 | if args.lmap == 'root': 253 | for node in state_machine.memory_map.top_level_nodes: 254 | print(node) 255 | else: 256 | n = state_machine.memory_map.get_node(args.lmap) 257 | for node in n.all_nodes(): 258 | print(node) 259 | elif args.lar: 260 | for node in state_machine.memory_map.root.all_nodes(): 261 | if node.arfile == args.lar: 262 | print(node) 263 | elif args.lobj: 264 | for node in state_machine.memory_map.root.all_nodes(): 265 | if node.objfile == args.lobj: 266 | print(node) 267 | elif args.addr: 268 | for node in state_machine.memory_map.root.all_nodes(): 269 | if node.contains_address(args.addr): 270 | print(node) 271 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | 2 | Usage 3 | ===== 4 | 5 | The primary entry point for use of ``fpvgcc`` is as a console script. The 6 | ``fpvgcc`` console entry point supports a variety of analysis functions, each 7 | of which essentially recasts the information contained in the provided mapfile 8 | in a different way. 9 | 10 | Script usage and arguments are listed here. This help listing can also be 11 | obtained on the command line with ``fpvgcc --help``. 12 | 13 | .. argparse:: 14 | :module: fpvgcc.cli 15 | :func: _get_parser 16 | :prog: fpvgcc 17 | :nodefault: 18 | 19 | The various available analysis functions are described below. Additional 20 | analysis may be possible using changes to the code and/or direct manipulation 21 | of the parsed memory map in the python interpreter / shell, and is not covered 22 | in this documentation. 23 | 24 | Memory Utilization Summaries 25 | ---------------------------- 26 | 27 | These functions print out a concise summary of memory utilization. 28 | 29 | .. rubric:: --sar 30 | 31 | Prints out a summary of memory utilization per library archive file, sorted by 32 | the total static memory footprint of each file. Object files which were included 33 | directly show up here as object files. 34 | 35 | .. code-block:: console 36 | 37 | $ fpvgcc app.map --sar 38 | +-----------------------------------+--------+--------+----------+------+------+-------+-------+ 39 | | FILE | VECT47 | VECT57 | RESETVEC | ROM | RAM | HIROM | TOTAL | 40 | +-----------------------------------+--------+--------+----------+------+------+-------+-------+ 41 | | TOTALS | 2 | 2 | 2 | 6588 | 1222 | 0 | | 42 | | libmodbus-msp430f5529.a | 0 | 0 | 0 | 2594 | 360 | 0 | 2954 | 43 | (...) (...) (...) (...) 44 | | crtend.o | 0 | 0 | 0 | 36 | 2 | 0 | 38 | 45 | | crtn.o | 0 | 0 | 0 | 12 | 0 | 0 | 12 | 46 | | libprintf-msp430f5529.a | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 47 | | libmul_f5.a | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 48 | +-----------------------------------+--------+--------+----------+------+------+-------+-------+ 49 | 50 | .. rubric:: --sobj ARFILE 51 | 52 | Prints out a summary of memory utilization per object file, sorted by the total 53 | static memory footprint of each file. 54 | 55 | The ``ARFILE`` specified should be one of the following : 56 | 57 | - ``all`` : All object files included 58 | - An archive file : Object files provided by that archive file are only listed 59 | 60 | .. code-block:: console 61 | 62 | $ fpvgcc app.map --sobj libc.a 63 | +-----------------+--------+--------+----------+-----+-----+-------+-------+ 64 | | OBJFILE | VECT47 | VECT57 | RESETVEC | ROM | RAM | HIROM | TOTAL | 65 | +-----------------+--------+--------+----------+-----+-----+-------+-------+ 66 | | TOTALS | 0 | 0 | 0 | 96 | 0 | 0 | | 67 | | lib_a-memmove.o | 0 | 0 | 0 | 58 | 0 | 0 | 58 | 68 | | lib_a-memcpy.o | 0 | 0 | 0 | 20 | 0 | 0 | 20 | 69 | | lib_a-memset.o | 0 | 0 | 0 | 18 | 0 | 0 | 18 | 70 | +-----------------+--------+--------+----------+-----+-----+-------+-------+ 71 | 72 | .. rubric:: --ssym FILE 73 | 74 | Prints out a summary of memory utilization per symbol, sorted by the total 75 | static memory footprint of each symbol. 76 | 77 | The ``FILE`` specified should be one of the following : 78 | 79 | - ``all`` : All symbols included 80 | - An object file : Symbols provided by that object file are only listed 81 | - An archive file : Symbols provided by that archive file are only listed 82 | 83 | .. code-block:: console 84 | 85 | $ fpvgcc app.map --ssym libc.a 86 | +-----------------+--------+--------+----------+-----+-----+-------+-------+ 87 | | SYMBOL | VECT47 | VECT57 | RESETVEC | ROM | RAM | HIROM | TOTAL | 88 | +-----------------+--------+--------+----------+-----+-----+-------+-------+ 89 | | TOTALS | 0 | 0 | 0 | 96 | 0 | 0 | | 90 | | memmove | 0 | 0 | 0 | 58 | 0 | 0 | 58 | 91 | | memcpy | 0 | 0 | 0 | 20 | 0 | 0 | 20 | 92 | | memset | 0 | 0 | 0 | 18 | 0 | 0 | 18 | 93 | | lib_a-memset_o | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 94 | | lib_a-memmove_o | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 95 | | lib_a-memcpy_o | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 96 | +-----------------+--------+--------+----------+-----+-----+-------+-------+ 97 | 98 | .. rubric:: --ssec 99 | 100 | Prints out a summary of memory utilization per object file, per section. 101 | 102 | The --ssec output can get pretty garbled very easily. The table that it results 103 | in is simply far too large (wide), and each line overflows (wraps) into a 104 | number of lines with even a slightly non-trivial program. 105 | 106 | It exists because at some point in the distant future, when I have the time, 107 | I would want to put in a web or desktop UI which would be able to handle the 108 | details, with baobab or filelight as a model of what I would want it to 109 | look and feel like. 110 | 111 | As it stands, the per-section split of memory utilization is rarely useful. 112 | I would recommend using the other more compact and useful outputs instead, 113 | starting with --sar followed by --ssym all. 114 | 115 | Pull requests which imrprove the output of print_sectioned_fp() of cli.py are 116 | always welcome. 117 | 118 | 119 | Linker Map Nodes 120 | ---------------- 121 | 122 | These functions print out a (relatively) concise version of all linker map 123 | nodes satisfying certain criteria. The output contains all nodes satisfying the 124 | given criteria, including those in DISCARDED sections. 125 | 126 | .. rubric:: --lmap ROOT 127 | 128 | Prints out all linker map nodes which are apparant descendents of the given 129 | root node. The ``ROOT`` node **must** be provided. 130 | 131 | If ROOT is 'root', i.e., the root node of the entire linker map, the output 132 | contains all the top level nodes (first children of 'root') of the linker map, 133 | and only the top level nodes. 134 | 135 | For all other provided nodes, the output contains all descendents. 136 | 137 | .. code-block:: console 138 | 139 | $ fpvgcc app.map --lmap root 140 | .__interrupt_vector_1....................................... UNDEF 141 | (...) 142 | .__interrupt_vector_47......................................0x0000ffdc 2 2 2 VECT47 uart_handlers.c.obj 143 | (...) 144 | .__reset_vector.............................................0x0000fffe 2 2 RESETVEC 145 | .rodata.....................................................0x00004400 234 234 ROM 146 | (...) 147 | .bss........................................................0x00002414 1202 1202 RAM 148 | (...) 149 | .lowtext....................................................0x00004550 102 102 ROM 150 | .text.......................................................0x00005cca 6172 6172 ROM slli.o 151 | (...) 152 | 153 | .. code-block:: console 154 | 155 | $ fpvgcc app.map --lmap .lowtext 156 | .lowtext....................................................0x00004550 102 102 ROM 157 | .lowtext.crt_0000start......................................0x00004550 4 4 ROM crt0.o 158 | .lowtext.crt_0100init_bss...................................0x00004554 14 14 ROM crt_bss.o 159 | .lowtext.crt_0300movedata...................................0x00004562 20 20 ROM crt_movedata.o 160 | .lowtext.crt_0700call_init_then_main........................0x00004576 10 10 ROM crt_main.o 161 | .lowtext.crt_0900main_init..................................0x00004580 54 54 ROM crt0.o 162 | 163 | .. rubric:: --lobj OBJFILE 164 | 165 | Prints out all linker map nodes that originated from the specified object file. 166 | 167 | .. code-block:: console 168 | 169 | $ fpvgcc app.map --lobj crt_bss.o 170 | .lowtext.crt_0100init_bss...................................0x00004554 14 14 ROM crt_bss.o 171 | .MSP430.attributes.crt_bss_o................................0x00000353 23 23 DISCARDED crt_bss.o 172 | 173 | .. rubric:: --lar ARFILE 174 | 175 | Prints out all linker map nodes that originated from the specified library 176 | archive file. 177 | 178 | .. code-block:: console 179 | 180 | $ fpvgcc app.map --lar libc.a 181 | .text.memcpy................................................0x00005d3e 20 20 ROM lib_a-memcpy.o 182 | .text.memset................................................0x00005d52 18 18 ROM lib_a-memset.o 183 | .text.memmove...............................................0x00005d64 58 58 ROM lib_a-memmove.o 184 | .MSP430.attributes.lib_a-memcpy_o...........................0x0000030e 23 23 DISCARDED lib_a-memcpy.o 185 | .MSP430.attributes.lib_a-memset_o...........................0x00000325 23 23 DISCARDED lib_a-memset.o 186 | .MSP430.attributes.lib_a-memmove_o..........................0x00000398 23 23 DISCARDED lib_a-memmove.o 187 | .comment.lib_a-memcpy_o.....................................0x00000041 66 66 DISCARDED lib_a-memcpy.o 188 | .comment.lib_a-memset_o.....................................0x00000041 66 66 DISCARDED lib_a-memset.o 189 | .comment.lib_a-memmove_o....................................0x00000041 66 66 DISCARDED lib_a-memmove.o 190 | 191 | 192 | Reverse Address Lookup 193 | ---------------------- 194 | 195 | Given a memory location / address, this function can be used to quickly 196 | determine what exists there. It is expected that this will be useful when 197 | looking through generated assembly listings. 198 | 199 | Example: 200 | 201 | .. code-block:: console 202 | 203 | $ fpvgcc app.map --addr 0x242e 204 | .bss........................................................0x00002414 1202 1202 RAM 205 | .bss.privateXT1ClockFrequency...............................0x0000242e 4 4 RAM ucs.c.obj 206 | $ fpvgcc app.map --addr 0x475d 207 | .text.clock_set_default.....................................0x000046ce 144 144 ROM core_impl.c.obj 208 | 209 | 210 | Other Information 211 | ----------------- 212 | 213 | .. rubric:: --lfa 214 | 215 | Prints a list of all loaded files. These are all the files that were provided 216 | to the linker. It is not necessary that all of these files have found their way 217 | into the output. 218 | 219 | Example : 220 | 221 | .. code-block:: console 222 | 223 | $ fpvgcc app.map --lfa 224 | ../peripherals/libhal-uc-core-msp430f5529.a 225 | (...) 226 | /opt/ti/msp430/gcc/bin/../lib/gcc/msp430-elf/5.3.0/../../../../msp430-elf/lib/crt0.o 227 | (...) 228 | /opt/ti/msp430/gcc/bin/../lib/gcc/msp430-elf/5.3.0/crtbegin.o 229 | (...) 230 | /opt/ti/msp430/gcc/bin/../lib/gcc/msp430-elf/5.3.0/crtend.o 231 | (...) 232 | CMakeFiles/firmware-msp430f5529.elf.dir/main.c.obj 233 | (...) 234 | 235 | 236 | .. rubric:: --uf 237 | 238 | Prints out a list of input files which have non-zero footprint in the output. 239 | If any of the used object files came from a library archive, then only the 240 | library archive is listed. If the object files were used directly, then the 241 | object file is listed. All elements in the output are necessarily represented 242 | by some file in this list, and all these files probably exist(ed) somewhere 243 | in the build tree at the link-time. 244 | 245 | .. code-block:: console 246 | 247 | $ fpvgcc app.map --uf 248 | crt0.o 249 | libucdm-msp430f5529.a 250 | (...) 251 | main.c.obj 252 | 253 | .. rubric:: --uarf 254 | 255 | Prints out a list of input library archives (.a/.ar) which have non-zero 256 | footprint in the output. Any elements from object files which were used 257 | directly are not represented in this output. 258 | 259 | .. code-block:: console 260 | 261 | $ fpvgcc app.map --uarf 262 | libc.a 263 | libcrt.a 264 | libgcc.a 265 | libhal-uc-core-msp430f5529.a 266 | (...) 267 | 268 | .. rubric:: --uobjf 269 | 270 | Prints out a list of input object files (.out) which have non-zero 271 | footprint in the output. All elements in the output are necessarily 272 | represented by some file in this list, though remember that some of 273 | these object files actually exist inside library archives. 274 | 275 | .. code-block:: console 276 | 277 | $ fpvgcc app.map --uobjf 278 | _ashldi3.o 279 | _clz.o 280 | _clzdi2.o 281 | _lshrdi3.o 282 | _muldi3.o 283 | _udivdi3.o 284 | bytebuf.c.obj 285 | core_impl.c.obj 286 | crt0.o 287 | (...) 288 | 289 | .. rubric:: --uregions 290 | 291 | Prints out a list of used memory regions. 292 | 293 | .. code-block:: console 294 | 295 | $ fpvgcc app.map --uregions 296 | HIROM 297 | RAM 298 | RESETVEC 299 | ROM 300 | VECT47 301 | VECT57 302 | 303 | .. rubric:: --usections 304 | 305 | Prints out a list of used memory sections. 306 | 307 | .. code-block:: console 308 | 309 | $ fpvgcc app.map --usections 310 | .__interrupt_vector_47 311 | .__interrupt_vector_57 312 | .__reset_vector 313 | .bss 314 | .data 315 | .lowtext 316 | .rodata 317 | .rodata2 318 | .text 319 | 320 | .. rubric:: --la 321 | 322 | Prints out a list of detected / assumed section aliases. 323 | 324 | .. code-block:: console 325 | 326 | $ fpvgcc app.map --la 327 | __TI_build_attributes -> .MSP430.attributes 328 | .gnu.attributes -> .MSP430.attributes 329 | __interrupt_vector_rtc -> .__interrupt_vector_42 330 | __interrupt_vector_port2 -> .__interrupt_vector_43 331 | (...) 332 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # This file is execfile()d with the current directory set to its 4 | # containing dir. 5 | # 6 | # Note that not all possible configuration values are present in this 7 | # autogenerated file. 8 | # 9 | # All configuration values have a default; values that are commented out 10 | # serve to show the default. 11 | 12 | import sys 13 | import os 14 | from pkg_resources import get_distribution 15 | 16 | _github_repo = 'fpv-gcc' 17 | _github_user = 'ebs-universe' 18 | 19 | _package_name = u'fpvgcc' 20 | _package_author = u'Chintalagiri Shashank' 21 | _package_copyright = u'2015-19' 22 | _package_logo = '_static/logo.png' 23 | _package_favicon = '_static/favicon.ico' 24 | 25 | _dist = get_distribution(_package_name) 26 | _package_release = _dist.version 27 | _package_description = '' 28 | for m in _dist._get_metadata(_dist.PKG_INFO): 29 | if m.startswith('Summary:'): 30 | _package_description = m.split(':')[1] 31 | 32 | # If extensions (or modules to document with autodoc) are in another directory, 33 | # add these directories to sys.path here. If the directory is relative to the 34 | # documentation root, use os.path.abspath to make it absolute, like shown here. 35 | 36 | sys.path.insert(0, os.path.abspath(os.pardir)) 37 | autodoc_default_options = { 38 | 'members': None, 'undoc-members': None, 39 | 'private-members': None, 'show-inheritance': None 40 | } 41 | autodoc_member_order = 'bysource' 42 | autoclass_content = 'init' 43 | 44 | # -- General configuration ------------------------------------------------ 45 | 46 | # If your documentation needs a minimal Sphinx version, state it here. 47 | #needs_sphinx = '1.0' 48 | 49 | # Add any Sphinx extension module names here, as strings. They can be 50 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 51 | # ones. 52 | extensions = [ 53 | 'sphinx.ext.autodoc', 54 | 'sphinx.ext.intersphinx', 55 | 'sphinx.ext.todo', 56 | 'sphinx.ext.coverage', 57 | 'sphinx.ext.viewcode', 58 | 'sphinxarg.ext', 59 | ] 60 | 61 | # Add any paths that contain templates here, relative to this directory. 62 | templates_path = ['_templates'] 63 | 64 | # The suffix(es) of source filenames. 65 | # You can specify multiple suffix as a list of string: 66 | # source_suffix = ['.rst', '.md'] 67 | source_suffix = '.rst' 68 | 69 | # The encoding of source files. 70 | #source_encoding = 'utf-8-sig' 71 | 72 | # The master toctree document. 73 | master_doc = 'index' 74 | 75 | # General information about the project. 76 | project = _package_name 77 | copyright = u'{0}, {1}'.format(_package_copyright, _package_author) 78 | author = _package_author 79 | 80 | # The version info for the project you're documenting, acts as replacement for 81 | # |version| and |release|, also used in various other places throughout the 82 | # built documents. 83 | # 84 | # The full version, including alpha/beta/rc tags. 85 | release = _package_release 86 | 87 | # The short X.Y version. 88 | version = '.'.join(release.split('.')[:2]) 89 | 90 | # The language for content autogenerated by Sphinx. Refer to documentation 91 | # for a list of supported languages. 92 | # 93 | # This is also used if you do content translation via gettext catalogs. 94 | # Usually you set "language" from the command line for these cases. 95 | language = None 96 | 97 | # List of patterns, relative to source directory, that match files and 98 | # directories to ignore when looking for source files. 99 | # This patterns also effect to html_static_path and html_extra_path 100 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 101 | 102 | # The reST default role (used for this markup: `text`) to use for all 103 | # documents. 104 | #default_role = None 105 | 106 | # If true, '()' will be appended to :func: etc. cross-reference text. 107 | #add_function_parentheses = True 108 | 109 | # If true, the current module name will be prepended to all description 110 | # unit titles (such as .. function::). 111 | #add_module_names = True 112 | 113 | # If true, sectionauthor and moduleauthor directives will be shown in the 114 | # output. They are ignored by default. 115 | #show_authors = False 116 | 117 | # The name of the Pygments (syntax highlighting) style to use. 118 | pygments_style = 'sphinx' 119 | 120 | # A list of ignored prefixes for module index sorting. 121 | #modindex_common_prefix = [] 122 | 123 | # If true, keep warnings as "system message" paragraphs in the built documents. 124 | #keep_warnings = False 125 | 126 | # If true, `todo` and `todoList` produce output, else they produce nothing. 127 | todo_include_todos = True 128 | 129 | 130 | # -- Options for HTML output ---------------------------------------------- 131 | 132 | import alabaster 133 | 134 | # Add any paths that contain custom themes here, relative to this directory. 135 | html_theme_path = [alabaster.get_path()] 136 | 137 | # The theme to use for HTML and HTML Help pages. See the documentation for 138 | # a list of builtin themes. 139 | html_theme = "alabaster" 140 | 141 | # Theme options are theme-specific and customize the look and feel of a theme 142 | # further. For a list of options available for each theme, see the 143 | # documentation. 144 | html_theme_options = { 145 | 'description': _package_description, 146 | 'fixed_sidebar': False, 147 | 'touch_icon': 'favicon.ico', 148 | 'github_repo': _github_repo, 149 | 'github_user': _github_user, 150 | } 151 | 152 | # The name for this set of Sphinx documents. If None, it defaults to 153 | # " v documentation". 154 | # html_title = None 155 | 156 | # A shorter title for the navigation bar. Default is the same as html_title. 157 | # html_short_title = '{0} v{1}'.format(project, version) 158 | 159 | # The name of an image file (relative to this directory) to place at the top 160 | # of the sidebar. 161 | html_logo = _package_logo 162 | 163 | # The name of an image file (relative to this directory) to use as a favicon of 164 | # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 165 | # pixels large. 166 | html_favicon = _package_favicon 167 | 168 | # Add any paths that contain custom static files (such as style sheets) here, 169 | # relative to this directory. They are copied after the builtin static files, 170 | # so a file named "default.css" will overwrite the builtin "default.css". 171 | html_static_path = ['_static'] 172 | 173 | # Add any extra paths that contain custom files (such as robots.txt or 174 | # .htaccess) here, relative to this directory. These files are copied 175 | # directly to the root of the documentation. 176 | #html_extra_path = [] 177 | 178 | # Custom sidebar templates, must be a dictionary that maps document names 179 | # to template names. 180 | # 181 | # This is required for the alabaster theme 182 | # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars 183 | html_sidebars = { 184 | '**': [ 185 | 'about.html', 186 | 'navigation.html', 187 | 'relations.html', 188 | 'searchbox.html', 189 | 'donate.html', 190 | ] 191 | } 192 | 193 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 194 | # using the given strftime format. 195 | #html_last_updated_fmt = '%b %d, %Y' 196 | 197 | # If true, SmartyPants will be used to convert quotes and dashes to 198 | # typographically correct entities. 199 | #html_use_smartypants = True 200 | 201 | # Additional templates that should be rendered to pages, maps page names to 202 | # template names. 203 | #html_additional_pages = {} 204 | 205 | # If false, no module index is generated. 206 | #html_domain_indices = True 207 | 208 | # If false, no index is generated. 209 | #html_use_index = True 210 | 211 | # If true, the index is split into individual pages for each letter. 212 | #html_split_index = False 213 | 214 | # If true, links to the reST sources are added to the pages. 215 | #html_show_sourcelink = True 216 | 217 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 218 | #html_show_sphinx = True 219 | 220 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 221 | #html_show_copyright = True 222 | 223 | # If true, an OpenSearch description file will be output, and all pages will 224 | # contain a tag referring to it. The value of this option must be the 225 | # base URL from which the finished HTML is served. 226 | #html_use_opensearch = '' 227 | 228 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 229 | #html_file_suffix = None 230 | 231 | # Language to be used for generating the HTML full-text search index. 232 | # Sphinx supports the following languages: 233 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 234 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' 235 | #html_search_language = 'en' 236 | 237 | # A dictionary with options for the search language support, empty by default. 238 | # Now only 'ja' uses this config value 239 | #html_search_options = {'type': 'default'} 240 | 241 | # The name of a javascript file (relative to the configuration directory) that 242 | # implements a search results scorer. If empty, the default will be used. 243 | #html_search_scorer = 'scorer.js' 244 | 245 | # -- Options for HTMLHelp output ------------------------------------------ 246 | 247 | # Output file base name for HTML help builder. 248 | htmlhelp_basename = '{0}-doc'.format(_package_name) 249 | 250 | # -- Options for LaTeX output --------------------------------------------- 251 | 252 | from sphinx.highlighting import PygmentsBridge 253 | from pygments.formatters.latex import LatexFormatter 254 | 255 | 256 | class CustomLatexFormatter(LatexFormatter): 257 | def __init__(self, **options): 258 | super(CustomLatexFormatter, self).__init__(**options) 259 | self.verboptions = r"formatcom=\footnotesize" 260 | 261 | 262 | PygmentsBridge.latex_formatter = CustomLatexFormatter 263 | 264 | latex_maketitle_override = r''' 265 | \makeatletter 266 | \renewcommand{\maketitle}{ 267 | \begingroup 268 | % These \defs are required to deal with multi-line authors; it 269 | % changes \\ to ', ' (comma-space), making it pass muster for 270 | % generating document info in the PDF file. 271 | \def\\{, } 272 | \def\and{and } 273 | \pdfinfo{ 274 | /Author (\@author) 275 | /Title (\@title) 276 | } 277 | \endgroup 278 | \noindent\begin{minipage}{0.3\textwidth} 279 | \sphinxlogo% 280 | \end{minipage} 281 | \thispagestyle{empty} 282 | \hfill 283 | \begin{minipage}{0.65\textwidth} 284 | \begin{flushright} 285 | {\rm\Huge\py@HeaderFamily \@title} \par 286 | {\em\large\py@HeaderFamily \py@release\releaseinfo,} {\em\@date}\par 287 | \vspace{25pt} 288 | {\large\py@HeaderFamily 289 | \begin{tabular}[t]{c} 290 | \@author 291 | \end{tabular}} \par 292 | \py@authoraddress \par 293 | \end{flushright} 294 | \@thanks 295 | \end{minipage} 296 | \setcounter{footnote}{0} 297 | \let\thanks\relax\let\maketitle\relax 298 | %\gdef\@thanks{}\gdef\@author{}\gdef\@title{} 299 | } 300 | \makeatother 301 | ''' 302 | 303 | latex_pagestyle_override = r""" 304 | \makeatletter 305 | \fancypagestyle{normal}{ 306 | \fancyhf{} 307 | \fancyhead[L]{\rightmark} 308 | \fancyhead[C]{\@title, \py@release} 309 | \fancyhead[R]{\thepage} 310 | \fancyfoot[R]{\includegraphics[]{logo_packed.png}} 311 | } 312 | \makeatother 313 | """ 314 | 315 | # \renewcommand{\headrulewidth}{0.4pt} 316 | # \renewcommand{\footrulewidth}{0.4pt} 317 | 318 | latex_elements = { 319 | # The paper size ('letterpaper' or 'a4paper'). 320 | # 'papersize': 'letterpaper', 321 | 322 | # The font size ('10pt', '11pt' or '12pt'). 323 | 'pointsize': '9pt', 324 | 325 | # Additional stuff for the LaTeX preamble. 326 | 'preamble': r'\definecolor{VerbatimBorderColor}{rgb}{1,1,1}' + 327 | latex_maketitle_override + 328 | latex_pagestyle_override, 329 | 330 | 'maketitle': r'\maketitle', 331 | 'tableofcontents': r'', 332 | # Latex figure (float) alignment 333 | # 'figure_align': 'htbp', 334 | 'extraclassoptions': 'openany', 335 | 'printindex': r'\footnotesize\raggedright\printindex', 336 | 'fncychap': '\\usepackage[Bjornstrup]{fncychap}', 337 | # 'sphinxsetup': 'vmargin={0.7in,1in}' 338 | } 339 | 340 | # Grouping the document tree into LaTeX files. List of tuples 341 | # (source start file, target name, title, 342 | # author, documentclass [howto, manual, or own class]). 343 | latex_documents = [( 344 | master_doc, 345 | '{0}.tex'.format(_package_name), 346 | u'{0} Documentation'.format(_package_name), 347 | _package_author, 'howto'), 348 | ] 349 | 350 | # The name of an image file (relative to this directory) to place at the top of 351 | # the title page. 352 | if _package_logo: 353 | latex_logo = _package_logo 354 | 355 | # For "manual" documents, if this is true, then toplevel headings are parts, 356 | # not chapters. 357 | #latex_use_parts = False 358 | 359 | # If true, show page references after internal links. 360 | #latex_show_pagerefs = False 361 | 362 | # If true, show URL addresses after external links. 363 | latex_show_urls = 'footnote' 364 | 365 | # Documents to append as an appendix to all manuals. 366 | #latex_appendices = [] 367 | 368 | # If false, no module index is generated. 369 | latex_domain_indices = False 370 | 371 | # latex_toplevel_sectioning = 'chapter' 372 | 373 | 374 | # -- Options for manual page output --------------------------------------- 375 | 376 | # One entry per manual page. List of tuples 377 | # (source start file, name, description, authors, manual section). 378 | man_pages = [( 379 | master_doc, _package_name, 380 | u'{0} Documentation'.format(_package_name), 381 | [author], 1) 382 | ] 383 | 384 | # If true, show URL addresses after external links. 385 | #man_show_urls = False 386 | 387 | 388 | # -- Options for Texinfo output ------------------------------------------- 389 | 390 | # Grouping the document tree into Texinfo files. List of tuples 391 | # (source start file, target name, title, author, 392 | # dir menu entry, description, category) 393 | texinfo_documents = [( 394 | master_doc, _package_name, u'{0} Documentation'.format(_package_name), 395 | author, _package_name, _package_description, 396 | 'Miscellaneous'), 397 | ] 398 | 399 | # Documents to append as an appendix to all manuals. 400 | #texinfo_appendices = [] 401 | 402 | # If false, no module index is generated. 403 | #texinfo_domain_indices = True 404 | 405 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 406 | #texinfo_show_urls = 'footnote' 407 | 408 | # If true, do not generate a @detailmenu in the "Top" node's menu. 409 | #texinfo_no_detailmenu = False 410 | 411 | 412 | # Example configuration for intersphinx: refer to the Python standard library. 413 | intersphinx_mapping = {'https://docs.python.org/3': None} 414 | -------------------------------------------------------------------------------- /src/fpvgcc/gccMemoryMap.py: -------------------------------------------------------------------------------- 1 | 2 | # Copyright (C) 2015 Quazar Technologies Pvt. Ltd. 3 | # 2015 Chintalagiri Shashank 4 | # 5 | # This file is part of fpv-gcc. 6 | # 7 | # fpv-gcc is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # fpv-gcc is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with fpv-gcc. If not, see . 19 | 20 | 21 | import logging 22 | from functools import cached_property 23 | 24 | from fpvgcc.datastructures.ntreeSize import SizeNTree, SizeNTreeNode 25 | 26 | 27 | class LinkAliases(object): 28 | def __init__(self): 29 | self._aliases = {} 30 | 31 | def register_alias(self, target, alias): 32 | if alias in self._aliases.keys(): 33 | if target != self._aliases[alias]: 34 | logging.warning("Alias Collision : {0} :: {1} ; {2}" 35 | "".format(alias, target, self._aliases[alias])) 36 | else: 37 | self._aliases[alias] = target 38 | 39 | def encode(self, name): 40 | for key in self._aliases.keys(): 41 | if name.startswith(key): 42 | # if alias.startswith(linkermap_section.gident): 43 | # alias = alias[len(linkermap_section.gident):] 44 | return self._aliases[key] + name 45 | return name 46 | 47 | def __repr__(self): 48 | return '\n'.join(["{0:>38} -> {1:<38}".format(a, t) 49 | for (a, t) in sorted(self._aliases.items(), 50 | key=lambda x: x[1])]) 51 | 52 | 53 | class GCCMemoryMapNode(SizeNTreeNode): 54 | _leaf_property = '_size' 55 | _ident_property = 'name' 56 | 57 | def __init__(self, parent=None, node_t=None, 58 | name=None, address=None, size=None, fillsize=None, 59 | arfile=None, objfile=None, arfolder=None): 60 | super(GCCMemoryMapNode, self).__init__(parent, node_t) 61 | self._size = None 62 | if name is None: 63 | if objfile is not None: 64 | name = objfile 65 | else: 66 | name = "" 67 | self.name = name 68 | if address is not None: 69 | self._address = int(address, 16) 70 | else: 71 | self._address = None 72 | if size is not None: 73 | self._defsize = int(size, 16) 74 | else: 75 | self._defsize = None 76 | self.arfolder = arfolder 77 | self.arfile = arfile 78 | self.objfile = objfile 79 | self._fillsize = None 80 | self.fillsize = fillsize 81 | 82 | @cached_property 83 | def ctx(self): 84 | return self.parent.ctx 85 | 86 | @property 87 | def address(self): 88 | if self._address is not None: 89 | return format(self._address, '#010x') 90 | else: 91 | return "" 92 | 93 | @address.setter 94 | def address(self, value): 95 | self._address = int(value, 16) 96 | 97 | def contains_address(self, addr): 98 | if not self.address or self.region in ['DISCARDED', 'UNDEF']: 99 | return False 100 | if int(self.address, 0) <= int(addr, 0) < \ 101 | (int(self.address, 0) + self.size): 102 | return True 103 | return False 104 | 105 | @property 106 | def defsize(self): 107 | return self._defsize 108 | 109 | @defsize.setter 110 | def defsize(self, value): 111 | self._defsize = int(value, 16) 112 | 113 | @property 114 | def osize(self): 115 | return self._size 116 | 117 | @osize.setter 118 | def osize(self, value): 119 | if len(self.children): 120 | logging.warning("Setting leaf property at a node which " 121 | "has children : {0}".format(self.gident)) 122 | newsize = int(value, 16) 123 | if self._size is not None: 124 | if newsize != self._size: 125 | logging.warning( 126 | "Overwriting leaf property at node : {0} :: {1} -> {2}" 127 | "".format(self.gident, self._size, newsize) 128 | ) 129 | else: 130 | logging.warning("Possibly missing leaf node " 131 | "with same name : {0}".format(self.gident)) 132 | self._size = newsize 133 | 134 | @property 135 | def fillsize(self): 136 | return self._fillsize 137 | 138 | @fillsize.setter 139 | def fillsize(self, value): 140 | if value: 141 | try: 142 | self._fillsize = int(value, 0) 143 | except TypeError: 144 | self._fillsize = int(value) 145 | else: 146 | self._fillsize = 0 147 | 148 | def add_child(self, newchild=None, name=None, 149 | address=None, size=None, fillsize=0, 150 | arfile=None, objfile=None, arfolder=None): 151 | if newchild is None: 152 | nchild = GCCMemoryMapNode(name=name, address=None, size=None, 153 | fillsize=0, arfile=None, objfile=None, 154 | arfolder=None) 155 | newchild = super(GCCMemoryMapNode, self).add_child(nchild) 156 | else: 157 | newchild = super(GCCMemoryMapNode, self).add_child(newchild) 158 | return newchild 159 | 160 | def push_to_leaf(self): 161 | if not self.objfile: 162 | logging.warning("No objfile defined. Can't push to leaf : " 163 | "{0}".format(self.gident)) 164 | return self 165 | for child in self.children: 166 | # TODO This probably discards data which could be preserved 167 | if child.name == self.objfile.replace('.', '_'): 168 | return self 169 | newleaf = self.add_child(name=self.objfile.replace('.', '_')) 170 | if self._defsize is not None: 171 | newleaf.defsize = hex(self._defsize) 172 | if self._address is not None: 173 | newleaf.address = hex(self._address) 174 | if self.fillsize is not None: 175 | newleaf.fillsize = self.fillsize 176 | if self.objfile is not None: 177 | newleaf.objfile = self.objfile 178 | if self.arfile is not None: 179 | newleaf.arfile = self.arfile 180 | if self.arfolder is not None: 181 | newleaf.arfolder = self.arfolder 182 | newleaf.osize = hex(self._size) 183 | 184 | self._size = None 185 | self._defsize = None 186 | if not self.is_toplevelnode: 187 | self._address = None 188 | self.fillsize = None 189 | self.objfile = None 190 | self.arfile = None 191 | self.arfolder = None 192 | 193 | return newleaf 194 | 195 | @property 196 | def leafsize(self): 197 | if self.fillsize is not None: 198 | if self._size is not None: 199 | return self._size + self.fillsize 200 | else: 201 | return self.fillsize 202 | return self._size 203 | 204 | @leafsize.setter 205 | def leafsize(self, value): 206 | raise AttributeError 207 | 208 | @cached_property 209 | def region(self): 210 | ctx = self.ctx 211 | if not isinstance(self.parent, GCCMemoryMap) and \ 212 | self.parent.region == 'DISCARDED': 213 | return 'DISCARDED' 214 | # Suppressed root identifiers for MSP430 GCC. A better mechanism to 215 | # provide user access to manipulate this set is needed. 216 | if ctx and self.name in ctx.suppressed_names: 217 | return 'DISCARDED' 218 | if self._address is None: 219 | return 'UNDEF' 220 | if self._address == 0: 221 | return "DISCARDED" 222 | for region in self.tree.memory_regions: 223 | if self._address in region: 224 | if region.name in ctx.suppressed_regions: 225 | return 'DISCARDED' 226 | return region.name 227 | raise ValueError(self._address) 228 | 229 | @property 230 | def is_leaf_property_set(self): 231 | return self._is_leaf_property_set 232 | 233 | def __repr__(self): 234 | r = '{0:.<60}{1:<15}{2:>10}{6:>10}{3:>10} {5:<15}{4}' \ 235 | ''.format(self.gident, self.address or '', self.defsize or '', 236 | self.size or '', self.objfile or '', self.region, 237 | self._size or '') 238 | return r 239 | 240 | 241 | class GCCMemoryMap(SizeNTree): 242 | # This really needs to be cleaned up. Most of the code here is pretty 243 | # much an example of what NOT to do. 244 | node_t = GCCMemoryMapNode 245 | collapse_vectors = True 246 | 247 | def __init__(self, ctx): 248 | self.ctx = ctx 249 | self.memory_regions = [] 250 | self._vector_regions = [] 251 | self._vector_sections = [] 252 | self.aliases = LinkAliases() 253 | super(GCCMemoryMap, self).__init__() 254 | 255 | @property 256 | def used_regions(self): 257 | ur = ['UNDEF'] 258 | if self.collapse_vectors: 259 | self._vector_regions = [] 260 | ur.append('VEC') 261 | for node in self.root.all_nodes(): 262 | region = node.region 263 | if region not in ur: 264 | if self.collapse_vectors: 265 | if 'VEC' not in region: 266 | ur.append(region) 267 | elif region not in self._vector_regions: 268 | self._vector_regions.append(region) 269 | else: 270 | ur.append(region) 271 | ur.remove('UNDEF') 272 | ur.remove('DISCARDED') 273 | return ur 274 | 275 | @property 276 | def used_objfiles(self): 277 | of = [] 278 | for node in self.root.all_nodes(): 279 | region = node.region 280 | if node.objfile is None and node.leafsize \ 281 | and region not in ['DISCARDED', 'UNDEF']: 282 | logging.warning( 283 | "Object unaccounted for : {0:<40} {1:<15} {2:>5}" 284 | "".format(node.gident, region, str(node.leafsize)) 285 | ) 286 | continue 287 | if node.objfile not in of: 288 | of.append(node.objfile) 289 | return of 290 | 291 | def arfile_objfiles(self, arfile): 292 | of = [] 293 | for node in self.root.all_nodes(): 294 | if node.leafsize and node.region not in ['DISCARDED', 'UNDEF']: 295 | continue 296 | if node.arfile == arfile and node.objfile not in of: 297 | of.append(node.objfile) 298 | return of 299 | 300 | @property 301 | def used_arfiles(self): 302 | af = [] 303 | for node in self.root.all_nodes(): 304 | region = node.region 305 | if node.arfile is None and node.leafsize \ 306 | and region not in ['DISCARDED', 'UNDEF']: 307 | logging.warning( 308 | "Object unaccounted for : {0:<40} {1:<15} {2:>5}" 309 | "".format(node.gident, region, str(node.leafsize)) 310 | ) 311 | continue 312 | if node.arfile not in af: 313 | af.append(node.arfile) 314 | return af 315 | 316 | @property 317 | def used_files(self): 318 | af = [] 319 | of = [] 320 | for node in self.root.all_nodes(): 321 | region = node.region 322 | if node.arfile is None and node.leafsize \ 323 | and region not in ['DISCARDED', 'UNDEF']: 324 | if node.objfile is None and node.leafsize \ 325 | and region not in ['DISCARDED', 'UNDEF']: 326 | logging.warning( 327 | "Object unaccounted for : {0:<40} {1:<15} {2:>5}" 328 | "".format(node.gident, region, str(node.leafsize)) 329 | ) 330 | continue 331 | else: 332 | if node.objfile not in of: 333 | of.append(node.objfile) 334 | if node.arfile not in af: 335 | af.append(node.arfile) 336 | if None in af: 337 | af.remove(None) 338 | if None in of: 339 | of.remove(None) 340 | return of, af 341 | 342 | @property 343 | def used_sections(self): 344 | sections = [node.gident for node in self.top_level_nodes 345 | if node.size > 0 and 346 | node.region not in ['DISCARDED', 'UNDEF']] 347 | sections += [node.gident for node in 348 | sum([n.children for n in self.top_level_nodes 349 | if n.region == 'UNDEF'], []) 350 | if node.region != 'DISCARDED' and node.size > 0] 351 | if self.collapse_vectors: 352 | self._vector_sections = [x for x in sections if 'vec' in x] 353 | sections = ['.*vec*'] + [x for x in sections if 'vec' not in x] 354 | return sections 355 | 356 | @property 357 | def all_symbols(self): 358 | asym = [] 359 | for node in self.root.all_nodes(): 360 | if node.name not in asym: 361 | asym.append(node.name) 362 | return asym 363 | 364 | def symbols_from_file(self, lfile): 365 | fsym = [] 366 | for node in self.root.all_nodes(): 367 | if node.name not in fsym and lfile in [node.objfile, node.arfile]: 368 | fsym.append(node.name) 369 | return fsym 370 | 371 | def get_symbol_fp(self, symbol): 372 | r = [] 373 | for rgn in self.used_regions: 374 | r.append(self.get_symbol_fp_rgn(symbol, rgn)) 375 | return r 376 | 377 | def get_symbol_fp_rgn(self, symbol, region): 378 | if self.collapse_vectors and region == "VEC": 379 | return self.get_symbol_fp_rgnvec(symbol) 380 | rv = 0 381 | for node in self.root.all_nodes(): 382 | if node.name == symbol: 383 | if node.region == region: 384 | if node.leafsize is not None: 385 | rv += node.leafsize 386 | return rv 387 | 388 | def get_symbol_fp_rgnvec(self, symbol): 389 | rv = 0 390 | for node in self.root.all_nodes(): 391 | if node.name == symbol: 392 | if 'VEC' in node.region: 393 | if node.leafsize is not None: 394 | rv += node.leafsize 395 | return rv 396 | 397 | def get_objfile_fp(self, objfile): 398 | r = [] 399 | for rgn in self.used_regions: 400 | r.append(self.get_objfile_fp_rgn(objfile, rgn)) 401 | return r 402 | 403 | def get_objfile_fp_rgn(self, objfile, region): 404 | if self.collapse_vectors and region == "VEC": 405 | return self.get_objfile_fp_rgnvec(objfile) 406 | rv = 0 407 | for node in self.root.all_nodes(): 408 | if node.objfile == objfile: 409 | if node.region == region: 410 | if node.leafsize is not None: 411 | rv += node.leafsize 412 | return rv 413 | 414 | def get_objfile_fp_rgnvec(self, objfile): 415 | rv = 0 416 | for node in self.root.all_nodes(): 417 | if node.objfile == objfile: 418 | if 'VEC' in node.region: 419 | if node.leafsize is not None: 420 | rv += node.leafsize 421 | return rv 422 | 423 | def get_objfile_fp_secs(self, objfile): 424 | r = [] 425 | for section in self.used_sections: 426 | r.append(self.get_objfile_fp_sec(objfile, section)) 427 | return r 428 | 429 | def get_arfile_fp_secs(self, arfile): 430 | r = [] 431 | for section in self.used_sections: 432 | r.append(self.get_arfile_fp_sec(arfile, section)) 433 | return r 434 | 435 | def get_objfile_fp_sec(self, objfile, section): 436 | if section == '.*vec*': 437 | return self.get_objfile_fp_secvec(objfile) 438 | rv = 0 439 | for node in self.get_node(section).all_nodes(): 440 | if node.objfile == objfile: 441 | if node.leafsize is not None: 442 | rv += node.leafsize 443 | return rv 444 | 445 | def get_objfile_fp_secvec(self, objfile): 446 | rv = 0 447 | for section in self._vector_sections: 448 | for node in self.get_node(section).all_nodes(): 449 | if node.objfile == objfile: 450 | if node.leafsize is not None: 451 | rv += node.leafsize 452 | return rv 453 | 454 | def get_arfile_fp_sec(self, arfile, section): 455 | if section == '.*vec*': 456 | return self.get_objfile_fp_secvec(arfile) 457 | rv = 0 458 | for node in self.get_node(section).all_nodes(): 459 | if node.arfile == arfile: 460 | if node.leafsize is not None: 461 | rv += node.leafsize 462 | return rv 463 | 464 | def get_arfile_fp_secvec(self, arfile): 465 | rv = 0 466 | for section in self._vector_sections: 467 | for node in self.get_node(section).all_nodes(): 468 | if node.arfile == arfile: 469 | if node.leafsize is not None: 470 | rv += node.leafsize 471 | return rv 472 | 473 | def get_arfile_fp(self, arfile): 474 | r = [] 475 | for rgn in self.used_regions: 476 | r.append(self.get_arfile_fp_rgn(arfile, rgn)) 477 | return r 478 | 479 | def get_arfile_fp_rgn(self, arfile, region): 480 | if self.collapse_vectors and region == "VEC": 481 | return self.get_arfile_fp_rgnvec(arfile) 482 | rv = 0 483 | for node in self.root.all_nodes(): 484 | if node.arfile == arfile: 485 | if node.region == region: 486 | if node.leafsize is not None: 487 | rv += node.leafsize 488 | return rv 489 | 490 | def get_arfile_fp_rgnvec(self, arfile): 491 | rv = 0 492 | for node in self.root.all_nodes(): 493 | if node.arfile == arfile: 494 | if 'VEC' in node.region: 495 | if node.leafsize is not None: 496 | rv += node.leafsize 497 | return rv 498 | 499 | 500 | class MemoryRegion(object): 501 | def __init__(self, name, origin, size, attribs): 502 | self.name = name 503 | self.origin = int(origin, 16) 504 | self.size = int(size, 16) 505 | self.attribs = attribs 506 | 507 | def __repr__(self): 508 | r = '{0:.<20}{1:>20}{2:>20} {3:<20}' \ 509 | ''.format(self.name, format(self.origin, '#010x'), 510 | self.size or '', self.attribs) 511 | return r 512 | 513 | def __contains__(self, value): 514 | if not isinstance(value, int): 515 | value = int(value, 16) 516 | if self.origin <= value < (self.origin + self.size): 517 | return True 518 | else: 519 | return False 520 | -------------------------------------------------------------------------------- /src/fpvgcc/fpv.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2 | # (c) 2015-16 Chintalagiri Shashank, Quazar Technologies Pvt. Ltd. 3 | # 4 | # This file is part of fpv-gcc. 5 | # 6 | # fpv-gcc is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # fpv-gcc is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with fpv-gcc. If not, see . 18 | 19 | 20 | from __future__ import with_statement 21 | from __future__ import print_function 22 | from six import iteritems 23 | 24 | import re 25 | import logging 26 | 27 | from .gccMemoryMap import GCCMemoryMap, MemoryRegion 28 | from .profiles import get_profile 29 | from .profiles.guess import guess_profile 30 | 31 | 32 | class GCCMemoryMapParserSM(object): 33 | def __init__(self, ctx): 34 | self.ctx = ctx 35 | self.state = 'START' 36 | 37 | self.IDEP_STATE = 'START' 38 | self.idep_archive = None 39 | 40 | self.COMSYM_STATE = 'NORMAL' 41 | self.comsym_name = None 42 | 43 | self.LINKERMAP_STATE = 'NORMAL' 44 | self.linkermap_section = None 45 | self.linkermap_symbol = None 46 | self.linkermap_lastsymbol = None 47 | 48 | self.idep_archives = [] 49 | self.idep_symbols = [] 50 | self.common_symbols = [] 51 | self.memory_regions = [] 52 | 53 | self.loaded_files = [] 54 | self.linker_defined_addresses = [] 55 | self.memory_map = GCCMemoryMap(self.ctx) 56 | 57 | def __repr__(self): 58 | return \ 59 | "30} = {1}\n".format('STATE', self.state) + \ 61 | " {0:>30} = {1}\n".format('IDEP_STATE', self.IDEP_STATE) + \ 62 | " {0:>30} = {1}\n".format('idep_archive', self.idep_archive) + \ 63 | " {0:>30} = {1}\n".format('COMSYM_STATE', self.COMSYM_STATE) + \ 64 | " {0:>28} = {1}\n".format('comsym_name', self.comsym_name) + \ 65 | " {0:>30} = {1}\n" \ 66 | "".format('LINKERMAP_STATE', self.LINKERMAP_STATE) + \ 67 | " {0:>28} = {1}\n" \ 68 | "".format('linkermap_section', self.linkermap_section) + \ 69 | " {0:>28} = {1}\n" \ 70 | "".format('linkermap_symbol', self.linkermap_symbol) + \ 71 | " {0:>28} = {1}\n" \ 72 | "".format('linkermap_lastsymbol', self.linkermap_lastsymbol) 73 | 74 | 75 | # Regular Expressions 76 | re_headings = { 77 | 'IN_DEPENDENCIES': re.compile(r"Archive member [\s\w]* file \(symbol\)"), 78 | 'IN_COMMON_SYMBOLS': re.compile(r"Allocating common symbols"), 79 | 'IN_DISCARDED_INPUT_SECTIONS': re.compile(r"Discarded input sections"), 80 | 'IN_MEMORY_CONFIGURATION': re.compile(r"Memory Configuration"), 81 | 'IN_LINKER_SCRIPT_AND_MEMMAP': re.compile(r"Linker script and memory map")} 82 | 83 | re_b1_archive = re.compile( 84 | r'^(?P.*/)?(?P:|(.+?)(?:(\.[^.]*)))\((?P.*)\)$' 85 | ) 86 | re_b1_file = re.compile( 87 | r'^\s+(?P.*/)?(?P:|(.+?)(?:(\.[^.]*)))\((?P.*)\)$' 88 | ) 89 | re_comsym_normal = re.compile( 90 | r'^(?P\S*)\s+(?P0[xX][0-9a-fA-F]+)\s+(?P.*/)?(?P:|.+?(?:\.[^.]*))\((?P.*)\)$' # noqa 91 | ) 92 | re_comsym_nameonly = re.compile( 93 | r'^(?P\S*)$' 94 | ) 95 | re_comsym_detailonly = re.compile( 96 | r'^\s+(?P0[xX][0-9a-fA-F]+)\s+(?P.*/)?(?P:|.+?(?:\.[^.]*))\((?P.*)\)$' # noqa 97 | ) 98 | 99 | re_sectionelem = re.compile( 100 | r'^(?P\.\S*)\s+(?P
0[xX][0-9a-fA-F]+)\s+(?P0[xX][0-9a-fA-F]+)\s+(?P.*/)?(?P:|.+?(?:\.[^.]*))\((?P.*)\)$' # noqa 101 | ) 102 | re_sectionelem_nameonly = re.compile( 103 | r'^(?P\.\S*)$' 104 | ) 105 | re_sectionelem_detailonly = re.compile( 106 | r'^\s+(?P
0[xX][0-9a-fA-F]+)\s+(?P0[xX][0-9a-fA-F]+)\s+(?P.*/)?(?P:|.+?(?:\.[^.]*))\((?P.*)\)$' # noqa 107 | ) 108 | 109 | re_memregion = re.compile( 110 | r'^(?P\S*)\s+(?P0[xX][0-9a-fA-F]+)\s+(?P0[xX][0-9a-fA-F]+)\s*(?P.*)$' # noqa 111 | ) 112 | 113 | re_linkermap = { 114 | 'LOAD': re.compile( 115 | r'^LOAD\s+(?P.*/)?(?P:|.+?(?:\.[^.]*))$'), 116 | 'DEFN_ADDR': re.compile( 117 | r'^\s+(?P0[xX][0-9a-fA-F]+)\s+(?P.*)\s=\s+(?P0[xX][0-9a-fA-F]+)$'), # noqa 118 | 'SECTION_HEADINGS': re.compile( 119 | r'^(?P[._]\S*)(?:\s+(?P
0[xX][0-9a-fA-F]+))?(?:\s+(?P0[xX][0-9a-fA-F]+))?(?:\s+load address\s+(?P0[xX][0-9a-fA-F]+))?$'), # noqa 120 | 'SYMBOL': re.compile( 121 | r'^\s(?P\S+)(?:\s+(?P
0[xX][0-9a-fA-F]+))(?:\s+(?P0[xX][0-9a-fA-F]+))\s+(?P.*/)?(?P:|.+?(?:\.[^.\)]*))?(?:\((?P\S*)\))?$'), # noqa 122 | 'FILL': re.compile( 123 | r'^\s(?:\*fill\*)(?:\s+(?P
0[xX][0-9a-fA-F]+))(?:\s+(?P0[xX][0-9a-fA-F]+))$'), # noqa 124 | 'SYMBOLONLY': 125 | re.compile(r'^\s(?P[._]\S+)$'), 126 | 'SYMBOLDETAIL': re.compile( 127 | r'^\s+(?:\s+(?P
0[xX][0-9a-fA-F]+))(?:\s+(?P0[xX][0-9a-fA-F]+))\s+(?P.*/)?(?P:|.+?(?:\.[^.\)]*))?(?:\((?P\S*)\))?$'), # noqa 128 | 'SECTIONDETAIL': re.compile( 129 | r'^\s+(?:\s+(?P
0[xX][0-9a-fA-F]+))(?:\s+(?P0[xX][0-9a-fA-F]+))$'), # noqa 130 | 'SECTIONHEADINGONLY': 131 | re.compile(r'^(?P[._]\S+)$'), 132 | 'LINKALIASES': re.compile( 133 | r'^\s\*\(((?:[^\s\*\(\)]+(?:\*|)\s)*(?:[^\s\*\(\)]+(?:\*|)))\)$') # noqa 134 | } 135 | 136 | 137 | def check_line_for_heading(l): 138 | for key, regex in iteritems(re_headings): 139 | if regex.match(l): 140 | logging.info("Entering File Region : " + key) 141 | return key 142 | return None 143 | 144 | 145 | class IDLArchive(object): 146 | # Rough draft. Needs much work to make it usable 147 | def __init__(self, folder, archive, objfile): 148 | self.folder = folder 149 | self.archive = archive 150 | self.objfile = objfile 151 | self.becauseof = None 152 | 153 | def __repr__(self): 154 | r = "\n\nArchive in Dependencies : \n" 155 | r += self.archive + "\n" 156 | r += self.objfile + "\n" 157 | r += self.folder + "\n" 158 | r += repr(self.becauseof) 159 | return r 160 | 161 | 162 | class IDLSymbol(object): 163 | # Rough draft. Needs much work to make it usable 164 | def __init__(self, folder, objfile, symbol): 165 | self.folder = folder 166 | self.objfile = objfile 167 | self.symbol = symbol 168 | 169 | def __repr__(self): 170 | r = "Because of :: \n" 171 | r += self.symbol + "\n" 172 | r += self.objfile + "\n" 173 | r += self.folder + "\n" 174 | return r 175 | 176 | 177 | def process_dependencies_line(l, sm): 178 | # Rough draft. Needs much work to make it usable 179 | if sm.IDEP_STATE == 'START': 180 | res = re_b1_archive.findall(l) 181 | if len(res) and len(res[0]) == 5: 182 | archive = IDLArchive(res[0][1], res[0][1], res[0][4]) 183 | sm.idep_archives.append(archive) 184 | sm.IDEP_STATE = 'ARCHIVE_DEFINED' 185 | sm.idep_archive = archive 186 | if sm.IDEP_STATE == 'ARCHIVE_DEFINED': 187 | res = re_b1_file.findall(l) 188 | if len(res) and len(res[0]) == 5: 189 | symbol = IDLSymbol(res[0][1], res[0][1], res[0][4]) 190 | sm.idep_symbols.append(symbol) 191 | sm.IDEP_STATE = 'START' 192 | sm.idep_archive.becauseof = symbol 193 | 194 | 195 | class CommonSymbol(object): 196 | def __init__(self, symbol, size, filefolder, archivefile, objfile): 197 | self.symbol = symbol 198 | self.size = int(size, 16) 199 | self.filefolder = filefolder 200 | self.archivefile = archivefile 201 | self.objfile = objfile 202 | 203 | def __repr__(self): 204 | r = '{0:.<30}{1:<8}{2:<20}{3:<40}{4}'.format( 205 | self.symbol, self.size or '', self.objfile or '', 206 | self.archivefile or '', self.filefolder or '' 207 | ) 208 | return r 209 | 210 | 211 | def process_common_symbols_line(l, sm): 212 | if sm.COMSYM_STATE == 'NORMAL': 213 | res = re_comsym_normal.findall(l) 214 | if len(res) and len(res[0]) == 5: 215 | sym = CommonSymbol(res[0][0], res[0][1], res[0][2], 216 | res[0][3], res[0][4]) 217 | sm.common_symbols.append(sym) 218 | else: 219 | res = re_comsym_nameonly.findall(l) 220 | if len(res) == 1: 221 | sm.comsym_name = res[0] 222 | sm.COMSYM_STATE = 'GOT_NAME' 223 | elif sm.COMSYM_STATE == 'GOT_NAME': 224 | res = re_comsym_detailonly.findall(l) 225 | if len(res) and len(res[0]) == 4: 226 | sym = CommonSymbol(sm.comsym_name, res[0][0], res[0][1], 227 | res[0][2], res[0][3]) 228 | sm.common_symbols.append(sym) 229 | sm.COMSYM_STATE = 'NORMAL' 230 | 231 | 232 | def process_discarded_input_section_line(l, sm): 233 | pass 234 | 235 | 236 | def process_memory_configuration_line(l, sm): 237 | res = re_memregion.findall(l) 238 | if len(res) and len(res[0]) == 4: 239 | region = MemoryRegion(res[0][0], res[0][1], res[0][2], res[0][3]) 240 | sm.memory_map.memory_regions.append(region) 241 | 242 | 243 | def process_linkermap_load_line(l, sm): 244 | res = re_linkermap['LOAD'].findall(l) 245 | if len(res) and len(res[0]) == 2: 246 | sm.loaded_files.append((res[0][0] + res[0][1]).strip()) 247 | 248 | 249 | class LinkerDefnAddr(object): 250 | def __init__(self, symbol, address, defn_addr): 251 | self.symbol = symbol 252 | self.address = int(address, 16) 253 | self.defn_addr = int(defn_addr, 16) 254 | 255 | def __repr__(self): 256 | r = self.symbol 257 | r += " :: " + hex(self.address) 258 | return r 259 | 260 | 261 | def process_linkermap_defn_addr_line(l, sm): 262 | res = re_linkermap['DEFN_ADDR'].findall(l) 263 | if len(res) and len(res[0]) == 3: 264 | sm.linker_defined_addresses.append( 265 | LinkerDefnAddr(res[0][1], res[0][0], res[0][2]) 266 | ) 267 | 268 | 269 | def linkermap_name_process(name, sm, checksection=True): 270 | name = name.strip() 271 | if name.startswith('_'): 272 | name = '.' + name 273 | if name.startswith('COMMON'): 274 | name = '.' + name 275 | if name.startswith('*fill*'): 276 | return '*fill*' 277 | if not name.startswith('.'): 278 | logging.error('Skipping : {0}'.format(name.rstrip())) 279 | return None 280 | name = sm.memory_map.aliases.encode(name) 281 | if checksection is False: 282 | return name 283 | if not name.startswith(sm.linkermap_section.gident): 284 | if name != sm.linkermap_section.gident: 285 | logging.warning("Possibly mismatched section : {0} ; {1}" 286 | "".format(name, sm.linkermap_section.gident)) 287 | name = sm.linkermap_section.gident + name 288 | return name 289 | 290 | 291 | def linkermap_get_newnode(name, sm, allow_disambig=True, 292 | objfile=None, at_fill=True): 293 | # print("getting new node :", name) 294 | newnode = sm.memory_map.get_node(name, create=True) 295 | if at_fill is True: 296 | if newnode.is_leaf_property_set or newnode._address is not None: 297 | # The node isn't a new one. The present data within it needs to 298 | # be handled first. 299 | 300 | # Push the current node into it's own leaf node. This is enough 301 | # for most cases. 302 | try: 303 | newnode.push_to_leaf() 304 | except TypeError: 305 | print("Error getting new node : {0}".format(name)) 306 | raise 307 | except RuntimeError: 308 | print("Runtime Error getting new node : {0}".format(name)) 309 | exit(0) 310 | 311 | if not objfile: 312 | print("Possibly duplicate node with a conflicting name and no objfile for disambiguation:", name) 313 | print("Footprint measurement is probably inaccurate!") 314 | return newnode 315 | 316 | # Now generate the new node as a child of the original target. 317 | # In some cases this needs the node disambiguation element 318 | # included. 319 | newnodename = objfile.replace('.', '_') 320 | newnodepath = "{0}.{1}".format(name, newnodename) 321 | 322 | # Check if disambiguation is already initialized or is recommended 323 | disambig = sm.memory_map.get_node_disambig(newnodepath, 324 | prospective=True) 325 | 326 | # Accordingly modify name as needed 327 | if disambig is not None: 328 | newnodepath = "{0}:{1}".format(newnodepath, disambig + 1) 329 | 330 | # Get the new child node for what was originally requested 331 | newnode = linkermap_get_newnode( 332 | newnodepath, sm, allow_disambig=False, 333 | objfile=objfile, at_fill=True 334 | ) 335 | return newnode 336 | 337 | 338 | def process_linkermap_section_headings_line(l, sm): 339 | match = re_linkermap['SECTION_HEADINGS'].match(l) 340 | name = match.group('name').strip() 341 | name = linkermap_name_process(name, sm, False) 342 | if name is None: 343 | return 344 | if name == '*fill*': 345 | print("IN SH") 346 | newnode = linkermap_get_newnode(name, sm, True) 347 | if match.group('address') is not None: 348 | newnode.address = match.group('address').strip() 349 | if match.group('size') is not None: 350 | newnode.defsize = match.group('size').strip() 351 | if len(newnode.children) > 0: 352 | newnode = newnode.push_to_leaf() 353 | if match.group('address') is not None: 354 | sm.linkermap_section = newnode 355 | sm.LINKERMAP_STATE = 'IN_SECTION' 356 | else: 357 | sm.linkermap_section = newnode 358 | sm.LINKERMAP_STATE = 'GOT_SECTION_NAME' 359 | 360 | 361 | def process_linkermap_section_heading_detail_line(l, sm): 362 | match = re_linkermap['SECTIONDETAIL'].match(l) 363 | newnode = sm.linkermap_section 364 | if match: 365 | if match.group('address') is not None: 366 | newnode.address = match.group('address').strip() 367 | if match.group('size') is not None: 368 | newnode.defsize = match.group('size').strip() 369 | if len(newnode.children) > 0: 370 | newnode.push_to_leaf() 371 | sm.LINKERMAP_STATE = 'IN_SECTION' 372 | 373 | 374 | def process_linkermap_symbol_line(l, sm): 375 | if sm.linkermap_symbol is not None: 376 | logging.warning("Probably Missed Symbol Detail : " + 377 | sm.linkermap_symbol) 378 | sm.linkermap_symbol = None 379 | match = re_linkermap['SYMBOL'].match(l) 380 | name = match.group('name').strip() 381 | name = linkermap_name_process(name, sm) 382 | if name is None: 383 | return 384 | if name == '*fill*': 385 | sm.linkermap_lastsymbol.fillsize = match.group('size').strip() 386 | return 387 | arfile = None 388 | objfile = None 389 | arfolder = None 390 | if match.group('file2') is not None: 391 | arfile = match.group('file').strip() 392 | objfile = match.group('file2').strip() 393 | if match.group('filefolder') is not None: 394 | arfolder = match.group('filefolder').strip() 395 | elif match.group('file') is not None: 396 | objfile = match.group('file').strip() 397 | if match.group('filefolder') is not None: 398 | arfolder = match.group('filefolder').strip() 399 | newnode = linkermap_get_newnode(name, sm, allow_disambig=True, 400 | objfile=objfile) 401 | if arfile is not None: 402 | newnode.arfile = arfile 403 | if objfile is not None: 404 | newnode.objfile = objfile 405 | if arfolder is not None: 406 | newnode.arfolder = arfolder 407 | if match.group('address') is not None: 408 | newnode.address = match.group('address').strip() 409 | if match.group('size') is not None: 410 | newnode.osize = match.group('size').strip() 411 | if len(newnode.children) > 0: 412 | newnode = newnode.push_to_leaf() 413 | sm.linkermap_lastsymbol = newnode 414 | 415 | 416 | def process_linkermap_fill_line(l, sm): 417 | if sm.linkermap_symbol is not None: 418 | logging.warning("Probably Missed Symbol Detail : " 419 | + sm.linkermap_symbol) 420 | sm.linkermap_symbol = None 421 | 422 | if sm.linkermap_lastsymbol is None or sm.linkermap_symbol is not None: 423 | logging.warning("Fill Container Unknown : " + l) 424 | return 425 | 426 | match = re_linkermap['FILL'].match(l) 427 | if match.group('size') is not None: 428 | sm.linkermap_lastsymbol.fillsize = int(match.group('size').strip(), 16) 429 | 430 | 431 | def process_linkermap_symbolonly_line(l, sm): 432 | if sm.linkermap_symbol is not None: 433 | logging.warning("Probably Missed Symbol Detail : " 434 | + sm.linkermap_symbol) 435 | sm.linkermap_symbol = None 436 | match = re_linkermap['SYMBOLONLY'].match(l) 437 | name = match.group('name').strip() 438 | name = linkermap_name_process(name, sm) 439 | if name is None: 440 | return 441 | if name == '*fill*': 442 | print("IN SO") 443 | sm.linkermap_symbol = name 444 | 445 | 446 | def process_linkermap_section_detail_line(l, sm): 447 | match = re_linkermap['SYMBOLDETAIL'].match(l) 448 | name = sm.linkermap_symbol 449 | if name is None: 450 | return 451 | arfile = None 452 | objfile = None 453 | arfolder = None 454 | if match.group('file2') is not None: 455 | arfile = match.group('file').strip() 456 | objfile = match.group('file2').strip() 457 | if match.group('filefolder') is not None: 458 | arfolder = match.group('filefolder').strip() 459 | elif match.group('file') is not None: 460 | objfile = match.group('file').strip() 461 | if match.group('filefolder') is not None: 462 | arfolder = match.group('filefolder').strip() 463 | newnode = linkermap_get_newnode(name, sm, 464 | allow_disambig=True, objfile=objfile) 465 | if arfile is not None: 466 | newnode.arfile = arfile 467 | if objfile is not None: 468 | newnode.objfile = objfile 469 | if arfolder is not None: 470 | newnode.arfolder = arfolder 471 | if match.group('address') is not None: 472 | newnode.address = match.group('address').strip() 473 | if match.group('size') is not None: 474 | newnode.osize = match.group('size').strip() 475 | if len(newnode.children) > 0: 476 | newnode = newnode.push_to_leaf() 477 | sm.linkermap_lastsymbol = newnode 478 | sm.linkermap_symbol = None 479 | 480 | 481 | def process_linkaliases_line(l, sm): 482 | match = re_linkermap['LINKALIASES'].match(l) 483 | alias_list = match.group(1).split(' ') 484 | # print alias_list, linkermap_section.gident 485 | for alias in alias_list: 486 | if alias.endswith('*'): 487 | alias = alias[:-1] 488 | if alias.endswith('.'): 489 | alias = alias[:-1] 490 | if sm.linkermap_section is not None and \ 491 | alias == sm.linkermap_section.gident: 492 | continue 493 | # print alias, linkermap_section.gident 494 | if sm.linkermap_section is not None: 495 | sm.memory_map.aliases.register_alias( 496 | sm.linkermap_section.gident, alias 497 | ) 498 | else: 499 | logging.warning("Target for alias unknown : " + alias) 500 | 501 | 502 | def process_linkermap_line(l, sm): 503 | if sm.LINKERMAP_STATE == 'GOT_SECTION_NAME': 504 | process_linkermap_section_heading_detail_line(l, sm) 505 | elif sm.LINKERMAP_STATE == 'NORMAL': 506 | for key, regex in iteritems(re_linkermap): 507 | if regex.match(l): 508 | if key == 'LOAD': 509 | process_linkermap_load_line(l, sm) 510 | return 511 | if key == 'DEFN_ADDR': 512 | process_linkermap_defn_addr_line(l, sm) 513 | return 514 | if key == 'SECTION_HEADINGS': 515 | process_linkermap_section_headings_line(l, sm) 516 | return 517 | logging.error( 518 | "Unhandled line in linkerm : {0}".format(l.strip())) 519 | elif sm.LINKERMAP_STATE == 'IN_SECTION': 520 | if sm.linkermap_symbol is not None: 521 | if re_linkermap['SYMBOLDETAIL'].match(l): 522 | process_linkermap_section_detail_line(l, sm) 523 | return 524 | if re_linkermap['SECTION_HEADINGS'].match(l): 525 | process_linkermap_section_headings_line(l, sm) 526 | return 527 | if re_linkermap['FILL'].match(l): 528 | process_linkermap_fill_line(l, sm) 529 | return 530 | if re_linkermap['LINKALIASES'].match(l): 531 | process_linkaliases_line(l, sm) 532 | return 533 | if re_linkermap['SYMBOL'].match(l): 534 | process_linkermap_symbol_line(l, sm) 535 | return 536 | if re_linkermap['SYMBOLONLY'].match(l): 537 | process_linkermap_symbolonly_line(l, sm) 538 | return 539 | logging.warning("Unhandled line in section : {0}".format(l.strip())) 540 | return None 541 | 542 | 543 | def cleanup_and_pack_map(sm): 544 | for node in sm.memory_map.root.all_nodes(): 545 | if len(node.children) > 0: 546 | logging.warning('Force clearing leaf size for intermediate node' 547 | ' : {0}'.format(node.gident)) 548 | node.osize = '0x0' 549 | node.fillsize = 0 550 | 551 | 552 | def process_map_file(fname, profile=None): 553 | if profile is None: 554 | profile = get_profile('default') 555 | elif profile == 'auto': 556 | profile = guess_profile(fname) 557 | sm = GCCMemoryMapParserSM(ctx=profile) 558 | with open(fname) as f: 559 | for line in f: 560 | if not line.strip(): 561 | continue 562 | rval = check_line_for_heading(line) 563 | if rval is not None: 564 | sm.state = rval 565 | else: 566 | if sm.state == 'IN_DEPENDENCIES': 567 | process_dependencies_line(line, sm) 568 | elif sm.state == 'IN_COMMON_SYMBOLS': 569 | process_common_symbols_line(line, sm) 570 | elif sm.state == 'IN_DISCARDED_INPUT_SECTIONS': 571 | process_discarded_input_section_line(line, sm) 572 | elif sm.state == 'IN_MEMORY_CONFIGURATION': 573 | process_memory_configuration_line(line, sm) 574 | elif sm.state == 'IN_LINKER_SCRIPT_AND_MEMMAP': 575 | process_linkermap_line(line, sm) 576 | cleanup_and_pack_map(sm) 577 | return sm 578 | 579 | 580 | if __name__ == '__main__': 581 | from .cli import main 582 | main() 583 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | --------------------------------------------------------------------------------