Skip to content

Commit 695df3c

Browse files
fix(dwc2/hcd): guard against divide-by-zero when ep_size is 0
In cal_packet_count(), ep_size could be 0 if the device descriptor returns bMaxPacketSize0 = 0 (due to buggy device or DMA cache coherency issues), causing an integer divide-by-zero crash. Two-layer fix: - In hcd_edpt_open(): validate ep_size != 0 before allocating the endpoint slot, returning false to let enumeration handle the error gracefully rather than storing an invalid ep_size. - In cal_packet_count(): guard ep_size == 0 as a last-resort safety net to prevent a hard crash if an endpoint with zero ep_size is somehow used for a transfer. Fixes #3525 Co-authored-by: Ha Thach <hathach@users.noreply.github.com>
1 parent cd7bbba commit 695df3c

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

src/portable/synopsys/dwc2/hcd_dwc2.c

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,7 @@ TU_ATTR_ALWAYS_INLINE static inline uint8_t edpt_find_opened(uint8_t dev_addr, u
293293
}
294294

295295
TU_ATTR_ALWAYS_INLINE static inline uint16_t cal_packet_count(uint16_t len, uint16_t ep_size) {
296-
if (len == 0) {
296+
if (len == 0 || ep_size == 0) {
297297
return 1;
298298
} else {
299299
return tu_div_ceil(len, ep_size);
@@ -523,13 +523,16 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, const tusb_desc_endpoint_t*
523523
tuh_bus_info_t bus_info;
524524
tuh_bus_info_get(dev_addr, &bus_info);
525525

526+
const uint16_t ep_size = tu_edpt_packet_size(desc_ep);
527+
TU_ASSERT(ep_size != 0, false); // ep descriptor must have non-zero wMaxPacketSize
528+
526529
// find a free endpoint
527530
const uint8_t ep_id = edpt_alloc();
528531
TU_ASSERT(ep_id < CFG_TUH_DWC2_ENDPOINT_MAX);
529532
hcd_endpoint_t* edpt = &_hcd_data.edpt[ep_id];
530533

531534
dwc2_channel_char_t* hcchar_bm = &edpt->hcchar_bm;
532-
hcchar_bm->ep_size = tu_edpt_packet_size(desc_ep);
535+
hcchar_bm->ep_size = ep_size;
533536
hcchar_bm->ep_num = tu_edpt_number(desc_ep->bEndpointAddress);
534537
hcchar_bm->ep_dir = tu_edpt_dir(desc_ep->bEndpointAddress);
535538
hcchar_bm->low_speed_dev = (bus_info.speed == TUSB_SPEED_LOW) ? 1 : 0;

0 commit comments

Comments
 (0)