Tk Source Code

View Ticket
Login
Ticket UUID: 92e4081d7464ce5e8eaef6f679fda1b6fb1cd840
Title: Undefined behavior while touchpad scrolling
Type: Bug Version: core-9-0-branch
Submitter: chrstphrchvz Created on: 2025-08-12 03:34:41
Subsystem: 01. Bindings Assigned To: chrstphrchvz
Priority: 5 Medium Severity: Minor
Status: Closed Last Modified: 2025-08-16 22:15:32
Resolution: Fixed Closed By: jan.nijtmans
    Closed on: 2025-08-16 22:15:32
Description:

Left-shifting a negative signed integer is undefined behavior. There is an instance of this in the touchpad scrolling (TIP 684) code for both Win32 and Aqua.

Example -fsanitize=shift-base error when scrolling right on a touchpad on Aqua:

macosx/tkMacOSXMouseEvent.c:562:22: runtime error: left shift of negative value -1

Suggested possible fixes (Win32 not tested):

--- win/tkWinX.c
+++ win/tkWinX.c
@@ -1196,7 +1196,7 @@ GenerateXEvent(
 		event.key.nbytes = 0;
 		event.x.xkey.state = state;
 		event.x.xany.serial = scrollCounter++;
-		event.x.xkey.keycode = (unsigned int)(-(delta << 16));
+		event.x.xkey.keycode = (unsigned int)(-delta) << 16;
 	    } else {
 		event.x.type = MouseWheelEvent;
 		event.x.xany.send_event = -1;
--- macosx/tkMacOSXMouseEvent.c
+++ macosx/tkMacOSXMouseEvent.c
@@ -545,7 +545,7 @@ enum {
 	}
     } else {
 	static unsigned long scrollCounter = 0;
-	int delta;
+	unsigned int delta;
 	CGFloat Delta;
 	Bool deltaIsPrecise = [theEvent hasPreciseScrollingDeltas];
 	XEvent xEvent = {0};
@@ -559,7 +559,9 @@ enum {
 	if (deltaIsPrecise) {
 	    int deltaX = [theEvent scrollingDeltaX];
 	    int deltaY = [theEvent scrollingDeltaY];
-	    delta = (deltaX << 16) | (deltaY & 0xffff);
+	    delta = deltaX;
+	    delta <<= 16;
+	    delta |= deltaY & 0xffff;
 	    if (delta != 0) {
 		xEvent.type = TouchpadScroll;
 		xEvent.xbutton.state = state;

User Comments: jan.nijtmans added on 2025-08-16 22:15:32:

Thanks for confirming!

[07d632f4ee7d9fae|fixed] now


chrstphrchvz added on 2025-08-16 18:00:42:

I have verified Jan’s approach works on Aqua. I have not tested it on win32 but I do not spot any issues with it.


jan.nijtmans added on 2025-08-16 15:58:03:

How about [a4410a9271d81736|this]?


marc_culler (claiming to be Marc Culler) added on 2025-08-15 21:13:46:
I agree with Harald that this is a good catch.  And I add my mea culpa.

But I am not sure of the current status.  Did this patch get applied?

oehhar added on 2025-08-12 06:27:03:

Good catch. I think, this may be committed.

Thanks, Harald