https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109352
Bug ID: 109352 Summary: Feature request: warn about "u64 = u32 * u32" and similar Product: gcc Version: unknown Status: UNCONFIRMED Severity: normal Priority: P3 Component: c Assignee: unassigned at gcc dot gnu.org Reporter: zhangboyang.id at gmail dot com Target Milestone: --- Hi, Please consider give warnings about "u64 = u32 * u32" and similar statements. In most cases, programmers want "u64 = (uint64_t) u32 * (uint64_t) u32" instead of "u64 = (uint32_t) u32 * (uint32_t) u32". This cause real world problems. In a security bug of GNU GRUB2 (CVE-2022-2601, reported by me), a similar expression causes interger overflow therefore heap overwrite. The simplified code is like below: struct bitmap { uint32_t width, height; uint8_t pixel[]; }; bmp = malloc(sizeof(struct bitmap) + width * height / 8); In the above example, if width==65536 and height==65536, then width*height will overflow to 0. Thus the allocated memory is smaller than expected. I'm not a compiler expert, so I can't give a precise definition of which statements should be warned. But I come up with some example code, please see below: 1) uint64_t pow2(int n) { return 1 << n; // I think almost everyone was hit by this :) return 1U << n; // or this } 2) double area(float b, float h) { return b * h / 2.0; // lose precision } 3) uint64_t add(uint64_t base, uint32_t a, uint32_t b) { return base + (a + b); // it's different from "base + a + b" } By the way, if a programmer think a warning is unnecessary, it should be able to suppressed by "u64 = (uint32_t)(u32 * u32);" Zhang Boyang