From 35542f56cba246582e11700454176efc889f079a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mario=20H=C3=BCttel?= Date: Tue, 9 Aug 2022 00:21:57 +0200 Subject: [PATCH] Add pylintrc and fix style problems in crc patcher --- stm-firmware/crc-patcher/crc-patch-elf.py | 128 +++-- stm-firmware/crc-patcher/pylintrc | 623 ++++++++++++++++++++++ 2 files changed, 692 insertions(+), 59 deletions(-) create mode 100644 stm-firmware/crc-patcher/pylintrc diff --git a/stm-firmware/crc-patcher/crc-patch-elf.py b/stm-firmware/crc-patcher/crc-patch-elf.py index 64e3439..69f9784 100755 --- a/stm-firmware/crc-patcher/crc-patch-elf.py +++ b/stm-firmware/crc-patcher/crc-patch-elf.py @@ -9,8 +9,9 @@ For this, it searches the follwoing sections: 3) .ccmdata 4) .vectors -All sections MUST be a multiple of 4 bytes long because the CRC calculation relies on whole 32 bit words. -The sections are excrated and the CRC is calculated for each section. +All sections MUST be a multiple of 4 bytes long +because the CRC calculation relies on whole 32 bit words. +The sections are extracted and the CRC is calculated for each section. In the section .flashcrc, the script expects a single struct with the prototype: struct flash_crcs { @@ -22,16 +23,16 @@ struct flash_crcs { uint32_t end_magic; }; -It checks, if the start magic and end magic are set to the appropriate values and then patches in the CRC values of the sections. +It checks, if the start magic and end magic are set to the appropriate values and then +patches in the CRC values of the sections. The magic values checked for are: 0xA8BE53F9 and 0xFFA582FF """ -from elftools.elf.elffile import ELFFile -from elftools.elf.segments import Segment -import elftools.elf.constants as elf_const + import sys +import struct +from elftools.elf.elffile import ELFFile import crcmod import crcmod.predefined -import struct crc_calc = crcmod.predefined.mkCrcFun('crc-32-mpeg') @@ -42,6 +43,9 @@ if len(sys.argv) < 2: filename=sys.argv[1] def section_calculate_crc(section): + """ + Calculate CRC of ELF file section + """ data = bytearray(section.data()) be_data = bytearray([0 for k in range(0, len(data))]) # Rearrange data, because the STM controller sees it as 32 bit little endian words @@ -53,62 +57,68 @@ def section_calculate_crc(section): return crc_calc(be_data) -with open(filename, 'r+b') as f: - elf = ELFFile(f) - sections = {} - sections['.text'] = elf.get_section_by_name('.text') - sections['.data'] = elf.get_section_by_name('.data') - sections['.ccmdata'] = elf.get_section_by_name('.ccmdata') - sections['.vectors'] = elf.get_section_by_name('.vectors') +def main(): + """ + Main function. Patches CRCs into ELF file + """ + with open(filename, 'r+b') as elf_file: + elf = ELFFile(elf_file) + sections = {} + sections['.text'] = elf.get_section_by_name('.text') + sections['.data'] = elf.get_section_by_name('.data') + sections['.ccmdata'] = elf.get_section_by_name('.ccmdata') + sections['.vectors'] = elf.get_section_by_name('.vectors') - for key, sec in sections.items(): - if sec is None: - print("Error! Section", key, "not found in ELF file!") + for key, sec in sections.items(): + if sec is None: + print("Error! Section", key, "not found in ELF file!") + sys.exit(-1) + print('Found section', key, 'Size:', + sec.data_size, 'Type:', sec['sh_type']) + if sec['sh_type'] != 'SHT_PROGBITS': + print('Error! Section must be of type SHT_PROGBITS') + sys.exit(-1) + if sec.data_size % 4 != 0: + print("Section", key, + "has wrong size. Must be a multiple of 4 bytes!") + sys.exit(-1) + + text_crc = section_calculate_crc(sections['.text']) + print('CRC of .text section:', hex(text_crc)) + data_crc = section_calculate_crc(sections['.data']) + print('CRC of .data section:', hex(data_crc)) + ccmdata_crc = section_calculate_crc(sections['.ccmdata']) + print('CRC of .ccmdata section:', hex(ccmdata_crc)) + vextors_crc = section_calculate_crc(sections['.vectors']) + print('CRC of .vectors section:', hex(vextors_crc)) + + # Check the flashcrc section + flashcrc_sec = elf.get_section_by_name('.flashcrc') + if flashcrc_sec is None: + print('Section for flash CRC missing!') sys.exit(-1) - print('Found section', key, 'Size:', - sec.data_size, 'Type:', sec['sh_type']) - if sec['sh_type'] != 'SHT_PROGBITS': - print('Error! Section must be of type SHT_PROGBITS') - sys.exit(-1) - if (sec.data_size % 4 != 0): - print("Section", key, "has wrong size. Must be a multiple of 4 bytes!") + if flashcrc_sec.data_size != 6*4: + print("Error: .flashcrc section has wrong size:",flashcrc_sec.data_size) sys.exit(-1) - text_crc = section_calculate_crc(sections['.text']) - print('CRC of .text section:', hex(text_crc)) - data_crc = section_calculate_crc(sections['.data']) - print('CRC of .data section:', hex(data_crc)) - ccmdata_crc = section_calculate_crc(sections['.ccmdata']) - print('CRC of .ccmdata section:', hex(ccmdata_crc)) - vextors_crc = section_calculate_crc(sections['.vectors']) - print('CRC of .vectors section:', hex(vextors_crc)) + crc_sec_data = bytearray(flashcrc_sec.data()) + magic1 = struct.unpack('?$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string='\t' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + +# Regular expression of note tags to take in consideration. +#notes-rgx= + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it work, +# install the 'python-enchant' package. +spelling-dict= + +# List of comma separated words that should be considered directives if they +# appear and the beginning of a comment and should not be checked. +spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of names allowed to shadow builtins +allowed-redefined-builtins= + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io + + +[LOGGING] + +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis). It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[CLASSES] + +# Warn about protected attribute access inside special methods +check-protected-access-in-special-methods=no + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=cls + + +[DESIGN] + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules= + +# Output a graph (.gv or any supported image format) of external dependencies +# to the given file (report RP0402 must not be disabled). +ext-import-graph= + +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be +# disabled). +import-graph= + +# Output a graph (.gv or any supported image format) of internal dependencies +# to the given file (report RP0402 must not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "BaseException, Exception". +overgeneral-exceptions=BaseException, + Exception