def __handle_recursive(self, data_prov_object, level, path): if level == 4: for item in os.listdir(path): if item.endswith(".xml"): data_prov_object.config = self.handle_meta_config(c_path.join(path, item)) elif c_path.validate_dir(c_path.join(path, item)): raise RuntimeError("DataProvisioner: found directory {0} in binary_file level of DataProvisioner. \ Directories are not allowed in the binary_file level".format(item)) else: try: with open(c_path.join(path, item), "r") as data_file: data_prov_object.files[item] = data_file.read() except: raise RuntimeError("DataProvisioner: Can't open {0}".format(c_path.join(path, item))) return for item in os.listdir(path): if item.endswith(".xml"): pass # configs at not the 4th level arent supported data_prov_object.config = self.handle_meta_config(c_path.join(path, item)) elif c_path.validate_dir(c_path.join(path, item)) == False: raise RuntimeError("DataProvisioner: found binary file {0} in level {1} of DataProvisioner. \ Binary files are only allowed at the binary_file level".format(item, level_num_to_name(level))) child_data_prov_object = DataProvObject(item, c_path.join(path, item)) data_prov_object.children[item] = child_data_prov_object self.__handle_recursive(child_data_prov_object, level + 1, c_path.join(path, item))
def __init__(self, config_dir): """Initializations and checks""" if not c_path.validate_dir(config_dir): raise RuntimeError('Directory doesnt exist: ' + config_dir) # First level of directory that is expected sub_config_dir = c_path.join(config_dir, defines.CONFIG_DIR_BASENAME) try: c_path.validate_dir(sub_config_dir) except Exception as e: raise RuntimeError('Directory ' + config_dir + '\n' ' ' + 'must contain configs sub directory: ' + defines.CONFIG_DIR_BASENAME) self.config_dir = sub_config_dir
def _populate_database(cls, data_prov_object, level, path): """ Recursively creates and fills in the DataProvObject including all of it's children :param data_prov_object: the highest level of the DataProvObject hierarchy :type data_prov_object: DataProvObject :param level: the level depth of the current data prov hierarchy. Should be set to 1 when initially calling _populate_database :type level: int :param path: the path in the file system corresponding to the current data prov level through which to scan and populate the DataProvObject :type path: str :rtype: None :raises: RuntimeError """ for item in os.listdir(path): if item.endswith(".xml") and level == BINARY_FILE_LEVEL: data_prov_object.config = cls._get_config( c_path.join(path, item)) # allow for unix style hidden folders to exist elif item.startswith("."): continue elif c_path.validate_dir(c_path.join( path, item)) and level == BINARY_FILE_LEVEL: raise RuntimeError( "DataProvisioner: found directory {0} in binary_file level of DataProvisioner. \ Directories are not allowed in the binary_file level".format( item)) elif not c_path.validate_dir(c_path.join( path, item)) and level != BINARY_FILE_LEVEL: raise RuntimeError( "DataProvisioner: found binary file {0} in level {1} of DataProvisioner. \ Binary files are only allowed at the binary_file level".format( item, cls._level_num_to_name(level))) elif level == 4: try: data_prov_object.files[item] = c_path.load_data_from_file( c_path.join(path, item)) except: raise RuntimeError( "DataProvisioner: Can't open {0}".format( c_path.join(path, item))) # recursively populate database children if level < BINARY_FILE_LEVEL: child_data_prov_object = DataProvObject( item, c_path.join(path, item)) data_prov_object.children[item] = child_data_prov_object cls._populate_database(child_data_prov_object, level + 1, c_path.join(path, item))
def verify(self): '''verifies self.database is correct. Checks for type/bin file mismatch. bin files not in level 3. Lack of binfiles. Too many binfiles. Etc.Some things are implicitly verified by the file handler, like existence of files/folders and correct paths, since it can't create the database with bad paths :raises: RuntimeError ''' if len(self.database.files) > 0: raise RuntimeError("DataProvisioner: binary files {0} exist within security_policy level of Data Provisioning file structure").format(self.database.files) for lvl1_name, lvl1_obj in self.database.children.items(): if len(lvl1_obj.files) > 0 : raise RuntimeError("DataProvisioner: binary files {0} exists within security_policy_type level of Data Provisioning file structure").format(lvl1_obj.files) for lvl2_name, lvl2_obj in lvl1_obj.children.items(): if len(lvl2_obj.files) > 0 : raise RuntimeError("DataProvisioner: binary files {0} exists within data_prov_id level of Data Provisioning file structure").format(lvl2_obj.files) for lvl3_name, lvl3_obj in lvl2_obj.children.items(): # if len(lvl3_obj.files) == 0: # raise RuntimeError("DataProvisioner: there are no binary files in data_prov_id of Data Provisioning file structure. {0}".format(lvl3_obj.path)) for file_name in lvl3_obj.files: if c_path.validate_dir(file_name): raise RuntimeError("DataProvisioner: Directories are not allowed within the data_prov_id directory of the Data Provisioning file structure") logger.debug("DataProvisioner database verification passed") return True
def __init__(self, meta_build_path, config_dir_obj, sign_id_list=[]): assert isinstance(meta_build_path, str) assert isinstance(config_dir_obj, ConfigDir) # Initialize the BaseStager BaseStager.__init__(self) self.config_dir_obj = config_dir_obj # Create internal attributes self._meta_build_path = meta_build_path # Validate that the meta_build path exists meta_build_path = c_path.normalize(meta_build_path) if not c_path.validate_dir(meta_build_path): raise RuntimeError('No read access to the meta build path: ' + meta_build_path) # Get the meta lib module from the metabuild meta_info = self.get_meta_info(meta_build_path) # Create the image info list based on the meta data for sign_id, chipset, image_src_path, image_dest_path in self.get_image_info_from_meta(meta_info): # Filer on the sign id if sign_id_list: if sign_id not in sign_id_list: continue try: img_config_parser = self.get_image_config_parser(chipset) # Validate the sign_id sign_id = self._get_sign_id(img_config_parser, os.path.basename(image_src_path.image_path), sign_id) # Get the config block for the sign id img_config_block = img_config_parser.get_config_for_sign_id(sign_id) # Create the one image info object image_info = ImageInfo('', sign_id, img_config_block, img_config_parser) # Set the src path image_info.src_image = image_src_path image_info.image_under_operation = image_info.src_image.image_path # Set the dest path image_info.dest_image = image_dest_path # Put the image info object into the list self._image_info_list.append(image_info) except Exception as e: logger.error(str(e)) if not self._image_info_list: raise RuntimeError('No images found from the meta build.')
def get_chipset_config_path(self, chipset): """ :param str chipset: chipset to return config file for :returns: config path corresponding to the given chipset :rtype: str """ logger.debug('Searching configs corresponding to chipset: ' + chipset) chipset_dir = c_path.join(self.config_dir, chipset) if c_path.validate_dir(chipset_dir): return self._get_config_path(chipset_dir) raise RuntimeError('Did not find config for chipset: "' + chipset + '"')
def get_chipset_config_paths(self, chipset): """Returns a tuple of the configs found for the chipset dir. If any of the config files is not found in the dir, its value is returned as None. :param str chipset_dir: Chipset to return config files for :returns: (oem_config_path, qc_config_path, ui_config_path, user_config_path) :rtype: (tuple(str)) """ logger.debug('Searching configs corresponding to chipset: ' + chipset) chipset_dir = c_path.join(self.config_dir, chipset) if c_path.validate_dir(chipset_dir): return self._get_config_paths(chipset_dir) raise RuntimeError('Did not find config for chipset: "' + chipset + '"')
def generateMetaBuild(self, timer=1200, interval=5): """ generate new meta build with given image build :param str meta_build_path: meta build directory, require write access :param str image_build_path: image build directory, require read access """ if self.run: self.retcode = '' # meta build path validation meta_path_val = c_path.normalize(self.meta_build_path) if not c_path.validate_dir_write(meta_path_val): raise RuntimeError('Cannot write at: ' + meta_path_val) # image build path validation image_path_val = c_path.normalize(self.image_build_path) if not c_path.validate_dir(image_path_val): raise RuntimeError('Cannot access: ' + image_path_val) """TODO: Don't know how to check if TZ build has changed and if re-generate NON-HLOS.bin is needed. For now, always re-generate meta build. """ # check if meta build has been generated with the required image build already meta_info = self.getMetainfo(self.meta_build_path) path = meta_info.get_build_path(BUILD) tz_path_in_meta_build_val = c_path.normalize(path) generation_complete_flag = c_path.join(meta_path_val, GENERATION_COMPLETE_STR) """ if tz_path_in_meta_build_val == image_path_val and c_path.validate_file(generation_complete_flag): self.logging_state_info('meta build with required image build is available at: ' + meta_path_val) self.logging_state_info('meta build generation is skipped') logger.debug('meta build path: ' + meta_path_val) logger.debug('image build path: ' + image_path_val) else: """ cmd = ['python', REGENERATE_CMD_TZ + image_path_val] cwd = c_path.join(meta_path_val, BUILD_SCRIPTS_DIR) self.logging_state_info(getCurrentTime() + ' start meta build generation, please wait and do not interrupt ...') self.logging_state_info('Set current working directory: ' + cwd) self.logging_state_info('Generate Meta build command: ' + " ".join(cmd)) self.log = c_path.join(meta_path_val, REGENERATE_BUID_LOG) self.run = False self.retcode = self.execute(cmd, self.log, cwd, timer, interval) self.logging_state_info(getCurrentTime() +' meta build generation return code: ' + str(self.retcode)) self.logging_state_info('meta build generation log can be found at: ' + self.log) if self.retcode == 0: open(generation_complete_flag,'a').close() self.run = True self.logging_state_info(SECTION_BREAK) else: self.logging_state_info('skip meta build regeneration')
def getBuildIDfrompath(meta_build_path): """ Returns build ID from meta build path :param str meta_build_path: meta build path :returns: meta build ID :rtype: str """ # meta build path validation path_val = c_path.normalize(meta_build_path) if not c_path.validate_dir(path_val): raise RuntimeError('Cannot access: ' + path_val) # get build id from build_path as it is the directory name in dest build_id = os.path.basename(path_val) return build_id
def config_paths(self): """(list[tuple(str)]) List of the config paths found in the workspace conforming to the naming structure. """ config_dir = self.config_dir config_paths = [] logger.debug('Searching config path sets in dir: ' + config_dir) for entry in os.listdir(config_dir): path = c_path.join(config_dir, entry) if c_path.validate_dir(path): oem, qc, ui, user = self._get_config_paths(path) if oem or qc or ui or user: config_paths.append((oem, qc, ui, user)) else: logger.debug2('Skipping dir: ' + entry + '\n' ' ' + 'Does not contain any configs') else: logger.debug2('Skipping file in first level: ' + entry) logger.debug('Config paths found from the config dir: ' + str(config_paths)) return config_paths
def config_paths(self): """(list[tuple(str)]) List of the config paths found in the workspace conforming to the naming structure. """ config_dir = self.config_dir config_paths = [] logger.debug('Searching config path sets in dir: ' + config_dir) for entry in os.listdir(config_dir): path = c_path.join(config_dir, entry) if c_path.validate_dir(path): config = self._get_config_path(path) if config: config_paths.append(config) else: logger.debug2('Skipping dir: ' + entry + '\n' ' ' + 'Does not contain any configs') else: logger.debug2('Skipping file in first level: ' + entry) logger.debug('Config paths found from the config dir: ' + str(config_paths)) return config_paths
def c_validate(self): """Validates the command line args provided by the user. :raises: RuntimeError if any error occurs. """ args = self.parsed_args err = [] # Check if the meta build supports sign id meta_supports_sign_id = False if args.meta_build: meta_supports_sign_id = SecImageCore.meta_supports_sign_id( args.meta_build) # Check the input files if ((args.image_file and args.meta_build) or (not args.image_file and not args.meta_build)): err.append( 'Provide either image_file or a meta_build for processing.') # Check that --override flag is not given without help flag if args.overrides and not args.help: err.append( '-h flag must accompany --overrides flag to view overridable properties' ) # Check the configuration option and output dir if args.image_file or (args.meta_build and not meta_supports_sign_id): if ((args.chipset and args.config_path) or (not args.chipset and not args.config_path)): err.append( 'Provide either chipset or a config_path to process images.' ) if not args.output_dir: err.append('Provide the output_dir for storing the output.') elif args.meta_build and not meta_supports_sign_id: if not args.output_dir and not args.mini_build: err.append( 'Provide either output_dir or mini_build for storing the output.' ) # Check the operations if not (args.integrity_check or args.sign or args.encrypt or args.decrypt or args.validate or args.verify_inputs): err.append('Specify one or more operations to perform.') # Check and sanitize any paths for read access for path in ['image_file', 'config_path']: path_val = getattr(args, path, None) if path_val: path_val = c_path.normalize(path_val) if not c_path.validate_file(path_val): err.append('Cannot access ' + path + ' at: ' + path_val) setattr(args, path, path_val) # Check and sanitize any paths for read dir access for path in ['meta_build']: path_val = getattr(args, path, None) if path_val: path_val = c_path.normalize(path_val) if not c_path.validate_dir(path_val): err.append('Cannot access ' + path + ' at: ' + path_val) setattr(args, path, path_val) # Check and sanitize paths for write access for path in ['output_dir', 'mini_build']: path_val = getattr(args, path, None) if path_val: path_val = c_path.normalize(path_val) try: c_path.create_dir(path_val) except Exception as e: err.append('Cannot write at: ' + path_val + '\n' ' ' + 'Error: ' + str(e)) setattr(args, path, path_val) # Raise error if any if err: if len(err) > 1: err = [(' ' + str(idx + 1) + '. ' + error) for idx, error in enumerate(err)] err = 'Please check the command line args:\n\n' + '\n'.join( err) else: err = err[0] raise RuntimeError(err)
def c_validate(self): """Validates the command line args provided by the user. :raises: RuntimeError if any error occurs. """ args = self.parsed_args err = [] # Check the input files if ((args.image_file and args.meta_build) or (not args.image_file and not args.meta_build)): err.append( 'Provide either image_file or a meta_build for processing.') # Check that m_image_file and meta_build are not both provided if args.meta_build and args.m_image_file: err.append('--m_image_file cannot be provided with meta_build.') err.append('Provide --m_gen flag if ' + multi_image_string() + ' file generation is desired.') # Check that m_gen and m_image_file are not both provided if args.m_gen and args.m_image_file: err.append('Provide either --m_image_file or --m_gen.') # Check that --override flag is not given without help flag if args.overrides and not args.help: err.append( '-h flag must accompany --overrides flag to view overridable properties' ) # Check if the meta build supports sign id meta_supports_sign_id = False if args.meta_build: meta_supports_sign_id = SecImageCore.meta_supports_sign_id( args.meta_build) # Check the configuration option and output dir if args.image_file or (args.meta_build and not meta_supports_sign_id): if ((args.chipset and args.config_path) or (not args.chipset and not args.config_path)): err.append( 'Provide either chipset or a config_path to process images.' ) if not args.output_dir: err.append('Provide the output_dir for storing the output.') elif args.meta_build and not meta_supports_sign_id: if not args.output_dir and not args.mini_build: err.append( 'Provide either output_dir or mini_build for storing the output.' ) if not (args.integrity_check or args.sign or args.encrypt or args.decrypt or args.validate or args.verify_inputs or args.no_op): err.append('Specify one or more operations to perform.') # Check that multi-image operations are enabled when m_gen or m_image_file are provided if args.m_image_file and not (args.m_integrity_check or args.m_sign or args.m_encrypt or args.m_decrypt or args.m_validate): err.append('Specify one or more ' + multi_image_string() + ' image operations to perform.') if args.m_gen and not (args.m_integrity_check or args.m_sign or args.m_encrypt): err.append('Specify one or more ' + multi_image_string() + ' image operations to perform.') # Check that multi-image operations are not enabled when m_gen and m_image_file are missing if not (args.m_gen or args.m_image_file) and ( args.m_integrity_check or args.m_sign or args.m_encrypt or args.m_decrypt or args.m_validate): err.append( 'Provide either --m_image_file or --m_gen when performing ' + multi_image_string() + ' image operations.') # Check that no_op operation is only enabled when m_gen or m_image_file are provided if args.no_op and not (args.m_gen or args.m_image_file): err.append( 'Provide either --m_image_file or --m_gen when adding image entry to ' + multi_image_string() + ' image.') # Check that no_op operation is not provided with any other individual image operations if args.no_op and (args.integrity_check or args.sign or args.encrypt or args.decrypt or args.validate): err.append( 'no_op operation cannot be performed alongside other image operations' ) # Check sign_attr is only set when adding hash table if args.sign_attr and not (args.integrity_check or args.sign): err.append( 'sign_attr operation can only be performed when integrity_check or sign are being performed.' ) # Check m_sign_attr is only set when adding hash table if args.m_sign_attr and not (args.m_integrity_check or args.m_sign): err.append( 'm_sign_attr operation can only be performed when m_integrity_check or m_sign are being performed.' ) # Check other options: if args.rch and not args.validate: err.append( 'Root Cert Hash can only be given when "--validate" operation is provided.' ) # Check and sanitize any paths for read access for path in ['image_file', 'config_path']: path_val = getattr(args, path, None) if path_val: path_val = c_path.normalize(path_val) if not c_path.validate_file(path_val): err.append('Cannot access ' + path + ' at: ' + path_val) setattr(args, path, path_val) # Check and sanitize any paths for read dir access for path in ['meta_build']: path_val = getattr(args, path, None) if path_val: path_val = c_path.normalize(path_val) if not c_path.validate_dir(path_val): err.append('Cannot access ' + path + ' at: ' + path_val) setattr(args, path, path_val) # Check and sanitize paths for write access for path in ['output_dir', 'mini_build']: path_val = getattr(args, path, None) if path_val: path_val = c_path.normalize(path_val) try: c_path.create_dir(path_val) except Exception as e: err.append('Cannot write at: ' + path_val + '\n' ' ' + 'Error: ' + str(e)) setattr(args, path, path_val) # Raise error if any if err: if len(err) > 1: err = [(' ' + str(idx + 1) + '. ' + error) for idx, error in enumerate(err)] err = 'Please check the command line args:\n\n' + '\n'.join( err) else: err = err[0] raise RuntimeError(err)
def __init__(self, meta_build_path, config_dir_obj, parsegen_config, authority, sign_id_list=[], gen_multi_image=False, platform_binding=None): assert isinstance(meta_build_path, str) assert isinstance(config_dir_obj, ConfigDir) assert isinstance(parsegen_config, ParsegenCfgParser) # Initialize the BaseStager super(MetaBuildStager, self).__init__(authority) self.config_dir_obj = config_dir_obj # Create internal attributes self._meta_build_path = meta_build_path # Validate that the meta_build path exists meta_build_path = c_path.normalize(meta_build_path) if not c_path.validate_dir(meta_build_path): raise RuntimeError('No read access to the meta build path: ' + meta_build_path) # Get the meta lib module from the metabuild meta_info = MetaBuild.getMetainfo(meta_build_path) # List of sign ids searched sign_ids_searched = [] # Create the image info list based on the meta data for sign_id, chipset, image_src_path, image_dest_path, err_code in self.get_image_info_from_meta(meta_info): # Filter on the sign id if sign_id_list and sign_id not in sign_id_list: continue # Update internal variables sign_ids_searched.append(sign_id) self.images_status[sign_id] = { 'errcode' : err_code, 'path' : image_src_path.image_path if image_src_path is not None else None, } # If there is an error, continue if err_code != MetaError.SUCCESS: continue try: # Put the image info object into the list img_config_parser = self.get_image_config_parser(chipset) imageinfo = self._create_imageinfo( img_config_parser, parsegen_config, sign_id, "", gen_multi_image=False, src_image=image_src_path, dest_image=image_dest_path, platform_binding=platform_binding) self._image_info_list.append(imageinfo) except Exception as e: logger.error(str(e)) continue # Create image info object for to-be-created Multi-Image Signing and Integrity image if gen_multi_image: if chipset in self._multi_image_imageinfo_dict: logger.debug("Multi-image imageinfo already exists for chipset " + chipset) continue logger.debug("Create multi-image imageinfo object for chipset " + chipset) # Set sign id to Multi-Image Sign & Integrity image's sign id sign_id = MULTI_IMAGE_SIGN_ID[authority] # Set the Multi-Image Signing & Integrity image's imageinfo self._multi_image_imageinfo_dict[chipset] = self._create_imageinfo( img_config_parser, parsegen_config, sign_id, None, gen_multi_image=True, platform_binding=platform_binding) if sign_id_list and set(sign_id_list) != set(sign_ids_searched): raise RuntimeError('Unknown sign id provided: ' + ', '.join(set(sign_id_list) - set(sign_ids_searched))) if not self._image_info_list: raise RuntimeError('No images found from the meta build.')
def __init__(self, meta_build_path, config_dir_obj, sign_id_list=[]): assert isinstance(meta_build_path, str) assert isinstance(config_dir_obj, ConfigDir) # Initialize the BaseStager BaseStager.__init__(self) self.config_dir_obj = config_dir_obj # Create internal attributes self._meta_build_path = meta_build_path # Validate that the meta_build path exists meta_build_path = c_path.normalize(meta_build_path) if not c_path.validate_dir(meta_build_path): raise RuntimeError('No read access to the meta build path: ' + meta_build_path) # Get the meta lib module from the metabuild meta_info = self.get_meta_info(meta_build_path) # Create the image info list based on the meta data for sign_id, chipset, image_src_path, image_dest_path in self.get_image_info_from_meta(meta_info): # Filer on the sign id if sign_id_list: if sign_id not in sign_id_list: continue try: img_config_parser = self.get_image_config_parser(chipset) # Validate the sign_id sign_id = self._get_sign_id(img_config_parser, os.path.basename(image_src_path.image_path), sign_id) # Get the config block for the sign id img_config_block = img_config_parser.get_config_for_sign_id(sign_id) # Create the one image info object image_info = ImageInfo('', sign_id, img_config_block, img_config_parser) # Set the src path image_info.src_image = image_src_path image_info.image_under_operation = image_info.src_image.image_path # Set the dest path image_info.dest_image = image_dest_path # Check if the dest image name should be overriden if img_config_block.output_file_name is not None: image_info.dest_image.image_name = img_config_block.output_file_name # Put the image info object into the list self._image_info_list.append(image_info) except Exception as e: logger.error(str(e)) if not self._image_info_list: raise RuntimeError('No images found from the meta build.')
def __init__(self, meta_build_path, config_dir_obj, parsegen_config, authority, sign_id_list=[]): from sectools.features.isc.parsegen.config.parser import ParsegenCfgParser assert isinstance(meta_build_path, str) assert isinstance(config_dir_obj, ConfigDir) assert isinstance(parsegen_config, ParsegenCfgParser) # Initialize the BaseStager BaseStager.__init__(self, authority) self.config_dir_obj = config_dir_obj # Create internal attributes self._meta_build_path = meta_build_path # Validate that the meta_build path exists meta_build_path = c_path.normalize(meta_build_path) if not c_path.validate_dir(meta_build_path): raise RuntimeError('No read access to the meta build path: ' + meta_build_path) # Get the meta lib module from the metabuild meta_info = self.get_meta_info(meta_build_path) # List of sign ids searched sign_ids_searched = [] # Create the image info list based on the meta data for sign_id, chipset, image_src_path, image_dest_path, err_code in self.get_image_info_from_meta( meta_info): # Filter on the sign id if sign_id_list and sign_id not in sign_id_list: continue # Update internal variables sign_ids_searched.append(sign_id) self.images_status[sign_id] = { 'errcode': err_code, 'path': image_src_path.image_path if image_src_path is not None else None, } # If there is an error, continue if err_code != MetaError.SUCCESS: continue try: # Put the image info object into the list img_config_parser = self.get_image_config_parser(chipset) imageinfo = self._create_imageinfo(img_config_parser, parsegen_config, sign_id, "", image_src_path, image_dest_path) self._image_info_list.append(imageinfo) except Exception as e: logger.error(str(e)) if sign_id_list and set(sign_id_list) != set(sign_ids_searched): raise RuntimeError( 'Unknown sign id provided: ' + ', '.join(set(sign_id_list) - set(sign_ids_searched))) if not self._image_info_list: raise RuntimeError('No images found from the meta build.')
def __init__(self, meta_build_path, config_dir_obj, parsegen_config, sign_id_list=[]): from sectools.features.isc.parsegen.config.parser import ParsegenCfgParser assert isinstance(meta_build_path, str) assert isinstance(config_dir_obj, ConfigDir) assert isinstance(parsegen_config, ParsegenCfgParser) # Initialize the BaseStager BaseStager.__init__(self) self.config_dir_obj = config_dir_obj # Create internal attributes self._meta_build_path = meta_build_path # Validate that the meta_build path exists meta_build_path = c_path.normalize(meta_build_path) if not c_path.validate_dir(meta_build_path): raise RuntimeError('No read access to the meta build path: ' + meta_build_path) # Get the meta lib module from the metabuild meta_info = self.get_meta_info(meta_build_path) # List of sign ids searched sign_ids_searched = [] # Create the image info list based on the meta data for sign_id, chipset, image_src_path, image_dest_path, err_code in self.get_image_info_from_meta( meta_info): # Filer on the sign id if sign_id_list and sign_id not in sign_id_list: continue else: sign_ids_searched.append(sign_id) # If there is an error, continue if err_code is not None: continue try: img_config_parser = self.get_image_config_parser(chipset) # Validate the sign_id sign_id = self._get_sign_id( img_config_parser, os.path.basename(image_src_path.image_path), sign_id) # Get the config block for the sign id img_config_block = img_config_parser.get_config_for_sign_id( sign_id) # Create the one image info object image_info = ImageInfo('', sign_id, img_config_block, img_config_parser, parsegen_config) # Set the src path image_info.src_image = image_src_path image_info.image_under_operation = image_info.src_image.image_path # Set the dest path image_info.dest_image = image_dest_path # Check if the dest image name should be overriden if img_config_block.output_file_name is not None: image_info.dest_image.image_name = img_config_block.output_file_name # Put the image info object into the list self._image_info_list.append(image_info) except Exception as e: logger.error(str(e)) if sign_id_list and set(sign_id_list) != set(sign_ids_searched): raise RuntimeError( 'Unknown sign id provided: ' + ', '.join(set(sign_id_list) - set(sign_ids_searched))) if not self._image_info_list: raise RuntimeError('No images found from the meta build.')
def c_validate(self): """Validates the command line args provided by the user. :raises: RuntimeError if any error occurs. """ args = self.parsed_args err = [] config_params_32bits = { "tcg min": args.tcg_min, "tcg max": args.tcg_max, 'testsig': args.testsig, "tcg fix": args.tcg_fix, } #import pdb; pdb.set_trace() if (args.input_dir or args.image_file) and args.testsig: err.append( 'Generate testsig (-t) and sign with image_file (-i or -r) cannot be used together' ) if args.capability and (args.cass is False): err.append( 'Capability (-p) is only supported when CASS (-c) is used') if not (args.image_file or args.input_dir) and not args.testsig: err.append( 'Either generate testsig (-t) or sign with image_file (-i or -r) must be specified' ) if args.validate and (args.testsig or args.input_dir): err.append( 'Validate (-a) should be used with image_file (-i). An input signed image should be referenced by -i.' ) if args.validate is False and args.image_file: path, filename = os.path.split(args.image_file) if filename.startswith(TESTSIG_PREFIX): err.append( 'Cannot sign testsig file {0}. Please use -t to generate testsig instead.' .format(args.image_file)) if args.tcg_fix: for key in ["tcg min", "tcg max"]: if config_params_32bits[key]: err.append( "{0} should not be specified when tcg_fix is specified" .format(key)) for key in config_params_32bits: if Attribute.validate(num_bits=32, string=config_params_32bits[key]) is False: err.append('{0}:{1} is not a valid 32 bit integer'.format( key, config_params_32bits[key])) # Check and sanitize any paths for read access for path in ['image_file', 'config']: path_val = getattr(args, path, None) if path_val: path_val = c_path.normalize(path_val) if not c_path.validate_file(path_val): err.append('Cannot access ' + path + ' at: ' + path_val) setattr(args, path, path_val) for path in ['input_dir']: path_val = getattr(args, path, None) if path_val: path_val = c_path.normalize(path_val) if not c_path.validate_dir(path_val): err.append('Cannot access ' + path + ' at: ' + path_val) setattr(args, path, path_val) # Check and sanitize paths for write access for path in ['output_dir']: path_val = getattr(args, path, None) if path_val: path_val = c_path.normalize(path_val) try: c_path.create_dir(path_val) except Exception as e: err.append('Cannot write at: ' + path_val + '\n' ' ' + 'Error: ' + str(e)) setattr(args, path, path_val) # Raise error if any if err: if len(err) > 1: err = [(' ' + str(idx + 1) + '. ' + error) for idx, error in enumerate(err)] err = 'Please check the command line args:\n\n' + '\n'.join( err) else: err = err[0] raise RuntimeError(err)