Skip to content

Commit

Permalink
Clean up libusb resources on some upload/download/reset failures
Browse files Browse the repository at this point in the history
In many cases we have already err'd out but if we end up back
in main() we can do it more tidily.

Signed-off-by: Tormod Volden <[email protected]>
  • Loading branch information
tormodvolden committed Nov 22, 2020
1 parent dbe170a commit 158a435
Showing 1 changed file with 16 additions and 18 deletions.
34 changes: 16 additions & 18 deletions src/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -685,14 +685,9 @@ int main(int argc, char **argv)
err(EX_CANTCREAT, "Cannot open file %s for writing", file.name);

if (dfuse_device || dfuse_options) {
if (dfuse_do_upload(dfu_root, transfer_size, fd,
dfuse_options) < 0)
exit(1);
ret = dfuse_do_upload(dfu_root, transfer_size, fd, dfuse_options);
} else {
if (dfuload_do_upload(dfu_root, transfer_size,
expected_size, fd) < 0) {
exit(1);
}
ret = dfuload_do_upload(dfu_root, transfer_size, expected_size, fd);
}
close(fd);
break;
Expand All @@ -709,40 +704,43 @@ int main(int argc, char **argv)
dfu_root->vendor, dfu_root->product);
}
if (dfuse_device || dfuse_options || file.bcdDFU == 0x11a) {
if (dfuse_do_dnload(dfu_root, transfer_size, &file,
dfuse_options) < 0)
exit(1);
ret = dfuse_do_dnload(dfu_root, transfer_size, &file, dfuse_options);
} else {
if (dfuload_do_dnload(dfu_root, transfer_size, &file) < 0)
exit(1);
ret = dfuload_do_dnload(dfu_root, transfer_size, &file);
}
break;
case MODE_DETACH:
if (dfu_detach(dfu_root->dev_handle, dfu_root->interface, 1000) < 0) {
ret = dfu_detach(dfu_root->dev_handle, dfu_root->interface, 1000);
if (ret < 0) {
warnx("can't detach");
/* allow combination with final_reset */
ret = 0;
}
break;
default:
errx(EX_SOFTWARE, "Unsupported mode: %u", mode);
warnx("Unsupported mode: %u", mode);
ret = EX_SOFTWARE;
break;
}

if (final_reset) {
if (dfu_detach(dfu_root->dev_handle, dfu_root->interface, 1000) < 0) {
if (!ret && final_reset) {
ret = dfu_detach(dfu_root->dev_handle, dfu_root->interface, 1000);
if (ret < 0) {
/* Even if detach failed, just carry on to leave the
device in a known state */
warnx("can't detach");
}
printf("Resetting USB to switch back to runtime mode\n");
ret = libusb_reset_device(dfu_root->dev_handle);
if (ret < 0 && ret != LIBUSB_ERROR_NOT_FOUND) {
errx(EX_IOERR, "error resetting after download: %s", libusb_error_name(ret));
warnx("error resetting after download: %s", libusb_error_name(ret));
ret = EX_IOERR;
}
}

libusb_close(dfu_root->dev_handle);
dfu_root->dev_handle = NULL;
libusb_exit(ctx);

return (0);
return (ret);
}

0 comments on commit 158a435

Please sign in to comment.