def __test_variable_width(self): """ Test variable width. """ if self.verbose: print("Running __test_variable_width()...") models = CrcModels() m = models.getParams("crc-64-jones") for width in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 23, 24, 25, 31, 32, 33, 63, 64]: mask = (1 << width) - 1 mw = { 'width': width, 'poly': m['poly'] & mask, 'reflect_in': m['reflect_in'], 'xor_in': m['xor_in'] & mask, 'reflect_out': m['reflect_out'], 'xor_out': m['xor_out'] & mask, } args = "--width %(width)s --poly 0x%(poly)x --xor-in 0x%(xor_in)x --reflect-in %(reflect_in)s --xor-out 0x%(xor_out)x --reflect-out %(reflect_out)s" % mw check = self.__get_crc(mw) if check is None: return False if self.use_algo_bit_by_bit: if self.crc_bin_bbb_c99 is not None: if not self.__check_command(self.crc_bin_bbb_c99 + " " + args, check): return False if not self.__compile_and_check_res("--algorithm bit-by-bit" + " " + args, None, "crc_bbb_arg", check): return False if self.use_algo_bit_by_bit_fast: if self.crc_bin_bbf_c99 is not None: if not self.__check_command(self.crc_bin_bbf_c99 + " " + args, check): return False if not self.__compile_and_check_res("--algorithm bit-by-bit-fast" + " " + args, None, "crc_bbf_arg", check): return False if self.use_algo_bitwise_expression: if self.crc_bin_bwe_c99 is not None: if not self.__check_command(self.crc_bin_bwe_c99 + " " + args, check): return False if not self.__compile_and_check_res("--algorithm bitwise-expression" + " " + args, None, "crc_bwe_arg", check): return False if self.use_algo_table_driven: if self.crc_bin_tbl_c99 is not None: if not self.__check_command(self.crc_bin_tbl_c99 + " " + args, check): return False if not self.__compile_and_check_res("--algorithm table-driven" + " " + args, None, "crc_tbl_arg", check): return False return True
def parse(self, argv = None): """ Parses and validates the options given as arguments """ usage = """\ %prog [OPTIONS]""" models = CrcModels() model_list = ", ".join(models.getList()) algorithms = ", ".join(sorted(list(self.AllAlgorithms)) + ["all"]) parser = OptionParser(usage=usage) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=self.Verbose, help="print information about the model") parser.add_option("-3", "--python3", action="store_true", dest="python3", default=self.Python3, help="use Python3.x") parser.add_option("-c", "--compile", action="store_true", dest="compile", default=self.Compile, help="test compiled version") parser.add_option("-r", "--random-parameters", action="store_true", dest="random_parameters", default=self.RandomParameters, help="test random parameters") parser.add_option("-m", "--compile-mixed-arguments", action="store_true", dest="compile_mixed_args", default=self.CompileMixedArgs, help="test compiled C program with some arguments given at compile time some arguments given at runtime") parser.add_option("-w", "--variable-width", action="store_true", dest="variable_width", default=self.VariableWidth, help="test variable width from 1 to 64") parser.add_option("-a", "--all", action="store_true", dest="all", default=False, help="do all tests") parser.add_option("--algorithm", action="store", type="string", dest="algorithm", default="all", help="choose an algorithm from {%s}" % algorithms, metavar="ALGO") (options, args) = parser.parse_args(argv) self.Verbose = options.verbose self.Python3 = options.python3 self.Compile = options.all or options.compile or options.random_parameters self.RandomParameters = options.all or options.random_parameters self.CompileMixedArgs = options.all or options.compile_mixed_args self.VariableWidth = options.all or options.variable_width if options.algorithm != None: alg = options.algorithm.lower() if alg in self.AllAlgorithms: self.Algorithm = set([alg]) elif alg == "all": self.Algorithm = copy(self.AllAlgorithms) else: sys.stderr.write("unknown algorithm: %s\n" % alg) sys.exit(1)
def __test_variable_width(self): """ Test variable width. """ if self.verbose: print('Running __test_variable_width()...') models = CrcModels() m = models.get_params('crc-64-jones') for width in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 23, 24, 25, 31, 32, 33, 63, 64]: mask = (1 << width) - 1 mw = { 'width': width, 'poly': m['poly'] & mask, 'reflect_in': m['reflect_in'], 'xor_in': m['xor_in'] & mask, 'reflect_out': m['reflect_out'], 'xor_out': m['xor_out'] & mask, } args = '--width {width:d} --poly {poly:#x} --xor-in {xor_in:#x} --reflect-in {reflect_in} --xor-out {xor_out:#x} --reflect-out {reflect_out}'.format(**mw) check = self.__get_crc(mw) if check is None: return False if self.use_algo_bit_by_bit: if self.crc_bin_bbb_c99 is not None: if not self.__check_command(self.crc_bin_bbb_c99 + ' ' + args, check): return False if not self.__compile_and_check_res('--algorithm bit-by-bit' + ' ' + args, None, 'crc_bbb_arg', check): return False if self.use_algo_bit_by_bit_fast: if self.crc_bin_bbf_c99 is not None: if not self.__check_command(self.crc_bin_bbf_c99 + ' ' + args, check): return False if not self.__compile_and_check_res('--algorithm bit-by-bit-fast' + ' ' + args, None, 'crc_bbf_arg', check): return False if self.use_algo_table_driven: if self.crc_bin_tbl_c99 is not None: if not self.__check_command(self.crc_bin_tbl_c99 + ' ' + args, check): return False if not self.__compile_and_check_res('--algorithm table-driven' + ' ' + args, None, 'crc_tbl_arg', check): return False return True
def model_cb(self, option, opt_str, value, parser): """ This function sets up the single parameters if the 'model' option has been selected by the user. """ model_name = value.lower() models = CrcModels() model = models.getParams(model_name) if model != None: setattr(parser.values, 'width', model['width']) setattr(parser.values, 'poly', model['poly']) setattr(parser.values, 'reflect_in', model['reflect_in']) setattr(parser.values, 'xor_in', model['xor_in']) setattr(parser.values, 'reflect_out', model['reflect_out']) setattr(parser.values, 'xor_out', model['xor_out']) else: raise OptionValueError("Error: unsupported model %s" % (value))
def model_cb(self, option, opt_str, value, parser): """ This function sets up the single parameters if the 'model' option has been selected by the user. """ model_name = value.lower() models = CrcModels() model = models.getParams(model_name) if model != None: setattr(parser.values, "width", model["width"]) setattr(parser.values, "poly", model["poly"]) setattr(parser.values, "reflect_in", model["reflect_in"]) setattr(parser.values, "xor_in", model["xor_in"]) setattr(parser.values, "reflect_out", model["reflect_out"]) setattr(parser.values, "xor_out", model["xor_out"]) else: models = CrcModels() model_list = ", ".join(models.getList()) raise OptionValueError("unsupported model %s. Supported models are: %s." % (value, model_list))
def __test_compiled_models(self): """ Standard Tests. Test all known models with the compiled code """ if self.verbose: print("Running __test_compiled_models()...") check_str = "123456789" models = CrcModels() for m in models.models: expected_crc = m["check"] cmp_opt = "--model %(name)s" % m if self.use_algo_bit_by_bit: filename = self.__make_bin( "--algorithm bit-by-bit" + " " + cmp_opt, "crc_bbb_mod") if filename == None: return False ret = self.__check_command(filename, expected_crc) self.__del_files([filename, filename + ".h", filename + ".c"]) if not ret: return False if self.use_algo_bit_by_bit_fast: filename = self.__make_bin( "--algorithm bit-by-bit-fast" + " " + cmp_opt, "crc_bbf_mod") if filename == None: return False ret = self.__check_command(filename, expected_crc) self.__del_files([filename, filename + ".h", filename + ".c"]) if not ret: return False if self.use_algo_bitwise_expression: filename = self.__make_bin( "--algorithm bitwise-expression" + " " + cmp_opt, "crc_bwe_mod") if filename == None: return False ret = self.__check_command(filename, expected_crc) self.__del_files([filename, filename + ".h", filename + ".c"]) if not ret: return False if self.use_algo_table_driven: filename = self.__make_bin( "--algorithm table-driven" + " " + cmp_opt, "crc_tbl_mod") if filename == None: return False ret = self.__check_command(filename, expected_crc) self.__del_files([filename, filename + ".h", filename + ".c"]) if not ret: return False return True
def __test_compiled_models(self): """ Standard Tests. Test all known models with the compiled code """ if self.verbose: print('Running __test_compiled_models()...') models = CrcModels() for m in models.models: expected_crc = m['check'] cmp_opt = '--model {name}'.format(**m) if self.use_algo_bit_by_bit: if not self.__compile_and_check_res( '--algorithm bit-by-bit' + ' ' + cmp_opt, None, 'crc_bbb_mod', expected_crc): return False if self.use_algo_bit_by_bit_fast: if not self.__compile_and_check_res( '--algorithm bit-by-bit-fast' + ' ' + cmp_opt, None, 'crc_bbf_mod', expected_crc): return False if self.use_algo_table_driven: if not self.__compile_and_check_res( '--algorithm table-driven' + ' ' + cmp_opt, None, 'crc_tbl_mod', expected_crc): return False if not self.__compile_and_check_res( '--algorithm table-driven --slice-by=4' + ' ' + cmp_opt, None, 'crc_tsb4_mod', expected_crc): return False if not self.__compile_and_check_res( '--algorithm table-driven --slice-by=8' + ' ' + cmp_opt, None, 'crc_tsb8_mod', expected_crc): return False if not self.__compile_and_check_res( '--algorithm table-driven --slice-by=16' + ' ' + cmp_opt, None, 'crc_tsb16_mod', expected_crc): return False if not self.__compile_and_check_res( '--algorithm table-driven --table-idx-width=2' + ' ' + cmp_opt, None, 'crc_tix2_mod', expected_crc): return False if not self.__compile_and_check_res( '--algorithm table-driven --table-idx-width=4' + ' ' + cmp_opt, None, 'crc_tix4_mod', expected_crc): return False return True
def _model_cb(option, opt_str, value, parser): """ This function sets up the single parameters if the 'model' option has been selected by the user. """ model_name = value.lower() models = CrcModels() model = models.get_params(model_name) if model != None: setattr(parser.values, 'width', model['width']) setattr(parser.values, 'poly', model['poly']) setattr(parser.values, 'reflect_in', model['reflect_in']) setattr(parser.values, 'xor_in', model['xor_in']) setattr(parser.values, 'reflect_out', model['reflect_out']) setattr(parser.values, 'xor_out', model['xor_out']) else: models = CrcModels() model_list = ", ".join(models.get_list()) raise OptionValueError( "unsupported model {0:s}. Supported models are: {1:s}." .format(value, model_list))
def __test_compiled_models(self): """ Standard Tests. Test all known models with the compiled code """ if self.verbose: print("Running __test_compiled_models()...") check_str = "123456789" models = CrcModels() for m in models.models: expected_crc = m["check"] cmp_opt = "--model %(name)s" % m if self.use_algo_bit_by_bit: if not self.__compile_and_check_res( "--algorithm bit-by-bit" + " " + cmp_opt, None, "crc_bbb_mod", expected_crc): return False if self.use_algo_bit_by_bit_fast: if not self.__compile_and_check_res( "--algorithm bit-by-bit-fast" + " " + cmp_opt, None, "crc_bbf_mod", expected_crc): return False if self.use_algo_bitwise_expression: if not self.__compile_and_check_res( "--algorithm bitwise-expression" + " " + cmp_opt, None, "crc_bwe_mod", expected_crc): return False if self.use_algo_table_driven: if not self.__compile_and_check_res( "--algorithm table-driven" + " " + cmp_opt, None, "crc_tbl_mod", expected_crc): return False if not self.__compile_and_check_res( "--algorithm table-driven --table-idx-width=2" + " " + cmp_opt, None, "crc_tb2_mod", expected_crc): return False if not self.__compile_and_check_res( "--algorithm table-driven --table-idx-width=4" + " " + cmp_opt, None, "crc_tb4_mod", expected_crc): return False return True
def __test_models(self): """ Standard Tests. Test all known models. """ if self.verbose: print('Running __test_models()...') check_str = '123456789' check_bytes = bytearray(check_str, 'utf-8') models = CrcModels() for m in models.models: expected_crc = m['check'] if self.__get_crc(m, check_str, expected_crc) != expected_crc: return False ext_args = '--width {width:d} --poly {poly:#x} --xor-in {xor_in:#x} --reflect-in {reflect_in} --xor-out {xor_out:#x} --reflect-out {reflect_out}'.format( **m) cmd_str = '{0:s} --model {1:s}'.format(self.pycrc_bin, m['name']) if not self.__check_command(cmd_str, expected_crc): return False cmd_str = '{0:s} {1:s}'.format(self.pycrc_bin, ext_args) if not self.__check_command(cmd_str, expected_crc): return False cmd_str = '{0:s} {1:s} --check-hexstring {2:s}'.format( self.pycrc_bin, ext_args, ''.join(['{0:02x}'.format(c) for c in check_bytes])) if not self.__check_command(cmd_str, expected_crc): return False cmd_str = '{0:s} --model {1:s} --check-file {2:s}'.format( self.pycrc_bin, m['name'], self.check_file) if not self.__check_command(cmd_str, expected_crc): return False if not self.__check_bin(ext_args, expected_crc, m['width'] > 32): return False if self.verbose: print("") return True
def __test_models(self): """ Standard Tests. Test all known models. """ if self.verbose: print("Running __test_models()...") check_str = "123456789" models = CrcModels() for m in models.models: expected_crc = m["check"] if self.__get_crc(m, check_str, expected_crc) != expected_crc: return False ext_args = "--width %(width)s --poly 0x%(poly)x --xor-in 0x%(xor_in)x --reflect-in %(reflect_in)s --xor-out 0x%(xor_out)x --reflect-out %(reflect_out)s" % m cmd_str = self.pycrc_bin + " --model %(name)s" % m if not self.__check_command(cmd_str, expected_crc): return False cmd_str = self.pycrc_bin + " " + ext_args if not self.__check_command(cmd_str, expected_crc): return False cmd_str = self.pycrc_bin + " %s --check-hexstring %s" % ( ext_args, "".join(["%02x" % ord(c) for c in check_str])) if not self.__check_command(cmd_str, expected_crc): return False cmd_str = self.pycrc_bin + " --model %s --check-file %s" % ( m["name"], self.check_file) if not self.__check_command(cmd_str, expected_crc): return False if not self.__check_bin(ext_args, expected_crc): return False if self.verbose: print("") return True
def _model_cb(option, opt_str, value, parser): """ This function sets up the single parameters if the 'model' option has been selected by the user. """ model_name = value.lower() models = CrcModels() model = models.get_params(model_name) if model != None: setattr(parser.values, 'width', model['width']) setattr(parser.values, 'poly', model['poly']) setattr(parser.values, 'reflect_in', model['reflect_in']) setattr(parser.values, 'xor_in', model['xor_in']) setattr(parser.values, 'reflect_out', model['reflect_out']) setattr(parser.values, 'xor_out', model['xor_out']) else: models = CrcModels() model_list = ", ".join(models.names()) raise OptionValueError( "unsupported model {0:s}. Supported models are: {1:s}." .format(value, model_list))
def parse(self, argv=None): """ Parses and validates the options given as arguments """ usage = """\ python %prog [OPTIONS] To calculate the checksum of a string or hexadecimal data: python %prog [model] --check-string "123456789" python %prog [model] --check-hexstring "313233343536373839" To calculate the checksum of a file: python %prog [model] --check-file filename To generate the C source code and write it to filename: python %prog [model] --generate c -o filename The model can be defined either with the --model switch or by specifying each of the following parameters: --width --poly --reflect-in --xor-in --reflect-out --xor-out""" models = CrcModels() model_list = ", ".join(models.getList()) parser = OptionParser(option_class=MyOption, usage=usage, version=self.VersionStr) parser.add_option( "-v", "--verbose", action="store_true", dest="verbose", default=False, help= "be more verbose; print the value of the parameters and the chosen model to stdout" ) parser.add_option( "--check-string", action="store", type="string", dest="check_string", help="calculate the checksum of a string (default: '123456789')", metavar="STRING") parser.add_option( "--check-hexstring", action="store", type="string", dest="check_hexstring", help="calculate the checksum of a hexadecimal number string", metavar="STRING") parser.add_option("--check-file", action="store", type="string", dest="check_file", help="calculate the checksum of a file", metavar="FILE") parser.add_option( "--generate", action="store", type="string", dest="generate", default=None, help= "generate C source code; choose the type from {h, c, c-main, table}", metavar="CODE") parser.add_option( "--std", action="store", type="string", dest="c_std", default="C99", help= "choose the C dialect of the generated code from {C89, ANSI, C99}", metavar="STD") parser.add_option( "--algorithm", action="store", type="string", dest="algorithm", default="all", help= "choose an algorithm from {bit-by-bit, bbb, bit-by-bit-fast, bbf, bitwise-expression, bwe, table-driven, tbl, all}", metavar="ALGO") parser.add_option("--model", action="callback", callback=self.model_cb, type="string", dest="model", default=None, help="choose a parameter set from {%s}" % model_list, metavar="MODEL") parser.add_option("--width", action="store", type="hex", dest="width", help="use NUM bits in the polynomial", metavar="NUM") parser.add_option("--poly", action="store", type="hex", dest="poly", help="use HEX as polynomial", metavar="HEX") parser.add_option("--reflect-in", action="store", type="bool", dest="reflect_in", help="reflect the octets in the input message", metavar="BOOL") parser.add_option("--xor-in", action="store", type="hex", dest="xor_in", help="use HEX as initial value", metavar="HEX") parser.add_option( "--reflect-out", action="store", type="bool", dest="reflect_out", help= "reflect the resulting checksum before applying the --xor-out value", metavar="BOOL") parser.add_option("--xor-out", action="store", type="hex", dest="xor_out", help="xor the final CRC value with HEX", metavar="HEX") parser.add_option( "--table-idx-width", action="store", type="int", dest="table_idx_width", help= "use NUM bits to index the CRC table; NUM must be one of the values {1, 2, 4, 8}", metavar="NUM") parser.add_option( "--symbol-prefix", action="store", type="string", dest="symbol_prefix", help= "when generating source code, use STRING as prefix to the exported C symbols", metavar="STRING") parser.add_option( "--crc-type", action="store", type="string", dest="crc_type", help="when generating source code, use STRING as crc_t type", metavar="STRING") parser.add_option( "--include-file", action="append", type="string", dest="include_files", help= "when generating source code, include also FILE as header file; can be specified multiple times", metavar="FILE") parser.add_option( "-o", "--output", action="store", type="string", dest="output_file", help="write the generated code to file instead to stdout", metavar="FILE") (options, args) = parser.parse_args(argv) undefined_params = [] if options.width != None: self.Width = options.width else: undefined_params.append("--width") if options.poly != None: self.Poly = options.poly else: undefined_params.append("--poly") if options.reflect_in != None: self.ReflectIn = options.reflect_in else: undefined_params.append("--reflect-in") if options.xor_in != None: self.XorIn = options.xor_in else: undefined_params.append("--xor-in") if options.reflect_out != None: self.ReflectOut = options.reflect_out else: undefined_params.append("--reflect-out") if options.xor_out != None: self.XorOut = options.xor_out else: undefined_params.append("--xor-out") if options.table_idx_width != None: if options.table_idx_width == 1 or \ options.table_idx_width == 2 or \ options.table_idx_width == 4 or \ options.table_idx_width == 8: self.TableIdxWidth = options.table_idx_width self.TableWidth = 1 << options.table_idx_width else: sys.stderr.write( "%s: error: unsupported table-idx-width %d\n" % (sys.argv[0], options.table_idx_width)) sys.exit(1) if self.Width != None: if self.Width <= 0: sys.stderr.write( "%s: error: Width must be strictly positive\n" % sys.argv[0]) sys.exit(1) self.MSB_Mask = 0x1 << (self.Width - 1) self.Mask = ((self.MSB_Mask - 1) << 1) | 1 if self.Poly != None: self.Poly = self.Poly & self.Mask if self.XorIn != None: self.XorIn = self.XorIn & self.Mask if self.XorOut != None: self.XorOut = self.XorOut & self.Mask else: self.MSB_Mask = None self.Mask = None if self.Width == None or \ self.Poly == None or \ self.ReflectIn == None or \ self.XorIn == None or \ self.ReflectOut == None or \ self.XorOut == None: self.UndefinedCrcParameters = True else: self.UndefinedCrcParameters = False if options.algorithm != None: alg = options.algorithm.lower() if alg in set(["bit-by-bit", "bbb", "all"]): self.Algorithm |= self.Algo_Bit_by_Bit if alg in set(["bit-by-bit-fast", "bbf", "all"]): self.Algorithm |= self.Algo_Bit_by_Bit_Fast if alg in set(["bitwise-expression", "bwe", "all"]): self.Algorithm |= self.Algo_Bitwise_Expression if alg in set(["table-driven", "tbl", "all"]): self.Algorithm |= self.Algo_Table_Driven if self.Algorithm == 0: sys.stderr.write("%s: error: unknown algorithm %s\n" % (sys.argv[0], options.algorithm)) sys.exit(1) if self.Algorithm & self.Algo_Bitwise_Expression and self.UndefinedCrcParameters: if self.Algorithm == self.Algo_Bitwise_Expression: sys.stderr.write( "Error: algorithm %s not applicable with undefined parameters\n" % options.algorithm) sys.exit(1) else: self.Algorithm &= ~(self.Algo_Bitwise_Expression) if options.c_std != None: std = options.c_std.upper() if std == "ANSI" or std == "C89": self.CStd = "C89" elif std == "C99": self.CStd = std else: sys.stderr.write("%s: error: unknown C standard %s\n" % (sys.argv[0], options.c_std)) sys.exit(1) if options.symbol_prefix != None: self.SymbolPrefix = options.symbol_prefix if options.include_files != None: self.IncludeFiles = options.include_files if options.crc_type != None: self.CrcType = options.crc_type if options.output_file != None: self.OutputFile = options.output_file op_count = 0 if options.check_string != None: self.Action = self.Action_Check_String self.CheckString = options.check_string self.Algorithm &= ~(self.Algo_Bitwise_Expression) op_count += 1 if options.check_hexstring != None: self.Action = self.Action_Check_Hex_String self.CheckString = options.check_hexstring self.Algorithm &= ~(self.Algo_Bitwise_Expression) op_count += 1 if options.check_file != None: self.Action = self.Action_Check_File self.CheckFile = options.check_file self.Algorithm &= ~(self.Algo_Bitwise_Expression) op_count += 1 if options.generate != None: arg = options.generate.lower() if arg == 'h': self.Action = self.Action_Generate_H elif arg == 'c': self.Action = self.Action_Generate_C elif arg == 'c-main': self.Action = self.Action_Generate_C_Main elif arg == 'table': self.Action = self.Action_Generate_Table else: sys.stderr.write("%s: error: don't know how to generate %s\n" % (sys.argv[0], options.generate)) sys.exit(1) op_count += 1 if self.Action == self.Action_Generate_Table: if self.Algorithm & self.Algo_Table_Driven == 0: sys.stderr.write( "%s: error: the --generate table option is incompatible with the --algorithm option\n" % sys.argv[0]) sys.exit(1) self.Algorithm = self.Algo_Table_Driven elif self.Algorithm not in set([ self.Algo_Bit_by_Bit, self.Algo_Bit_by_Bit_Fast, self.Algo_Bitwise_Expression, self.Algo_Table_Driven ]): sys.stderr.write( "%s: error: select an algorithm to be used in the generated file\n" % sys.argv[0]) sys.exit(1) else: if self.TableIdxWidth != 8: sys.stderr.write( "%s: warning: reverting to Table Index Width = 8 for internal CRC calculation\n" % sys.argv[0]) self.TableIdxWidth = 8 self.TableWidth = 1 << options.table_idx_width if op_count == 0: self.Action = self.Action_Check_String if op_count > 1: sys.stderr.write("%s: error: too many actions scecified\n" % sys.argv[0]) sys.exit(1) if (self.Algorithm == self.Algo_Bitwise_Expression) and \ (self.Action == self.Action_Check_String or self.Action == self.Action_Check_Hex_String or self.Action == self.Action_Check_File): sys.stderr.write( "Error: algorithm %s is only applicable to generate source code\n" % options.algorithm) sys.exit(1) if len(args) != 0: sys.stderr.write("%s: error: unrecognized argument(s): %s\n" % (sys.argv[0], " ".join(args))) sys.exit(1) if self.UndefinedCrcParameters and self.Action in set( (self.Action_Check_String, self.Action_Check_Hex_String, self.Action_Check_File, self.Action_Generate_Table)): sys.stderr.write( "%s: error: undefined parameters: Add %s or use --model\n" % (sys.argv[0], ", ".join(undefined_params))) sys.exit(1) self.Verbose = options.verbose
def parse(self, argv = None): """ Parses and validates the options given as arguments """ usage = """\ %prog [OPTIONS] To generate the checksum of a string or hexadecimal data: %prog [model] --check-string "123456789" %prog [model] --check-hexstring "313233343536373839" To generate the checksum of a file: %prog [model] --check-file filename To generate the c-source and write it to filename: %prog [model] --generate c -o filename The model can be defined by the --model switch or by specifying each of the following parameters: --width --poly --reflect-in --xor-in --reflect-out --xor-out""" models = CrcModels() model_list = ", ".join(models.getList()) parser = OptionParser(option_class=MyOption, usage=usage, version=self.VersionStr) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="print information about the model") parser.add_option("--check-string", action="store", type="string", dest="check_string", help="calculate the checksum of the given string (default: '123456789')", metavar="STRING") parser.add_option("--check-hexstring", action="store", type="string", dest="check_hexstring", help="calculate the checksum of the given hexadecimal number string", metavar="STRING") parser.add_option("--check-file", action="store", type="string", dest="check_file", help="calculate the checksum of the given file", metavar="FILE") parser.add_option("--generate", action="store", type="string", dest="generate", default=None, help="choose which type of code to generate from {c, h, c-main, table}", metavar="CODE") parser.add_option("--std", action="store", type="string", dest="c_std", default="C99", help="C standard style of the generated code from {C89, ANSI, C99}", metavar="STD") parser.add_option("--algorithm", action="store", type="string", dest="algorithm", default="all", help="choose an algorithm from {bit-by-bit, bit-by-bit-fast, table-driven, all}", metavar="ALGO") parser.add_option("--model", action="callback", callback=self.model_cb, type="string", dest="model", default=None, help="choose a parameter set from {%s}" % model_list, metavar="MODEL") parser.add_option("--width", action="store", type="hex", dest="width", help="use NUM bits in the polynomial", metavar="NUM") parser.add_option("--poly", action="store", type="hex", dest="poly", help="use HEX as Polynom", metavar="HEX") parser.add_option("--reflect-in", action="store", type="bool", dest="reflect_in", help="reflect input bytes", metavar="BOOL") parser.add_option("--xor-in", action="store", type="hex", dest="xor_in", help="use HEX as initial value", metavar="HEX") parser.add_option("--reflect-out", action="store", type="bool", dest="reflect_out", help="reflect output bytes", metavar="BOOL") parser.add_option("--xor-out", action="store", type="hex", dest="xor_out", help="xor the final crc value with HEX", metavar="HEX") parser.add_option("--table-idx-width", action="store", type="int", dest="table_idx_width", help="use NUM bits to index the crc table; NUM must be one of the values {1, 2, 4, 8}", metavar="NUM") parser.add_option("--symbol-prefix", action="store", type="string", dest="symbol_prefix", help="when generating source code, use STRING as prefix to the generated symbols", metavar="STRING") parser.add_option("--crc-type", action="store", type="string", dest="crc_type", help="when generating source code, use STRING as crc_t type", metavar="STRING") parser.add_option("--include-file", action="store", type="string", dest="include_file", help="when generating source code, use FILE as additional include file", metavar="FILE") parser.add_option("-o", "--output", action="store", type="string", dest="output_file", help="write the generated code to file instead to stdout", metavar="FILE") (options, args) = parser.parse_args(argv) undefined_params = [] if options.width != None: self.Width = options.width else: undefined_params.append("--width") if options.poly != None: self.Poly = options.poly else: undefined_params.append("--poly") if options.reflect_in != None: self.ReflectIn = options.reflect_in else: undefined_params.append("--reflect-in") if options.xor_in != None: self.XorIn = options.xor_in else: undefined_params.append("--xor-in") if options.reflect_out != None: self.ReflectOut = options.reflect_out else: undefined_params.append("--reflect-out") if options.xor_out != None: self.XorOut = options.xor_out else: undefined_params.append("--xor-out") if options.table_idx_width != None: if options.table_idx_width == 1 or \ options.table_idx_width == 2 or \ options.table_idx_width == 4 or \ options.table_idx_width == 8: self.TableIdxWidth = options.table_idx_width self.TableWidth = 1 << options.table_idx_width else: sys.stderr.write("%s: error: unsupported table-idx-width %d\n" % (sys.argv[0], options.table_idx_width)) sys.exit(1) if self.Poly != None and self.Poly % 2 == 0: sys.stderr.write("%s: warning: the polynomial 0x%x is even. A valid CRC polynomial must be odd.\n" % (sys.argv[0], self.Poly)) if self.Width != None: if self.Width <= 0: sys.stderr.write("%s: error: Width must be strictly positive\n" % sys.argv[0]) sys.exit(1) self.MSB_Mask = 0x1 << (self.Width - 1) self.Mask = ((self.MSB_Mask - 1) << 1) | 1 if self.Poly != None: self.Poly = self.Poly & self.Mask if self.XorIn != None: self.XorIn = self.XorIn & self.Mask if self.XorOut != None: self.XorOut = self.XorOut & self.Mask else: self.MSB_Mask = None self.Mask = None if self.Width == None or \ self.Poly == None or \ self.ReflectIn == None or \ self.XorIn == None or \ self.ReflectOut == None or \ self.XorOut == None: self.UndefinedCrcParameters = True else: self.UndefinedCrcParameters = False if options.algorithm != None: alg = options.algorithm.lower() if alg == "bit-by-bit" or alg == "all": self.Algorithm |= self.Algo_Bit_by_Bit if alg == "bit-by-bit-fast" or alg == "all": self.Algorithm |= self.Algo_Bit_by_Bit_Fast if alg == "table-driven" or alg == "all": self.Algorithm |= self.Algo_Table_Driven if self.Algorithm == 0: sys.stderr.write("%s: error: unknown algorithm %s\n" % (sys.argv[0], options.algorithm)) sys.exit(1) if options.c_std != None: std = options.c_std.upper() if std == "ANSI" or std == "C89": self.CStd = "C89" elif std == "C99": self.CStd = std else: sys.stderr.write("%s: error: unknown C standard %s\n" % (sys.argv[0], options.c_std)) sys.exit(1) if options.symbol_prefix != None: self.SymbolPrefix = options.symbol_prefix if options.include_file != None: self.IncludeFile = options.include_file if options.crc_type != None: self.CrcType = options.crc_type if options.output_file != None: self.OutputFile = options.output_file op_count = 0 if options.check_string != None: self.Action = self.Action_Check_String self.CheckString = options.check_string op_count += 1 if options.check_hexstring != None: self.Action = self.Action_Check_Hex_String self.CheckString = options.check_hexstring op_count += 1 if options.check_file != None: self.Action = self.Action_Check_File self.CheckFile = options.check_file op_count += 1 if options.generate != None: arg = options.generate.lower() if arg == 'h': self.Action = self.Action_Generate_H elif arg == 'c': self.Action = self.Action_Generate_C elif arg == 'c-main': self.Action = self.Action_Generate_C_Main elif arg == 'table': self.Action = self.Action_Generate_Table else: sys.stderr.write("%s: error: don't know how to generate %s\n" % (sys.argv[0], options.generate)) sys.exit(1) op_count += 1 if self.Action == self.Action_Generate_Table: if self.Algorithm & self.Algo_Table_Driven == 0: sys.stderr.write("%s: error: the --generate table option is incompatible with the --algorithm option\n" % sys.argv[0]) sys.exit(1) self.Algorithm = self.Algo_Table_Driven elif self.Algorithm != self.Algo_Bit_by_Bit and self.Algorithm != self.Algo_Bit_by_Bit_Fast and self.Algorithm != self.Algo_Table_Driven: sys.stderr.write("%s: error: select an algorithm to be used in the generated file\n" % sys.argv[0]) sys.exit(1) else: if self.TableIdxWidth != 8: sys.stderr.write("%s: warning: reverting to Table Index Width = 8 for internal CRC calculation\n" % sys.argv[0]) self.TableIdxWidth = 8 self.TableWidth = 1 << options.table_idx_width if op_count == 0: self.Action = self.Action_Check_String if op_count > 1: sys.stderr.write("%s: error: too many actions scecified\n" % sys.argv[0]) sys.exit(1) if len(args) != 0: sys.stderr.write("%s: error: unrecognized argument(s): %s\n" % (sys.argv[0], " ".join(args))) sys.exit(1) if self.UndefinedCrcParameters and self.Action in set((self.Action_Check_String, self.Action_Check_Hex_String, self.Action_Check_File, self.Action_Generate_Table)): sys.stderr.write("%s: error: undefined parameters: Add %s or use --model\n" % (sys.argv[0], ", ".join(undefined_params))) sys.exit(1) self.Verbose = options.verbose
def __test_variable_width(self): """ Test variable width. """ if self.verbose: print("Running __test_variable_width()...") models = CrcModels() m = models.getParams("crc-64-jones") for width in [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 23, 24, 25, 31, 32, 33, 63, 64 ]: mask = (1 << width) - 1 mw = { 'width': width, 'poly': m['poly'] & mask, 'reflect_in': m['reflect_in'], 'xor_in': m['xor_in'] & mask, 'reflect_out': m['reflect_out'], 'xor_out': m['xor_out'] & mask, } args = "--width %(width)s --poly 0x%(poly)x --xor-in 0x%(xor_in)x --reflect-in %(reflect_in)s --xor-out 0x%(xor_out)x --reflect-out %(reflect_out)s" % mw check = self.__get_crc(mw) if check == None: return False if self.use_algo_bit_by_bit: if self.crc_bin_bbb_c99 != None: if not self.__check_command( self.crc_bin_bbb_c99 + " " + args, check): return False filename = self.__make_bin( "--algorithm bit-by-bit" + " " + args, "crc_bbb_arg") if filename == None: return False ret = self.__check_command(filename, check) self.__del_files([filename, filename + ".h", filename + ".c"]) if not ret: return False if self.use_algo_bit_by_bit_fast: if self.crc_bin_bbf_c99 != None: if not self.__check_command( self.crc_bin_bbf_c99 + " " + args, check): return False filename = self.__make_bin( "--algorithm bit-by-bit-fast" + " " + args, "crc_bbf_arg") if filename == None: return False ret = self.__check_command(filename, check) self.__del_files([filename, filename + ".h", filename + ".c"]) if not ret: return False if self.use_algo_bitwise_expression: if self.crc_bin_bwe_c99 != None: if not self.__check_command( self.crc_bin_bwe_c99 + " " + args, check): return False filename = self.__make_bin( "--algorithm bitwise-expression" + " " + args, "crc_bwe_arg") if filename == None: return False ret = self.__check_command(filename, check) self.__del_files([filename, filename + ".h", filename + ".c"]) if not ret: return False if self.use_algo_table_driven: if self.crc_bin_tbl_c99 != None: if not self.__check_command( self.crc_bin_tbl_c99 + " " + args, check): return False filename = self.__make_bin( "--algorithm table-driven" + " " + args, "crc_tbl_arg") if filename == None: return False ret = self.__check_command(filename, check) self.__del_files([filename, filename + ".h", filename + ".c"]) if not ret: return False return True
def parse(self, argv=None): """ Parses and validates the options given as arguments """ # pylint: disable=too-many-branches, too-many-statements usage = """python %prog [OPTIONS] To calculate the checksum of a string or hexadecimal data: python %prog [model] --check-string "123456789" python %prog [model] --check-hexstring "313233343536373839" To calculate the checksum of a file: python %prog [model] --check-file filename To generate the C source code and write it to filename: python %prog [model] --generate c -o filename The model can be defined either with the --model switch or by specifying each of the following parameters: --width --poly --reflect-in --xor-in --reflect-out --xor-out""" models = CrcModels() model_list = ", ".join(models.names()) parser = OptionParser(option_class=MyOption, usage=usage, version=self.version_str) parser.add_option( "-v", "--verbose", action="store_true", dest="verbose", default=False, help="be more verbose; print the value of the parameters " "and the chosen model to stdout") parser.add_option( "--check-string", action="store", type="string", dest="check_string", help="calculate the checksum of a string (default: '123456789')", metavar="STRING") parser.add_option( "--check-hexstring", action="store", type="string", dest="check_hexstring", help="calculate the checksum of a hexadecimal number string", metavar="STRING") parser.add_option( "--check-file", action="store", type="string", dest="check_file", help="calculate the checksum of a file", metavar="FILE") parser.add_option( "--generate", action="store", type="string", dest="generate", default=None, help="generate C source code; choose the type from {h, c, c-main, table}", metavar="CODE") parser.add_option( "--std", action="store", type="string", dest="c_std", default="C99", help="choose the C dialect of the generated code from {C89, ANSI, C99}", metavar="STD") parser.add_option( "--algorithm", action="store", type="string", dest="algorithm", default="all", help="choose an algorithm from " "{bit-by-bit, bbb, bit-by-bit-fast, bbf, table-driven, tbl, all}", metavar="ALGO") parser.add_option( "--model", action="callback", callback=_model_cb, type="string", dest="model", default=None, help="choose a parameter set from {{{0:s}}}".format(model_list), metavar="MODEL") parser.add_option( "--width", action="store", type="hex", dest="width", help="use NUM bits in the polynomial", metavar="NUM") parser.add_option( "--poly", action="store", type="hex", dest="poly", help="use HEX as polynomial", metavar="HEX") parser.add_option( "--reflect-in", action="store", type="bool", dest="reflect_in", help="reflect the octets in the input message", metavar="BOOL") parser.add_option( "--xor-in", action="store", type="hex", dest="xor_in", help="use HEX as initial value", metavar="HEX") parser.add_option( "--reflect-out", action="store", type="bool", dest="reflect_out", help="reflect the resulting checksum before applying the --xor-out value", metavar="BOOL") parser.add_option( "--xor-out", action="store", type="hex", dest="xor_out", help="xor the final CRC value with HEX", metavar="HEX") parser.add_option( "--slice-by", action="store", type="int", dest="slice_by", help="read NUM bytes at a time from the input. NUM must be one of the values {4, 8, 16}", metavar="NUM") parser.add_option( "--table-idx-width", action="store", type="int", dest="table_idx_width", help="use NUM bits to index the CRC table; NUM must be one of the values {1, 2, 4, 8}", metavar="NUM") parser.add_option( "--symbol-prefix", action="store", type="string", dest="symbol_prefix", help="when generating source code, use STRING as prefix to the exported C symbols", metavar="STRING") parser.add_option( "--crc-type", action="store", type="string", dest="crc_type", help="when generating source code, use STRING as crc_t type", metavar="STRING") parser.add_option( "--include-file", action="append", type="string", dest="include_files", help="when generating source code, include also FILE as header file; " "can be specified multiple times", metavar="FILE") parser.add_option( "-o", "--output", action="store", type="string", dest="output_file", help="write the generated code to file instead to stdout", metavar="FILE") (options, args) = parser.parse_args(argv) if options.c_std != None: std = options.c_std.upper() if std == "ANSI" or std == "C89": self.c_std = "C89" elif std == "C99": self.c_std = std else: self.__error("unknown C standard {0:s}".format(options.c_std)) undefined_params = [] if options.width != None: self.width = options.width else: undefined_params.append("--width") if options.poly != None: self.poly = options.poly else: undefined_params.append("--poly") if options.reflect_in != None: self.reflect_in = options.reflect_in else: undefined_params.append("--reflect-in") if options.xor_in != None: self.xor_in = options.xor_in else: undefined_params.append("--xor-in") if options.reflect_out != None: self.reflect_out = options.reflect_out else: undefined_params.append("--reflect-out") if options.xor_out != None: self.xor_out = options.xor_out else: undefined_params.append("--xor-out") if options.table_idx_width != None: if options.table_idx_width in set((1, 2, 4, 8)): self.tbl_idx_width = options.table_idx_width self.tbl_width = 1 << options.table_idx_width else: self.__error("unsupported table-idx-width {0:d}".format(options.table_idx_width)) if self.width != None: if self.width <= 0: self.__error("Width must be strictly positive") self.msb_mask = 0x1 << (self.width - 1) self.mask = ((self.msb_mask - 1) << 1) | 1 if self.poly != None: self.poly = self.poly & self.mask if self.xor_in != None: self.xor_in = self.xor_in & self.mask if self.xor_out != None: self.xor_out = self.xor_out & self.mask else: self.msb_mask = None self.mask = None if self.width == None or \ self.poly == None or \ self.reflect_in == None or \ self.xor_in == None or \ self.reflect_out == None or \ self.xor_out == None: self.undefined_crc_parameters = True else: self.undefined_crc_parameters = False if options.slice_by != None: if options.slice_by in set((4, 8, 16)): self.slice_by = options.slice_by else: self.__error("unsupported slice-by {0:d}".format(options.slice_by)) if self.undefined_crc_parameters: self.__error("slice-by is only implemented for fully defined models") if self.tbl_idx_width != 8: self.__error("slice-by is only implemented for table-idx-width=8") # FIXME tp: Fix corner cases and disable the following tests if self.width < 8: self.__warning("disabling slice-by for width {0}".format(self.width)) self.slice_by = 1 if self.width < 16: self.__warning("disabling slice-by for width {0}".format(self.width)) self.slice_by = 1 if self.width > 32: self.__warning("disabling slice-by for width {0}".format(self.width)) self.slice_by = 1 if not self.reflect_in: self.__warning("disabling slice-by for non-reflected algorithm") self.slice_by = 1 # FIXME tp: reintroduce this? # if self.width % 8 != 0: # self.__error("slice-by is only implemented for width multiples of 8") # if options.slice_by < self.width / 8: # self.__error("slice-by must be greater or equal width / 8") if self.c_std == "C89": self.__error("--slice-by not supported for C89") if options.algorithm != None: alg = options.algorithm.lower() if alg in set(["bit-by-bit", "bbb", "all"]): self.algorithm |= self.algo_bit_by_bit if alg in set(["bit-by-bit-fast", "bbf", "all"]): self.algorithm |= self.algo_bit_by_bit_fast if alg in set(["table-driven", "tbl", "all"]): self.algorithm |= self.algo_table_driven if self.algorithm == 0: self.__error("unknown algorithm {0:s}".format(options.algorithm)) if options.symbol_prefix != None: self.symbol_prefix = options.symbol_prefix if options.include_files != None: self.include_files = options.include_files if options.crc_type != None: self.crc_type = options.crc_type if options.output_file != None: self.output_file = options.output_file op_count = 0 if options.check_string != None: self.action = self.action_check_str self.check_string = options.check_string op_count += 1 if options.check_hexstring != None: self.action = self.action_check_hex_str self.check_string = options.check_hexstring op_count += 1 if options.check_file != None: self.action = self.action_check_file self.check_file = options.check_file op_count += 1 if options.generate != None: arg = options.generate.lower() if arg == 'h': self.action = self.action_generate_h elif arg == 'c': self.action = self.action_generate_c elif arg == 'c-main': self.action = self.action_generate_c_main elif arg == 'table': self.action = self.action_generate_table else: self.__error("don't know how to generate {0:s}".format(options.generate)) op_count += 1 if self.action == self.action_generate_table: if self.algorithm & self.algo_table_driven == 0: self.__error("the --generate table option is incompatible " "with the --algorithm option") self.algorithm = self.algo_table_driven elif self.algorithm not in set( [self.algo_bit_by_bit, self.algo_bit_by_bit_fast, self.algo_table_driven]): self.__error("select an algorithm to be used in the generated file") else: if self.tbl_idx_width != 8: self.__warning("reverting to Table Index Width = 8 " "for internal CRC calculation") self.tbl_idx_width = 8 self.tbl_width = 1 << options.table_idx_width if op_count == 0: self.action = self.action_check_str if op_count > 1: self.__error("too many actions specified") if len(args) != 0: self.__error("unrecognized argument(s): {0:s}".format(" ".join(args))) def_params_acts = (self.action_check_str, self.action_check_hex_str, self.action_check_file, self.action_generate_table) if self.undefined_crc_parameters and self.action in set(def_params_acts): self.__error("undefined parameters: Add {0:s} or use --model" .format(", ".join(undefined_params))) self.verbose = options.verbose
def parse(self, argv=None): """ Parses and validates the options given as arguments """ usage = """\ %prog [OPTIONS]""" models = CrcModels() model_list = ", ".join(models.getList()) algorithms = ", ".join(sorted(list(self.AllAlgorithms)) + ["all"]) parser = OptionParser(usage=usage) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=self.Verbose, help="print information about the model") parser.add_option("-3", "--python3", action="store_true", dest="python3", default=self.Python3, help="use Python3.x") parser.add_option("-c", "--compile", action="store_true", dest="compile", default=self.Compile, help="test compiled version") parser.add_option("-r", "--random-parameters", action="store_true", dest="random_parameters", default=self.RandomParameters, help="test random parameters") parser.add_option( "-m", "--compile-mixed-arguments", action="store_true", dest="compile_mixed_args", default=self.CompileMixedArgs, help= "test compiled C program with some arguments given at compile time some arguments given at runtime" ) parser.add_option("-w", "--variable-width", action="store_true", dest="variable_width", default=self.VariableWidth, help="test variable width from 1 to 64") parser.add_option("-a", "--all", action="store_true", dest="all", default=False, help="do all tests") parser.add_option("--algorithm", action="store", type="string", dest="algorithm", default="all", help="choose an algorithm from {%s}" % algorithms, metavar="ALGO") (options, args) = parser.parse_args(argv) self.Verbose = options.verbose self.Python3 = options.python3 self.Compile = options.all or options.compile or options.random_parameters self.RandomParameters = options.all or options.random_parameters self.CompileMixedArgs = options.all or options.compile_mixed_args self.VariableWidth = options.all or options.variable_width if options.algorithm != None: alg = options.algorithm.lower() if alg in self.AllAlgorithms: self.Algorithm = set([alg]) elif alg == "all": self.Algorithm = copy(self.AllAlgorithms) else: sys.stderr.write("unknown algorithm: %s\n" % alg) sys.exit(1)
def parse(self, argv=None): """ Parses and validates the options given as arguments """ # pylint: disable=too-many-branches, too-many-statements usage = """python %prog [OPTIONS] To calculate the checksum of a string or hexadecimal data: python %prog [model] --check-string "123456789" python %prog [model] --check-hexstring "313233343536373839" To calculate the checksum of a file: python %prog [model] --check-file filename To generate the C source code and write it to filename: python %prog [model] --generate c -o filename The model can be defined either with the --model switch or by specifying each of the following parameters: --width --poly --reflect-in --xor-in --reflect-out --xor-out""" models = CrcModels() model_list = ", ".join(models.get_list()) parser = OptionParser(option_class=MyOption, usage=usage, version=self.version_str) parser.add_option( "-v", "--verbose", action="store_true", dest="verbose", default=False, help="be more verbose; print the value of the parameters " "and the chosen model to stdout") parser.add_option( "--check-string", action="store", type="string", dest="check_string", help="calculate the checksum of a string (default: '123456789')", metavar="STRING") parser.add_option( "--check-hexstring", action="store", type="string", dest="check_hexstring", help="calculate the checksum of a hexadecimal number string", metavar="STRING") parser.add_option( "--check-file", action="store", type="string", dest="check_file", help="calculate the checksum of a file", metavar="FILE") parser.add_option( "--generate", action="store", type="string", dest="generate", default=None, help="generate C source code; choose the type from {h, c, c-main, table}", metavar="CODE") parser.add_option( "--std", action="store", type="string", dest="c_std", default="C99", help="choose the C dialect of the generated code from {C89, ANSI, C99}", metavar="STD") parser.add_option( "--algorithm", action="store", type="string", dest="algorithm", default="all", help="choose an algorithm from " "{bit-by-bit, bbb, bit-by-bit-fast, bbf, table-driven, tbl, all}", metavar="ALGO") parser.add_option( "--model", action="callback", callback=_model_cb, type="string", dest="model", default=None, help="choose a parameter set from {{{0:s}}}".format(model_list), metavar="MODEL") parser.add_option( "--width", action="store", type="hex", dest="width", help="use NUM bits in the polynomial", metavar="NUM") parser.add_option( "--poly", action="store", type="hex", dest="poly", help="use HEX as polynomial", metavar="HEX") parser.add_option( "--reflect-in", action="store", type="bool", dest="reflect_in", help="reflect the octets in the input message", metavar="BOOL") parser.add_option( "--xor-in", action="store", type="hex", dest="xor_in", help="use HEX as initial value", metavar="HEX") parser.add_option( "--reflect-out", action="store", type="bool", dest="reflect_out", help="reflect the resulting checksum before applying the --xor-out value", metavar="BOOL") parser.add_option( "--xor-out", action="store", type="hex", dest="xor_out", help="xor the final CRC value with HEX", metavar="HEX") parser.add_option( "--slice-by", action="store", type="int", dest="slice_by", help="read NUM bytes at a time from the input. NUM must be one of the values {4, 8, 16}", metavar="NUM") parser.add_option( "--table-idx-width", action="store", type="int", dest="table_idx_width", help="use NUM bits to index the CRC table; NUM must be one of the values {1, 2, 4, 8}", metavar="NUM") parser.add_option( "--symbol-prefix", action="store", type="string", dest="symbol_prefix", help="when generating source code, use STRING as prefix to the exported C symbols", metavar="STRING") parser.add_option( "--crc-type", action="store", type="string", dest="crc_type", help="when generating source code, use STRING as crc_t type", metavar="STRING") parser.add_option( "--include-file", action="append", type="string", dest="include_files", help="when generating source code, include also FILE as header file; " "can be specified multiple times", metavar="FILE") parser.add_option( "-o", "--output", action="store", type="string", dest="output_file", help="write the generated code to file instead to stdout", metavar="FILE") (options, args) = parser.parse_args(argv) if options.c_std != None: std = options.c_std.upper() if std == "ANSI" or std == "C89": self.c_std = "C89" elif std == "C99": self.c_std = std else: self.__error("unknown C standard {0:s}".format(options.c_std)) undefined_params = [] if options.width != None: self.width = options.width else: undefined_params.append("--width") if options.poly != None: self.poly = options.poly else: undefined_params.append("--poly") if options.reflect_in != None: self.reflect_in = options.reflect_in else: undefined_params.append("--reflect-in") if options.xor_in != None: self.xor_in = options.xor_in else: undefined_params.append("--xor-in") if options.reflect_out != None: self.reflect_out = options.reflect_out else: undefined_params.append("--reflect-out") if options.xor_out != None: self.xor_out = options.xor_out else: undefined_params.append("--xor-out") if options.table_idx_width != None: if options.table_idx_width in set((1, 2, 4, 8)): self.tbl_idx_width = options.table_idx_width self.tbl_width = 1 << options.table_idx_width else: self.__error("unsupported table-idx-width {0:d}".format(options.table_idx_width)) if self.width != None: if self.width <= 0: self.__error("Width must be strictly positive") self.msb_mask = 0x1 << (self.width - 1) self.mask = ((self.msb_mask - 1) << 1) | 1 if self.poly != None: self.poly = self.poly & self.mask if self.xor_in != None: self.xor_in = self.xor_in & self.mask if self.xor_out != None: self.xor_out = self.xor_out & self.mask else: self.msb_mask = None self.mask = None if self.width == None or \ self.poly == None or \ self.reflect_in == None or \ self.xor_in == None or \ self.reflect_out == None or \ self.xor_out == None: self.undefined_crc_parameters = True else: self.undefined_crc_parameters = False if options.slice_by != None: if options.slice_by in set((4, 8, 16)): self.slice_by = options.slice_by else: self.__error("unsupported slice-by {0:d}".format(options.slice_by)) if self.undefined_crc_parameters: self.__error("slice-by is only implemented for fully defined models") if self.tbl_idx_width != 8: self.__error("slice-by is only implemented for table-idx-width=8") # FIXME tp: Fix corner cases and disable the following tests if self.width < 8: self.__warning("disabling slice-by for width {0}".format(self.width)) self.slice_by = 1 if self.width < 16: self.__warning("disabling slice-by for width {0}".format(self.width)) self.slice_by = 1 if self.width > 32: self.__warning("disabling slice-by for width {0}".format(self.width)) self.slice_by = 1 if not self.reflect_in: self.__warning("disabling slice-by for non-reflected algorithm") self.slice_by = 1 # FIXME tp: reintroduce this? # if self.width % 8 != 0: # self.__error("slice-by is only implemented for width multiples of 8") # if options.slice_by < self.width / 8: # self.__error("slice-by must be greater or equal width / 8") if self.c_std == "C89": self.__error("--slice-by not supported for C89") if options.algorithm != None: alg = options.algorithm.lower() if alg in set(["bit-by-bit", "bbb", "all"]): self.algorithm |= self.algo_bit_by_bit if alg in set(["bit-by-bit-fast", "bbf", "all"]): self.algorithm |= self.algo_bit_by_bit_fast if alg in set(["table-driven", "tbl", "all"]): self.algorithm |= self.algo_table_driven if self.algorithm == 0: self.__error("unknown algorithm {0:s}".format(options.algorithm)) if options.symbol_prefix != None: self.symbol_prefix = options.symbol_prefix if options.include_files != None: self.include_files = options.include_files if options.crc_type != None: self.crc_type = options.crc_type if options.output_file != None: self.output_file = options.output_file op_count = 0 if options.check_string != None: self.action = self.action_check_str self.check_string = options.check_string op_count += 1 if options.check_hexstring != None: self.action = self.action_check_hex_str self.check_string = options.check_hexstring op_count += 1 if options.check_file != None: self.action = self.action_check_file self.check_file = options.check_file op_count += 1 if options.generate != None: arg = options.generate.lower() if arg == 'h': self.action = self.action_generate_h elif arg == 'c': self.action = self.action_generate_c elif arg == 'c-main': self.action = self.action_generate_c_main elif arg == 'table': self.action = self.action_generate_table else: self.__error("don't know how to generate {0:s}".format(options.generate)) op_count += 1 if self.action == self.action_generate_table: if self.algorithm & self.algo_table_driven == 0: self.__error("the --generate table option is incompatible " "with the --algorithm option") self.algorithm = self.algo_table_driven elif self.algorithm not in set( [self.algo_bit_by_bit, self.algo_bit_by_bit_fast, self.algo_table_driven]): self.__error("select an algorithm to be used in the generated file") else: if self.tbl_idx_width != 8: self.__warning("reverting to Table Index Width = 8 " "for internal CRC calculation") self.tbl_idx_width = 8 self.tbl_width = 1 << options.table_idx_width if op_count == 0: self.action = self.action_check_str if op_count > 1: self.__error("too many actions scecified") if len(args) != 0: self.__error("unrecognized argument(s): {0:s}".format(" ".join(args))) def_params_acts = (self.action_check_str, self.action_check_hex_str, self.action_check_file, self.action_generate_table) if self.undefined_crc_parameters and self.action in set(def_params_acts): self.__error("undefined parameters: Add {0:s} or use --model" .format(", ".join(undefined_params))) self.verbose = options.verbose
def __test_variable_width(self): """ Test variable width. """ if self.verbose: print("Running __test_variable_width()...") models = CrcModels() m = models.getParams("crc-64-jones") for width in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 23, 24, 25, 31, 32, 33, 63, 64]: mask = (1 << width) - 1 mw = { 'width': width, 'poly': m['poly'] & mask, 'reflect_in': m['reflect_in'], 'xor_in': m['xor_in'] & mask, 'reflect_out': m['reflect_out'], 'xor_out': m['xor_out'] & mask, } args = "--width %(width)s --poly 0x%(poly)x --xor-in 0x%(xor_in)x --reflect-in %(reflect_in)s --xor-out 0x%(xor_out)x --reflect-out %(reflect_out)s" % mw check = self.__get_crc(mw) if check == None: return False if self.use_algo_bit_by_bit: if self.crc_bin_bbb_c99 != None: if not self.__check_command(self.crc_bin_bbb_c99 + " " + args, check): return False filename = self.__make_bin("--algorithm table-driven" + " " + args, "crc_bbb_arg") if filename == None: return False ret = self.__check_command(filename, check) self.__del_files([filename, filename+".h", filename+".c"]) if not ret: return False if self.use_algo_bit_by_bit_fast: if self.crc_bin_bbf_c99 != None: if not self.__check_command(self.crc_bin_bbf_c99 + " " + args, check): return False filename = self.__make_bin("--algorithm table-driven" + " " + args, "crc_bbf_arg") if filename == None: return False ret = self.__check_command(filename, check) self.__del_files([filename, filename+".h", filename+".c"]) if not ret: return False if self.use_algo_table_driven: if self.crc_bin_tbl_c99 != None: if not self.__check_command(self.crc_bin_tbl_c99 + " " + args, check): return False filename = self.__make_bin("--algorithm table-driven" + " " + args, "crc_tbl_arg") if filename == None: return False ret = self.__check_command(filename, check) self.__del_files([filename, filename+".h", filename+".c"]) if not ret: return False return True