Skip to content

Function touches whole buffer even if not necessary #1773

@levicki

Description

@levicki

int API_EXPORTED libusb_get_port_numbers(libusb_device *dev,

Currently the function libusb_get_port_numbers writes into the array from the end and then uses memmove but doesn't cleanup the remainder.

Also it writes into buffer even when it later fails due to overflow which IMO is a code smell — the golden rule is don't write out result if you are returning error.

Example call:

unsigned char buffer[7]{};

int count = libusb_get_port_numbers(device, buffer, 7);

For count = 2 and ports 11 2, the buffer will have 11 2 0 0 0 11 2 instead of 11 2 0 0 0 0 0.

I don't know about you, but I'd prefer if it worked like this:

int count = 0;
struct libusb_device *tmp = dev;

while ((tmp) && (tmp->port_number != 0)) {
    count++;
    tmp = tmp->parent_dev;
}

if (count > port_numbers_len) { // don't write partial results
    usbi_warn(ctx, "port numbers array is too small");
    return LIBUSB_ERROR_OVERFLOW;
}

for (int i = count - 1; i >= 0; i--) {
    port_numbers[i] = dev->port_number;
    dev = dev->parent_dev;
}

return count;

As a minimal alternative if you are concerned with performance at least do memset to clear the leftovers after current memmove.

Metadata

Metadata

Assignees

No one assigned

    Labels

    coreRelated to common codes

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions