Exemple #1
0
def get_projects_from_workspace(workspace_file):
    """
    Given a workspace file (x2w) will return the 
    Path to the apps0, main project and kymera_audio
    projects contained within
    """
    project_dict = {}
    workspace_name = os.path.basename(workspace_file)
    main_proj_name, dont_care = os.path.splitext(workspace_name)
    main_proj_name = main_proj_name + ".x2p"
    ws_projects = Workspace(workspace_file).parse()
    for child in ws_projects.keys():
        project = ws_projects[child].filename
        if "apps0_firmware.x2p" in project:
            project_dict["apps0"] = project
        if "audio_firmware.x2p" in project:
            project_dict["audio_image"] = project
        if "kymera_audio.x2p" in project:
            project_dict["audio_package"] = project
        if main_proj_name in project:
            project_dict["apps1"] = project
    return project_dict
def main(args):
    UISTATE_LOCATION_SELECTION = 0
    UISTATE_RESPONSE_SELECTION = 1
    UISTATE_PROCEED = 2
    UISTATE_EXIT = -1
    uistate = UISTATE_LOCATION_SELECTION

    parsed_args = parse_args(args)

    # Display whatever arguments have been given
    print("devkit root: %s" % (parsed_args.devkit_root))
    print("workspace: %s" % (parsed_args.workspace))
    if (parsed_args.nowstring != None):
        print("nowstring: %s" % (parsed_args.nowstring))
    if (parsed_args.response != None):
        print("response: %s" % (parsed_args.response))
    if parsed_args.folder_for_rsa_files != None:
        print("folder_for_rsa_files: %s" % (parsed_args.folder_for_rsa_files))
    sys.stdout.flush()

    # Add required paths to sys.path if not there already
    path = os.path.join(parsed_args.devkit_root, "tools", "ubuild")
    if not path in sys.path:
        sys.path.append(path)

    # Set up the use of build.py main
    from maker.build import build_configs as build_configs
    build_runner = BuildRunner(parsed_args.devkit_root, build_configs)

    if (parsed_args.nowstring != None):
        # The user has provided their own folder name
        nowstring = parsed_args.nowstring
    else:
        nowstring = datetime.strftime(datetime.now(), '%Y%m%d%H%M%S')

    if parsed_args.folder_for_rsa_files == None:
        # The -f option has not been given so use the default location
        # Present the UI to the user to confirm or change that location
        outpath = os.path.join(os.path.dirname(parsed_args.workspace), "dfu")
    else:
        # The -f option has been given so use that location
        outpath = os.path.abspath(parsed_args.folder_for_rsa_files)
        uistate = UISTATE_RESPONSE_SELECTION

    returnValue = 3
    if (parsed_args.response != None):
        # The user has provided a response on the command line
        # to avoid having to present a UI, for test automation
        response = str.lower(parsed_args.response)
        if response == "use":
            returnValue = 1
        elif response == "replace":
            returnValue = 2
        else:
            print("Invalid -r option {}".format(parsed_args.response))
            print('Valid options are "Use" or "Replace"')
            sys.stdout.flush()
            return False

        if uistate is UISTATE_RESPONSE_SELECTION:
            uistate = UISTATE_PROCEED

    sys.stdout.flush()

    tlh = None
    if uistate is UISTATE_LOCATION_SELECTION or \
    uistate is UISTATE_RESPONSE_SELECTION:
        tlh = TCL_LIBRARY_handler(parsed_args.devkit_root)
        top = Tkinter.Tk()

    private_pem_file = os.path.join(outpath, "private.pem")
    rsa_pss_constants_c_file = os.path.join(outpath, "rsa_pss_constants.c")

    while uistate != UISTATE_EXIT and uistate != UISTATE_PROCEED:
        if uistate is UISTATE_LOCATION_SELECTION:
            if not os.path.isdir(outpath):
                try:
                    os.makedirs(outpath)
                    print("Created folder %s" % outpath)
                    sys.stdout.flush()
                    returnValue = 3
                except (OSError, IOError) as exception:
                    print("Unable to create path {}; error {}. Exit!\n".format(
                        outpath, exception.errno))
                    sys.stdout.flush()
                    return False
            newpath = askdirectory(top, outpath)
            if newpath is "":
                # The directory selection has been cancelled
                # Cancel is exit
                print("Cancelled\n")
                sys.stdout.flush()
                return False

            if not os.path.isdir(newpath):
                try:
                    os.makedirs(newpath)
                    print("Created folder %s" % newpath)
                    sys.stdout.flush()
                    returnValue = 3
                except (OSError, IOError) as exception:
                    print("Unable to create path {}; error {}. Exit!\n".format(
                        newpath, exception.errno))
                    sys.stdout.flush()
                    return False

            outpath = newpath
            sys.stdout.flush()
            private_pem_file = os.path.join(outpath, "private.pem")
            rsa_pss_constants_c_file = os.path.join(outpath,
                                                    "rsa_pss_constants.c")

            if (parsed_args.response is None):
                uistate = UISTATE_RESPONSE_SELECTION
            else:
                uistate = UISTATE_PROCEED

        elif uistate is UISTATE_RESPONSE_SELECTION:
            if os.path.isfile(private_pem_file) and \
                os.path.isfile(rsa_pss_constants_c_file):
                # There are existing files to use or replace.
                # The above is the minimum set.
                # Ask the user what to do via a dialog
                bb = show_button_box(top, outpath)
                returnValue = 0
                while returnValue is 0:
                    returnValue = bb.returnValue()
                if returnValue == -1:
                    # Cancelling
                    if parsed_args.folder_for_rsa_files == None:
                        # Back to location selection UI
                        uistate = UISTATE_LOCATION_SELECTION
                    else:
                        # Folder given so no location  selectio UI
                        # Cancel is exit
                        print("Cancelled\n")
                        sys.stdout.flush()
                        return False
                else:
                    uistate = UISTATE_PROCEED
            else:
                returnValue = 3
                uistate = UISTATE_PROCEED

    if tlh is not None:
        tlh.close()

    if not os.path.isdir(outpath):
        try:
            os.makedirs(outpath)
            print("Created folder %s" % outpath)
            returnValue = 3
        except (OSError, IOError) as exception:
            print("Unable to create path {}; error {}. Exit!\n".format(
                outpath, exception.errno))
            return False

    # Set up the file specs for the files to of interest for archive/create
    filelist = []
    private_pem_file = os.path.join(outpath, "private.pem")
    filelist.append(private_pem_file)
    public_pem_file = os.path.join(outpath, "public.pem")
    filelist.append(public_pem_file)
    dfu_private_key_file = os.path.join(outpath, "dfu-private.key")
    filelist.append(dfu_private_key_file)
    dfu_public_key_file = os.path.join(outpath, "dfu-public.key")
    filelist.append(dfu_public_key_file)
    rsa_pss_constants_c_file = os.path.join(outpath, "rsa_pss_constants.c")
    filelist.append(rsa_pss_constants_c_file)

    # At this point the returnValue should be:
    # 1 to use (known to already exist),
    # 2 to replace (known to already exist), or
    # 3 to create

    if returnValue >= 2:
        # If we are to replace or create we need SecurityCmd.exe,
        # python.exe and gen_rsa_pss_constants.py
        scexe = os.path.join(parsed_args.devkit_root, "tools", "bin",
                             "SecurityCmd.exe")
        if not os.path.isfile(scexe):
            print("{} does not exist\n".format(scexe))
            print("Exiting!\n")
            sys.stdout.flush()
            return False
        python_exe = os.path.join(parsed_args.devkit_root, 'tools', 'python27',
                                  'python.exe')
        if not os.path.isfile(python_exe):
            print("{} does not exist\n".format(python_exe))
            print("Exiting!\n")
            sys.stdout.flush()
            return False
        gen_rsa_pss_constants_py = os.path.join(parsed_args.devkit_root,
                                                'tools',
                                                'gen_rsa_pss_constants.py')
        if not os.path.isfile(gen_rsa_pss_constants_py):
            print("{} does not exist\n".format(gen_rsa_pss_constants_py))
            print("Exiting!\n")
            sys.stdout.flush()
            return False

    if returnValue == 2:
        # Going to replace so archive what we already have
        zip_filename = nowstring + ".zip"
        zip_filespec = os.path.join(outpath, zip_filename)
        # Create the archive for writing "deflated" (compressed) files to
        try:
            with zipfile.ZipFile(zip_filespec,
                                 mode="w",
                                 compression=zipfile.ZIP_DEFLATED) as zip:
                for listfile in filelist:
                    if os.path.isfile(listfile):
                        print("Adding {} to archive {}".format(
                            listfile, zip_filespec))
                        zip.write(listfile, os.path.basename(listfile))
        except (OSError, IOError) as exception:
            print("Error with zip file {}; error {}, {}\n" \
                .format(zip_filespec, exception.errno,
                    os.strerror(exception.errno)))
            print("Exiting!\n")
            sys.stdout.flush()
            return False

        try:
            # Having archived all the files without an error, delete them
            for listfile in filelist:
                # Ensure the file is not read-only before trying to delete it
                os.chmod(listfile, stat.S_IWRITE)
                os.remove(listfile)
                print("Deleted {}".format(listfile))
        except (OSError, IOError) as exception:
            print("Error deleting file; error {}, {}\n" \
                .format(exception.errno, os.strerror(exception.errno)))
            restore_archive(nowstring, outpath, filelist)
            print("Exiting!\n")
            sys.stdout.flush()
            return False

        sys.stdout.flush()
        # Having archived and deleted the original files, now as for create
        returnValue = 3

    if returnValue == 3:
        # Create the required files
        cmd_line = [scexe, "-product", "hyd", "creatersakey", "2048", "F4", \
            private_pem_file, public_pem_file]
        print("Invoking '%s'" % " ".join(cmd_line))
        sys.stdout.flush()
        result = subprocess.call(cmd_line)
        if result != 0:
            print("'%s' failed" % " ".join(cmd_line))
            restore_archive(nowstring, outpath, filelist)
            print("Exiting!\n")
            sys.stdout.flush()
            return False
        if not os.path.isfile(private_pem_file):
            print("Failed to create '%s'" % private_pem_file)
            restore_archive(nowstring, outpath, filelist)
            print("Exiting!\n")
            sys.stdout.flush()
            return False
        if not os.path.isfile(public_pem_file):
            print("Failed to create '%s'" % public_pem_file)
            restore_archive(nowstring, outpath, filelist)
            print("Exiting!\n")
            sys.stdout.flush()
            return False

        print("'%s' created" % private_pem_file)
        print("'%s' created" % public_pem_file)

        cmd_line = [scexe, "-product", "hyd", "pem2dfukey", "prv", \
            private_pem_file, dfu_private_key_file]
        print("Invoking '%s'" % " ".join(cmd_line))
        sys.stdout.flush()
        result = subprocess.call(cmd_line)

        # We don't care whether that failed or not as the dfu_private_key_file
        # is not used for any other processing

        if os.path.isfile(dfu_private_key_file):
            print("'%s' created" % dfu_private_key_file)

        cmd_line = [scexe, "-product", "hyd", "pem2dfukey", "pub", \
            public_pem_file, dfu_public_key_file]
        print("Invoking '%s'" % " ".join(cmd_line))
        sys.stdout.flush()
        result = subprocess.call(cmd_line)
        if result != 0:
            print("'%s' failed" % " ".join(cmd_line))
            restore_archive(nowstring, outpath, filelist)
            print("Exiting!\n")
            sys.stdout.flush()
            return False
        if not os.path.isfile(dfu_public_key_file):
            print("Failed to create '%s'" % dfu_public_key_file)
            restore_archive(nowstring, outpath, filelist)
            print("Exiting!\n")
            sys.stdout.flush()
            return False

        print("'%s' created" % dfu_public_key_file)

        cmd_line = [python_exe, gen_rsa_pss_constants_py, "-i", \
            dfu_public_key_file]
        print("Invoking '%s'" % " ".join(cmd_line))
        sys.stdout.flush()
        result = subprocess.call(cmd_line)
        if result != 0:
            print("'%s' failed" % " ".join(cmd_line))
            restore_archive(nowstring, outpath, filelist)
            print("Exiting!\n")
            sys.stdout.flush()
            return False
        if not os.path.isfile(rsa_pss_constants_c_file):
            print("Failed to create '%s'" % rsa_pss_constants_c_file)
            restore_archive(nowstring, outpath, filelist)
            print("Exiting!\n")
            sys.stdout.flush()
            return False

        print("'%s' created" % rsa_pss_constants_c_file)

    # All the required files are now in place
    # Find the rsa_pss_constants.c in the workspace and replace it
    ws_projects = Workspace(parsed_args.workspace).parse()
    for project in ws_projects.keys():
        result = process_project(build_runner, parsed_args,
                                 ws_projects[project].filename,
                                 rsa_pss_constants_c_file, nowstring)
        if result < 0:
            # An error has occured
            restore_archive(nowstring, outpath, filelist)
            sys.stdout.flush()
            return False
        elif result > 0:
            print("\nPlease rebuild library project %s and your application" \
                % ws_projects[project].filename)
            sys.stdout.flush()
            break

    if result == 0:
        print("\nUnable to find {} in any of the projects".format(
            rsa_pss_constants_c_file))
        sys.stdout.flush()
        return False

    sys.stdout.flush()
    return True
def zip_it(root_dir, workspace, out_dir, base_name):
    """ Archive the xcd file and any elf and lst files found below the root_dir
        - the root directory of the devkit
        - the output directory containing the xcd and log files, and to contain
            the zip file containing those and any elf and lst files found
        - the base string used for the name of the xcd, log and zip files
    """
    zip_filename = base_name + ".zip"
    zip_filespec = os.path.join(out_dir, zip_filename)
    # Create the archive for writing "deflated" (compressed) files to
    try:
        with zipfile.ZipFile(zip_filespec,
                             mode="w",
                             compression=zipfile.ZIP_DEFLATED) as zip:
            # So put the xcd file in it...
            xcd_arcname = base_name + ".xcd"
            xcd_filespec = os.path.join(out_dir, xcd_arcname)
            assert os.path.isfile(xcd_filespec)
            print("Adding {} to archive {}\n".format(xcd_arcname,
                                                     zip_filespec))
            zip.write(xcd_filespec, xcd_arcname)
            # ... and put the log file in it ...
            log_arcname = base_name + ".log"
            log_filespec = os.path.join(out_dir, log_arcname)
            if os.path.isfile(log_filespec):
                print("Adding {} to archive {}\n".format(
                    log_arcname, zip_filespec))
                zip.write(log_filespec, log_arcname)
            else:
                print("{} not found\n".format(log_filespec))
            # ... and put any *.elf/*.lst files found in the workspace in it
            print(
                "Looking in {} project locations for *.elf and *.lst files\n".
                format(workspace))
            sys.stdout.flush()
            ws_projects = Workspace(workspace).parse()
            for proj in ws_projects.keys():
                project = ws_projects[proj].filename
                import maker.parse_proj_file as pproj
                proj_parser = pproj.Project(project, root_dir, workspace)
                print("Processing project %s\n" % project)
                elffile, lstfile = process_project(project, proj_parser)

                if elffile is not None:
                    _, elffilename = os.path.split(elffile)
                    print("Adding %s to archive %s\n" %
                          (elffile, zip_filespec))
                    sys.stdout.flush()
                    zip.write(elffile, elffilename)
                    if lstfile is not None:
                        _, lstfilename = os.path.split(lstfile)
                        print("Adding %s to archive %s\n" %
                              (lstfile, zip_filespec))
                        sys.stdout.flush()
                        zip.write(lstfile, lstfilename)
                else:
                    print("No elf file found for this project\n")

            print("Please send the {} file to your".format(zip_filespec))
            print(
                "Qualcomm Technologies International, Ltd. representative.\n")
    except OSError as exception:
        print("Error with zip file {} failed; error {}, {}\n" \
            .format(zip_filespec, exception.errno, os.strerror(exception.errno)))

    sys.stdout.flush()
def main(args):

    DEFAULT_KEY_FOLDER_NAME = "peer_pair_key"
    KEY_C_FILE_NAME = "peer_pair_le_key.c"

    UISTATE_LOCATION_SELECTION = 0
    UISTATE_RESPONSE_SELECTION = 1
    UISTATE_PROCEED = 2
    UISTATE_EXIT = -1
    uistate = UISTATE_LOCATION_SELECTION

    parsed_args = parse_args(args)

    # Display whatever arguments have been given
    print("devkit root: %s" % (parsed_args.devkit_root))
    print("workspace: %s" % (parsed_args.workspace))
    if (parsed_args.nowstring != None):
        print("nowstring: %s" % (parsed_args.nowstring))
    if (parsed_args.response != None):
        print("response: %s" % (parsed_args.response))
    if parsed_args.folder_for_key_files != None:
        print("folder_for_key_files: %s" % (parsed_args.folder_for_key_files))
    sys.stdout.flush()

    # Add required paths to sys.path if not there already
    path = os.path.join(parsed_args.devkit_root, "tools", "ubuild")
    if not path in sys.path:
        sys.path.append(path)

    # Set up the use of build.py main
    from maker.build import build_configs as build_configs
    build_runner = BuildRunner(parsed_args.devkit_root, build_configs)

    if (parsed_args.nowstring != None):
        # The user has provided their own folder name
        nowstring = parsed_args.nowstring
    else:
        nowstring = datetime.strftime(datetime.now(), '%Y%m%d%H%M%S')

    if parsed_args.folder_for_key_files == None:
        # The -f option has not been given so use the default location
        # Present the UI to the user to confirm or change that location
        outpath = os.path.join(os.path.dirname(parsed_args.workspace),
                               DEFAULT_KEY_FOLDER_NAME)
    else:
        # The -f option has been given so use that location
        outpath = os.path.abspath(parsed_args.folder_for_key_files)
        uistate = UISTATE_RESPONSE_SELECTION

    returnValue = 3
    if (parsed_args.response != None):
        # The user has provided a response on the command line
        # to avoid having to present a UI, for test automation
        response = str.lower(parsed_args.response)
        if response == "use":
            returnValue = 1
        elif response == "replace":
            returnValue = 2
        else:
            print("Invalid -r option {}".format(parsed_args.response))
            print('Valid options are "Use" or "Replace"')
            sys.stdout.flush()
            return False

        if uistate is UISTATE_RESPONSE_SELECTION:
            uistate = UISTATE_PROCEED

    sys.stdout.flush()

    tlh = None
    if uistate is UISTATE_LOCATION_SELECTION or \
    uistate is UISTATE_RESPONSE_SELECTION:
        tlh = TCL_LIBRARY_handler(parsed_args.devkit_root)
        top = Tkinter.Tk()

    while uistate != UISTATE_EXIT and uistate != UISTATE_PROCEED:
        if uistate is UISTATE_LOCATION_SELECTION:
            if not os.path.isdir(outpath):
                try:
                    os.makedirs(outpath)
                    print("Created folder %s" % outpath)
                    sys.stdout.flush()
                    returnValue = 3
                except (OSError, IOError) as exception:
                    print("Unable to create path {}; error {}. Exit!\n".format(
                        outpath, exception.errno))
                    sys.stdout.flush()
                    return False
            newpath = askdirectory(top, outpath)
            if newpath is "":
                # The directory selection has been cancelled
                # Cancel is exit
                print("Cancelled\n")
                sys.stdout.flush()
                return False

            if not os.path.isdir(newpath):
                try:
                    os.makedirs(newpath)
                    print("Created folder %s" % newpath)
                    sys.stdout.flush()
                    returnValue = 3
                except (OSError, IOError) as exception:
                    print("Unable to create path {}; error {}. Exit!\n".format(
                        newpath, exception.errno))
                    sys.stdout.flush()
                    return False

            outpath = newpath
            sys.stdout.flush()

            if (parsed_args.response is None):
                uistate = UISTATE_RESPONSE_SELECTION
            else:
                uistate = UISTATE_PROCEED

        elif uistate is UISTATE_RESPONSE_SELECTION:
            if os.path.isfile(os.path.join(outpath, KEY_C_FILE_NAME)):
                # There are existing files to use or replace.
                # The above is the minimum set.
                # Ask the user what to do via a dialog
                bb = show_button_box(top, outpath)
                returnValue = 0
                while returnValue is 0:
                    returnValue = bb.returnValue()
                if returnValue == -1:
                    # Cancelling
                    if parsed_args.folder_for_key_files == None:
                        # Back to location selection UI
                        uistate = UISTATE_LOCATION_SELECTION
                    else:
                        # Folder given so no location  selectio UI
                        # Cancel is exit
                        print("Cancelled\n")
                        sys.stdout.flush()
                        return False
                else:
                    uistate = UISTATE_PROCEED
            else:
                returnValue = 3
                uistate = UISTATE_PROCEED

    if tlh is not None:
        tlh.close()

    if not os.path.isdir(outpath):
        try:
            os.makedirs(outpath)
            print("Created folder %s" % outpath)
            returnValue = 3
        except (OSError, IOError) as exception:
            print("Unable to create path {}; error {}. Exit!\n".format(
                outpath, exception.errno))
            return False

    c_key_file = os.path.join(outpath, KEY_C_FILE_NAME)

    # Set up the file specs for the files to of interest for archive/create
    filelist = []
    filelist.append(c_key_file)

    # At this point the returnValue should be:
    # 1 to use (known to already exist),
    # 2 to replace (known to already exist), or
    # 3 to create

    if returnValue == 2:
        # Going to replace so archive what we already have
        zip_filename = nowstring + ".zip"
        zip_filespec = os.path.join(outpath, zip_filename)
        # Create the archive for writing "deflated" (compressed) files to
        try:
            with zipfile.ZipFile(zip_filespec,
                                 mode="w",
                                 compression=zipfile.ZIP_DEFLATED) as zip:
                for listfile in filelist:
                    if os.path.isfile(listfile):
                        print("Adding {} to archive {}".format(
                            listfile, zip_filespec))
                        zip.write(listfile, os.path.basename(listfile))
        except (OSError, IOError) as exception:
            print("Error with zip file {}; error {}, {}\n" \
                .format(zip_filespec, exception.errno,
                    os.strerror(exception.errno)))
            print("Exiting!\n")
            sys.stdout.flush()
            return False

        try:
            # Having archived all the files without an error, delete them
            for listfile in filelist:
                # Ensure the file is not read-only before trying to delete it
                os.chmod(listfile, stat.S_IWRITE)
                os.remove(listfile)
                print("Deleted {}".format(listfile))
        except (OSError, IOError) as exception:
            print("Error deleting file; error {}, {}\n" \
                .format(exception.errno, os.strerror(exception.errno)))
            restore_archive(nowstring, outpath, filelist)
            print("Exiting!\n")
            sys.stdout.flush()
            return False

        sys.stdout.flush()
        # Having archived and deleted the original files, now as for create
        returnValue = 3

    if returnValue >= 2:
        # Create the required c file
        create_key_c_source(c_key_file)
        print("'%s' created" % c_key_file)

    # Find the c file in the workspace and replace it
    ws_projects = Workspace(parsed_args.workspace).parse()
    for project in ws_projects.keys():
        result = process_project(build_runner, parsed_args,
                                 ws_projects[project].filename, c_key_file,
                                 nowstring)
        if result < 0:
            # An error has occured
            restore_archive(nowstring, outpath, filelist)
            sys.stdout.flush()
            return False
        elif result > 0:
            print("\nPlease rebuild your application which includes project %s" \
                % ws_projects[project].filename)
            sys.stdout.flush()
            break

    if result == 0:
        print("\nUnable to find {} in any of the projects".format(c_key_file))
        sys.stdout.flush()
        return False

    sys.stdout.flush()
    return True