Exemplo n.º 1
0
 def device(self):
     """The associated Device object."""
     if self._device:
         return self._device
     device = Device(self, addr='::1')
     device.configure()
     self._device = device
     return self._device
Exemplo n.º 2
0
 def __init__(self, app, count, lang="-l chi_sim+normal", cleanup=False):
     self.app = app
     self.count = count
     self.lang = lang
     self.cleanup = cleanup
     if not DEBUG:
         Device.init()
     self.device = Device.getDevice()
Exemplo n.º 3
0
    def test_ssh_config(self):
        device = Device(self.buildenv, '::1')
        self.assertFalse(device.ssh_config)

        with self.assertRaises(ValueError):
            device.ssh_config = 'no_such_config'
        ssh_config = 'ssh_config'
        self.host.touch(ssh_config)
        device.ssh_config = ssh_config
        self.assertEqual(['-F', ssh_config], device.ssh_opts())
Exemplo n.º 4
0
    def test_ssh_identity(self):
        device = Device(self.buildenv, '::1')
        self.assertFalse(device.ssh_identity)

        with self.assertRaises(ValueError):
            device.ssh_identity = 'no_such_identity'
        ssh_identity = 'ssh_identity'
        self.host.touch(ssh_identity)
        device.ssh_identity = ssh_identity
        self.assertEqual(['-i', ssh_identity], device.ssh_opts())
Exemplo n.º 5
0
 def test_configure(self):
     device = Device(self.buildenv, '::1')
     device.configure()
     self.assertEqual(
         device.ssh_config,
         self.buildenv.path(
             self.buildenv.build_dir, 'ssh-keys', 'ssh_config'))
     self.assertFalse(device.ssh_identity)
     self.assertFalse(device.ssh_options)
     self.assertFalse(device.ssh_verbosity)
Exemplo n.º 6
0
    def init(self, dma_id):
        if self._init_done:
            logging.warning("Already initialized! Skip init")
            return

        self.dma_id = dma_id
        self.dev = Device()
        self.dev.open_device()
        self.sdl = StreamDescList(self.dev)
        self.ipc = Ipc(self.dev)
        self._init_done = True
Exemplo n.º 7
0
    def test_ssh_option(self):
        device = Device(self.factory, addr='::1')
        self.assertEqual(device.ssh_options, [])

        device.ssh_options = ['StrictHostKeyChecking no']
        device.ssh_options.append('UserKnownHostsFile=/dev/null')
        self.assertEqual([
            '-o',
            'StrictHostKeyChecking no',
            '-o',
            'UserKnownHostsFile=/dev/null',
        ], device.ssh_opts())
Exemplo n.º 8
0
 def parse_devices(self):
     """Creates an array of Device objects from the channel"""
     devices = []
     for device in self._channel_dict["devices"]:
         devices.append(
             Device(device, self._is_sixteen_bit, self._ignore_list))
     return devices
Exemplo n.º 9
0
 def test_from_args(self):
     host = MockHost()
     parser = Args.make_parser('description', name_required=False)
     # netaddr should get called with 'just-four-random-words', and fail
     with self.assertRaises(RuntimeError):
         args = parser.parse_args(['--device', 'just-four-random-words'])
         device = Device.from_args(host, args)
Exemplo n.º 10
0
def main():
  parser = Args.make_parser(
      'Starts the named fuzzer.  Additional arguments are passed through.')
  args, fuzzer_args = parser.parse_known_args()

  host = Host()
  device = Device.from_args(host, args)
  fuzzer = Fuzzer.from_args(device, args)

  with Cipd.from_args(fuzzer, args) as cipd:
    if cipd.install():
      device.store(os.path.join(cipd.root, '*'), fuzzer.data_path('corpus'))

  print('\n****************************************************************')
  print(' Starting ' + str(fuzzer) + '.')
  print(' Outputs will be written to:')
  print('   ' + fuzzer.results())
  if not args.foreground:
    print(' You should be notified when the fuzzer stops.')
    print(' To check its progress, use `fx fuzz check ' + str(fuzzer) + '`.')
    print(' To stop it manually, use `fx fuzz stop ' + str(fuzzer) + '`.')
  print('****************************************************************\n')
  fuzzer.start(fuzzer_args)

  title = str(fuzzer) + ' has stopped.'
  body = 'Output written to ' + fuzzer.results() + '.'
  print(title)
  print(body)
  host.notify_user(title, body)
  return 0
Exemplo n.º 11
0
def main():
    parser = ArgParser('Lists corpus instances in CIPD for the named fuzzer')
    args = parser.parse_args()

    host = Host.from_build()
    device = Device.from_args(host, args)
    fuzzer = Fuzzer.from_args(device, args)

    with Corpus.from_args(fuzzer, args) as corpus:
        cipd = Cipd(corpus)
        print(cipd.instances())
    return 0
Exemplo n.º 12
0
def on_start_input(cmd: pcmd.Command, args: List[str], indi: int) -> None:
    """Callback for `start input` - adds an input device"""
    try:
        ch.add_ist(
            Device(pa,
                   format=pyaudio.paFloat32,
                   channels=1,
                   rate=params.SMPRATE,
                   input=True,
                   input_device_index=indi))
    except Exception as e:
        utils.printerr(str(e))
Exemplo n.º 13
0
def main():
    parser = Args.make_parser(
        'Lists the fuzzing corpus instances in CIPD for a named fuzzer')
    args = parser.parse_args()

    host = Host()
    device = Device.from_args(host, args)
    fuzzer = Fuzzer.from_args(device, args)
    cipd = Cipd(fuzzer)

    if not cipd.list():
        return 1
    return 0
Exemplo n.º 14
0
def main():
    """ Main Entry Point """

    args = parse_args()

    log_level = logging.INFO
    if args.debug:
        log_level = logging.DEBUG

    logging.basicConfig(level=log_level, format="%(message)s")

    dev = Device()
    dev.open_device()

    etrace = Etrace(dev)
    etrace.print()

    if args.hexdump:
        etrace.hexdump()

    if args.output_file:
        etrace.save(args.output_file)
Exemplo n.º 15
0
def main():
    parser = Args.make_parser('Stops the named fuzzer.')
    args = parser.parse_args()

    host = Host.from_build()
    device = Device.from_args(host, args)
    fuzzer = Fuzzer.from_args(device, args)

    if fuzzer.is_running():
        print('Stopping ' + str(fuzzer) + '.')
        fuzzer.stop()
    else:
        print(str(fuzzer) + ' is already stopped.')
    return 0
Exemplo n.º 16
0
def main():
    parser = Args.make_parser(
        'Runs the named fuzzer on provided test units, or all current test ' +
        'units for the fuzzer. Use \'check-fuzzer\' to see current tests units.'
    )
    args, fuzzer_args = parser.parse_known_args()

    host = Host.from_build()
    device = Device.from_args(host, args)
    fuzzer = Fuzzer.from_args(device, args)

    if fuzzer.repro(fuzzer_args) == 0:
        print('No matching artifacts found.')
        return 1
    return 0
Exemplo n.º 17
0
def main():
    parser = Args.make_parser(
        'Transfers a fuzzing corpus for a named fuzzer from a device to CIPD')
    args = parser.parse_args()

    host = Host()
    device = Device.from_args(host, args)
    fuzzer = Fuzzer.from_args(device, args)

    if fuzzer.measure_corpus()[0] == 0:
        print('Ignoring ' + str(fuzzer) + '; corpus is empty.')
        return 0
    with Cipd.from_args(fuzzer, args) as cipd:
        device.fetch(fuzzer.data_path('corpus/*'), cipd.root)
        if not cipd.create():
            return 1
    return 0
Exemplo n.º 18
0
def main():
  parser = Args.make_parser(
      'Transfers corpus for a named fuzzer to a device', label_present=True)
  args = parser.parse_args()

  host = Host()
  device = Device.from_args(host, args)
  fuzzer = Fuzzer.from_args(device, args)

  if os.path.isdir(args.label):
    device.store(os.path.join(args.label, '*'), fuzzer.data_path('corpus'))
    return 0
  with Cipd.from_args(fuzzer, args, label=args.label) as cipd:
    if not cipd.install():
      return 1
    device.store(os.path.join(cipd.root, '*'), fuzzer.data_path('corpus'))
  return 0
Exemplo n.º 19
0
def main():
    parser = ArgParser(
        'Transfers a fuzzing corpus for a named fuzzer from a device to CIPD')
    args = parser.parse_args()

    host = Host.from_build()
    device = Device.from_args(host, args)
    fuzzer = Fuzzer.from_args(device, args)

    if fuzzer.measure_corpus()[0] == 0:
        print('Ignoring ' + str(fuzzer) + '; corpus is empty.')
        return 0
    with Corpus.from_args(fuzzer, args) as corpus:
        corpus.pull()
        cipd = Cipd(corpus)
        if not args.no_cipd:
            cipd.create()
    return 0
Exemplo n.º 20
0
def main():
    parser = ArgParser(
        'Starts the named fuzzer.  Additional arguments are passed through.')
    args, fuzzer_args = parser.parse_known_args()

    host = Host.from_build()
    device = Device.from_args(host, args)
    fuzzer = Fuzzer.from_args(device, args)

    if not args.monitor:
        with Corpus.from_args(fuzzer, args) as corpus:
            cipd = Cipd(corpus)
            if not args.no_cipd:
                cipd.install('latest')
            corpus.push()

        print(
            '\n****************************************************************'
        )
        print(' Starting ' + str(fuzzer) + '.')
        print(' Outputs will be written to:')
        print('   ' + fuzzer.results())
        if not args.foreground:
            print(' You should be notified when the fuzzer stops.')
            print(' To check its progress, use `fx fuzz check ' + str(fuzzer) +
                  '`.')
            print(' To stop it manually, use `fx fuzz stop ' + str(fuzzer) +
                  '`.')
        print(
            '****************************************************************\n'
        )
        fuzzer.start(fuzzer_args)
        if not args.foreground:
            subprocess.Popen(['python', sys.argv[0], '--monitor', str(fuzzer)])
    else:
        fuzzer.monitor()
        title = str(fuzzer) + ' has stopped.'
        body = 'Output written to ' + fuzzer.results() + '.'
        print(title)
        print(body)
        host.notify_user(title, body)
    return 0
Exemplo n.º 21
0
def on_start_input(cmd: pcmd.Command, args: List[str], indi: int,
                   json: bool) -> None:
    """Callback for `start input` - adds an input device"""
    try:
        ch.add_ist(
            Device(pa,
                   format=pyaudio.paFloat32,
                   channels=1,
                   rate=params.SMPRATE,
                   input=True,
                   input_device_index=indi))
        if json:
            print(JSON.dumps({}))
    except Exception as e:
        if not json:
            utils.printerr(str(e))
        else:
            print(JSON.dumps({
                'error': str(e),
            }))
Exemplo n.º 22
0
def main():
  parser = Args.make_parser(
      'Minimizes the current corpus for the named fuzzer. This should be ' +
      'used after running the fuzzer for a while, or after incorporating a ' +
      'third-party corpus using \'fetch-corpus\'')
  args, fuzzer_args = parser.parse_known_args()

  host = Host.from_build()
  device = Device.from_args(host, args)
  fuzzer = Fuzzer.from_args(device, args)

  with Cipd.from_args(fuzzer, args) as cipd:
    if cipd.install():
      device.store(os.path.join(cipd.root, '*'), fuzzer.data_path('corpus'))
    if fuzzer.merge(fuzzer_args) == (0, 0):
      print('Corpus for ' + str(fuzzer) + ' is empty.')
      return 1
    device.fetch(fuzzer.data_path('corpus/*'), cipd.root)
    if not cipd.create():
      return 1
  return 0
Exemplo n.º 23
0
def main():
    parser = Args.make_parser(
        description='Reports status for the fuzzer matching NAME if provided, '
        +
        'or for all running fuzzers.  Status includes execution state, corpus '
        + 'size, and number of artifacts.',
        name_required=False)
    args = parser.parse_args()

    host = Host()
    device = Device.from_args(host, args)
    fuzzers = Fuzzer.filter(host.fuzzers, args.name)

    pids = device.getpids()
    silent = True
    for pkg, tgt in fuzzers:
        fuzzer = Fuzzer(device, pkg, tgt)
        if not args.name and tgt not in pids:
            continue
        silent = False
        if tgt in pids:
            print(str(fuzzer) + ': RUNNING')
        else:
            print(str(fuzzer) + ': STOPPED')
        print('    Output path:  ' + fuzzer.data_path())
        print('    Corpus size:  %d inputs / %d bytes' %
              fuzzer.measure_corpus())
        artifacts = fuzzer.list_artifacts()
        if len(artifacts) == 0:
            print('    Artifacts:    None')
        else:
            print('    Artifacts:    ' + artifacts[0])
            for artifact in artifacts[1:]:
                print('                  ' + artifact)
    if silent:
        print(
            'No fuzzers are running.  Include \'name\' to check specific fuzzers.'
        )
        return 1
    return 0
Exemplo n.º 24
0
def main():
    parser = ArgParser(
        'Minimizes the current corpus for the named fuzzer. This should be ' +
        'used after running the fuzzer for a while, or after incorporating a '
        + 'third-party corpus using \'fetch-corpus\'')
    args, fuzzer_args = parser.parse_known_args()

    host = Host.from_build()
    device = Device.from_args(host, args)
    fuzzer = Fuzzer.from_args(device, args)

    with Corpus.from_args(fuzzer, args) as corpus:
        cipd = Cipd(corpus)
        if not args.no_cipd:
            cipd.install('latest')
        corpus.push()
        if fuzzer.merge(fuzzer_args) == (0, 0):
            print('Corpus for ' + str(fuzzer) + ' is empty.')
            return 1
        corpus.pull()
        if not args.no_cipd:
            cipd.create()
    return 0
Exemplo n.º 25
0
Arquivo: avd.py Projeto: pr1001/avd
def run(options, arguments):
    AVD_ROOT = os.path.abspath(os.path.dirname(sys.argv[0]))
    AVD_REPO_ROOT = os.path.abspath(options.repo)
    ANDROID_SDK_ROOT = os.path.abspath(options.sdk)
    
    if len(arguments) == 1:
        subject = arguments[0]
        if (subject == 'devices'):
            devices = [os.path.basename(entry) for entry in os.listdir(os.path.join(AVD_ROOT, 'devices')) if os.path.isfile(os.path.join(AVD_ROOT, 'devices', entry)) and os.path.splitext(os.path.join(AVD_ROOT, 'devices', entry))[1] == '.json']
            # stupid Python and returning None instead of an empty List
            if (not devices):
                devices = []
            for device_name in devices:
                device = Device(os.path.splitext(device_name)[0], AVD_ROOT, AVD_REPO_ROOT, ANDROID_SDK_ROOT)
                print 'Name: {name}'.format(name=device.name)
                if device.skin:
                    print 'Skin: {skin}'.format(skin=device.skin.name)
                versions = ', '.join(device.supported_versions) if device.supported_versions else 'None'
                print 'Versions Supported: {versions}'.format(versions=versions)
                installed = ', '.join(device.installed_versions()) if device.installed_versions() else 'None'
                print 'Versions Installed: {installed}'.format(installed=installed)
            if not devices:
                print "No devices installed."
        elif (subject == 'skins'):
            skins = [os.path.basename(entry) for entry in os.listdir(os.path.join(AVD_ROOT, 'skins')) if os.path.isdir(os.path.join(AVD_ROOT, 'skins', entry))]
            # stupid Python and returning None instead of an empty List
            if (not skins):
                skins = []
            for skin_name in skins:
                skin = Skin(skin_name, AVD_ROOT, ANDROID_SDK_ROOT)
                print 'Name: {name}'.format(name=skin.name)
                versions = ', '.join(skin.supported_versions) if skin.supported_versions else 'None'
                print 'Versions Supported: {versions}'.format(versions=versions)
                installed = ', '.join(skin.installed_versions()) if skin.installed_versions() else 'None'
                print 'Versions Installed: {installed}'.format(installed=installed)
            if not skins:
                print 'No skins installed.'
    elif len(arguments) == 3:
        subject, action, name = arguments
        
        if (subject == 'device'):
            device = Device(name, AVD_ROOT, AVD_REPO_ROOT, ANDROID_SDK_ROOT)
            if (action == 'info'):
                print 'Name: {name}'.format(name=device.name)
                if device.skin:
                    print 'Skin: {skin}'.format(skin=device.skin.name)
                versions = ', '.join(device.supported_versions) if device.supported_versions else 'None'
                print 'Versions Supported: {versions}'.format(versions=versions)
                installed = ', '.join(device.installed_versions()) if device.installed_versions() else 'None'
                print 'Versions Installed: {installed}'.format(installed=installed)
            elif (action == 'install'):
                if (options.target):
                    if (device.install(options.target)):
                        print 'Successfully installed the device {name} for version {version}. The specific device name is {versioned_name}.'.format(name=device.name, version=options.target, versioned_name=device.versioned_name(options.target))
                    else:
                        print 'Unable to install the device {name} for version {version}. Please check that the devices isn\'t already installed, {version} is one of the device\'s supported versions, and that the appropriate file permissions are set.'.format(name=device.name, version=options.target)
                else:
                    results = [device.install(version) for version in device.supported_versions]
                    if not False in results:
                        print 'Successfully installed the device {name} for all supported versions: {versions}. The specific device names are: {versioned_names}.'.format(name=device.name, versions=', '.join(device.supported_versions), versioned_names=', '.join([device.versioned_name(version) for version in device.supported_versions]))
                    else:
                        print 'Unable to install the device {name} for one or more of the Android versions.'.format(name=device.name)
            elif (action == 'uninstall'):
                if (options.target):
                    if (device.uninstall(options.target)):
                        print 'Successfully uninstalled the device {name} for version {version}.'.format(name=device.name, version=options.target)
                    else:
                        print 'Unable to uninstall the device {name} for version {version}. Please check that the device isn\'t already uninstalled, {version} is one of the device\'s supported versions, and that the appropriate file permissions are set.'.format(name=device.name, version=options.target)
                else:
                    results = [device.uninstall(version) for version in device.supported_versions]
                    if not False in results:
                        print 'Successfully uninstalled the device {name} for all supported versions: {versions}.'.format(name=device.name, versions=', '.join(device.supported_versions))
                    else:
                        print 'Unable to uninstall the device {name} for one or more of the Android versions.'.format(name=device.name)
            else:
                print "Invalid action: {action}".format(action=action)
                return False
        elif (subject == 'skin'):
            skin = Skin(name, AVD_ROOT, ANDROID_SDK_ROOT)
            if (action == 'info'):
                print 'Name: {name}'.format(name=skin.name)
                versions = ', '.join(skin.supported_versions) if skin.supported_versions else 'None'
                print 'Versions Supported: {versions}'.format(versions=versions)
                installed = ', '.join(skin.installed_versions()) if skin.installed_versions() else 'None'
                print 'Versions Installed: {installed}'.format(installed=installed)
            elif (action == 'install'):
                if (options.target):
                    if (skin.install(options.target)):
                        print 'Successfully installed the skin {name} for version {version}.'.format(name=skin.name, version=options.target)
                    else:
                        print 'Unable to install the skin {name} for version {version}. Please check that the skins isn\'t already installed, {version} is one of the skin\'s supported versions, and that the appropriate file permissions are set.'.format(name=skin.name, version=options.target)
                else:
                    results = [skin.install(version) for version in skin.supported_versions]
                    if not False in results:
                        print 'Successfully installed the skin {name} for all supported versions: {versions}.'.format(name=skin.name, versions=', '.join(skin.supported_versions))
                    else:
                        print 'Unable to install the skin {name} for one or more of the Android versions.'.format(name=skin.name)
            elif (action == 'uninstall'):
                if (options.target):
                    if (skin.uninstall(options.target)):
                        print 'Successfully uninstalled the skin {name} for version {version}.'.format(name=skin.name, version=options.target)
                    else:
                        print 'Unable to uninstall the skin {name} for version {version}. Please check that the skin isn\'t already uninstalled, {version} is one of the skin\'s supported versions, and that the appropriate file permissions are set.'.format(name=skin.name, version=options.target)
                else:
                    results = [skin.uninstall(version) for version in skin.supported_versions]
                    if not False in results:
                        print 'Successfully uninstalled the skin {name} for all supported versions: {versions}.'.format(name=skin.name, versions=', '.join(skin.supported_versions))
                    else:
                        print 'Unable to uninstall the skin {name} for one or more of the Android versions.'.format(name=skin.name)
            else:
                print "Invalid action: {action}".format(action=action)
                return False
        else:
            print "Invalid subject: {subject}".format(subject=subject)
            return False
Exemplo n.º 26
0
    def test_ssh_verbosity(self):
        device = Device(self.buildenv, '::1')
        self.assertEqual(device.ssh_verbosity, 0)

        with self.assertRaises(ValueError):
            device.ssh_verbosity = 4

        device.ssh_verbosity = 3
        self.assertEqual(['-vvv'], device.ssh_opts())

        device.ssh_verbosity = 2
        self.assertEqual(['-vv'], device.ssh_opts())

        device.ssh_verbosity = 1
        self.assertEqual(['-v'], device.ssh_opts())

        device.ssh_verbosity = 0
        self.assertEqual([], device.ssh_opts())

        with self.assertRaises(ValueError):
            device.ssh_verbosity = -1
Exemplo n.º 27
0
 def test_get_devices(self):
     """ Test set_copies() and set_rotation(90) should stack along x axis."""
     for device in Device.get_printers():
         print device.name
     assert 1 == 0
Exemplo n.º 28
0
 def test_get_devices(self):
     """ Test set_copies() and set_rotation(90) should stack along x axis."""
     for device in Device.get_printers():
         print device.name
     assert 1==0
Exemplo n.º 29
0
 def _create_device(self, name, params):
     return Device(name=params[name],
                   terminal_list=params[name]['terminal'],
                   default_terminal=params[name]['default_terminal'],
                   logger=logger)
Exemplo n.º 30
0

# Character passed in mailbox ID field
def mailbox_poll_char(dev):
    while True:
        if dev.dsp_hipct.value & regs.ADSP_IPC_HIPCT_BUSY:

            # Use only id for passing character
            character = dev.dsp_hipct.value & regs.ADSP_IPC_HIPCT_MSG

            # Get readable character
            character &= 0x10FFFF

            print('{}'.format(chr(character)), end='')

            # Clear interrupt
            dev.dsp_hipct.value |= regs.ADSP_IPC_HIPCT_BUSY
        else:
            sleep(0.005)


if __name__ == "__main__":
    # Clear Done if needed
    #dev.dsp_hipct.value |= regs.ADSP_IPC_HIPCT_BUSY

    # Use Device library for controlling registers
    device = Device()
    device.open_device()

    mailbox_poll_mem(device)
Exemplo n.º 31
0
class FirmwareLoader():
    def __init__(self):
        self._init_done = False
        self.dma_id = None
        self.dev = None
        self.sdl = None

    def init(self, dma_id):
        if self._init_done:
            logging.warning("Already initialized! Skip init")
            return

        self.dma_id = dma_id
        self.dev = Device()
        self.dev.open_device()
        self.sdl = StreamDescList(self.dev)
        self.ipc = Ipc(self.dev)
        self._init_done = True

    def close(self):
        if not self._init_done:
            logging.warning("Not initialized! Skip closing.")
            return

        self.sdl.close()
        self.dev.close()
        self._init_done = False

    def reset_dsp(self):
        logging.debug(">>> FirmwareLoader.reset_dsp()")
        logging.debug("Recycling controller power...")
        self.dev.power_cycle()

        # This should be enabled prior to power down the cores.
        self.dev.enable_proc_pipe_ctl()

        logging.debug("Power down cores...")
        self.dev.core_stall_reset(plat_def.CORE_MASK)
        self.dev.core_power_down(plat_def.CORE_MASK)
        logging.debug("<<< FirmwareLoader.reset_dsp()")

    def boot_dsp(self):
        logging.debug(">>> FirmwareLoader.boot_dsp()")
        self.dev.enable_proc_pipe_ctl()
        self.sdl.reset_all()
        self.dev.core_power_up(0x1)
        self.dev.dsp_hipct.value = self.dev.dsp_hipct.value

        logging.debug("Purging pending FW request")
        boot_config = plat_def.FW_IPC_PURGE | regs_def.ADSP_IPC_HIPCI_BUSY
        boot_config = boot_config | ((self.dma_id - 7) << 9)
        self.dev.dsp_hipci.value = boot_config
        time.sleep(0.1)
        logging.debug("   DSP_HIPCI=%s" % self.dev.dsp_hipci)

        self.dev.core_power_up(plat_def.CORE_MASK)
        self.dev.core_run(plat_def.CORE_0)
        self.dev.core_run(plat_def.CORE_1)
        logging.debug("Wait for IPC DONE bit from ROM")
        while True:
            ipc_ack = self.dev.dsp_hipcie.value
            if (ipc_ack & (1 << regs_def.ADSP_IPC_HIPCIE_DONE_OFFSET)) != 0:
                break
            time.sleep(0.1)
        logging.debug("<<< FirmwareLoader.boot_dsp()")

    def check_fw_boot_status(self, expected):
        logging.debug(">>> FirmwareLoader.check_fw_boot_status(0x%08X)" %
                      expected)
        raw_status = self.dev.fw_status.value
        FirmwareStatus(raw_status).print()

        if (raw_status & plat_def.FW_STATUS_ERROR) != 0:
            output = ("Firmware Status error:"
                      "   Status:     0x%08X\n"
                      "   Error Code  0x%08X" %
                      (raw_status, self.dev.fw_err_code.value))
            raise RuntimeError(output)
        status = raw_status & plat_def.FW_STATUS_BOOT_STATE
        logging.debug("<<< FirmwareLoader.check_fw_boot_status()")
        return status == expected

    def wait_for_fw_boot_status(self, boot_status):
        logging.debug("Waiting for FW Boot Status: 0x%08X (%s)" %
                      (boot_status, plat_def.BOOT_STATUS_STR(boot_status)))

        for _ in range(10):
            reg = self.dev.fw_status.value
            bs = reg & plat_def.FW_STATUS_BOOT_STATE
            if bs == boot_status:
                logging.debug("Received Expected Boot Status")
                return True
            time.sleep(0.01)
        logging.error("Failed to receive expected status")
        return False

    def wait_for_fw_wait_status(self, wait_status):
        logging.debug("Waiting for FW Wait Status: 0x%08X (%s)" %
                      (wait_status, plat_def.WAIT_STATUS_STR(wait_status)))
        for _ in range(10):
            reg = self.dev.fw_status.value
            ws = reg & plat_def.FW_STATUS_WAIT_STATE
            if ws == (wait_status << plat_def.FW_STATUS_WAIT_STATE_OFFSET):
                logging.debug("Received Expected Wait Status")
                return True
            time.sleep(0.01)
        logging.error("Failed to receive expected status")
        return False

    def load_firmware(self, fw_file):
        logging.debug(">>> FirmwareLoader.load_firmware()")
        with open(fw_file, "rb") as fd:
            data = array.array('B', fd.read())
            sd = self.sdl.get_sd(self.dma_id)
            sd.enable = True
            sd.alloc_memory(len(data))
            sd.buf.copy(data, len(data))
            sd.config()
            sd.set_stream_id(1)
            sd.set_traffic_priority(1)
            sd.set_bitrate(0x4)
            time.sleep(0.1)
            logging.debug("<<< FirmwareLoader.load_firmware()")
            return sd

    def download_firmware(self, fw_file):
        logging.debug(">>> FirmwareLoader.download_firmware(fw_file=%s)" %
                      fw_file)

        # Load firmware to DMA buffer and update SD and SDL
        sd = self.load_firmware(fw_file)
        try:
            self.dev.hda_spibe.value |= (1 << self.dma_id)
            self.wait_for_fw_wait_status(plat_def.WAIT_STATUS_DMA_BUFFER_FULL)

            logging.info("Start firmware downloading...")
            sd.start()
            time.sleep(0.5)
            self.wait_for_fw_boot_status(plat_def.BOOT_STATUS_FW_ENTERED)
        finally:
            sd.pause()
            sd.reset()
            self.sdl.release_sd(sd.idx)
            self.dev.hda_spibe.value = 0

        logging.debug("<<< FirmwareLoader.download_firmware()")