Tk Source Code

View Ticket
Login
Ticket UUID: 156e58bc6e14031e7b302bc65a862948f765b9e8
Title: Tk_PhotoPutBlock(), Tk_PhotoPutZoomedBlock(): undefined behavior, other possible issues?
Type: Bug Version: 8.6.12
Submitter: chrstphrchvz Created on: 2021-12-08 23:27:24
Subsystem: 41. Photo Images Assigned To: jan.nijtmans
Priority: 5 Medium Severity: Minor
Status: Closed Last Modified: 2021-12-14 23:05:40
Resolution: Fixed Closed By: jan.nijtmans
    Closed on: 2021-12-14 23:05:40
Description:

A pointer range check was added in [11192077fd] to Tk_PhotoPutBlock() and Tk_PhotoPutZoomedBlock() to avoid corruption when the source and destination images are backed by the same data buffer. The second part of the range check involves pointer arithmetic on modelPtr->pix32:

sourceBlock.pixelPtr <= modelPtr->pix32 + modelPtr->width * modelPtr->height * 4

However, these functions are called even when the destination image does not have a valid data buffer, i.e. modelPtr->pix32 is NULL, and there is no check for NULL prior to the range check. This leads to pointer arithmetic using NULL, which is undefined (at least since C89). Example complaint from UBSan (-fsanitize=pointer-overflow):

% image create photo src -height 1 -width 1
src
% image create photo dst
dst
% dst copy src
tk/generic/tkImgPhoto.c:2774:49: runtime error: applying zero offset to null pointer
% dst copy src -zoom 2 2
tk/generic/tkImgPhoto.c:3220:49: runtime error: applying zero offset to null pointer

Pointer arithmetic with NULL could be avoided by putting

NULL != modelPtr->pix32 && …

at the very beginning of the condition. But I believe there may still be other issues with the range check:

  • Is using sourceBlock.pixelPtr <= … instead of soucreBlock.pixelPtr < … correct, or does it lead to unnecessarily copying the source buffer when sourceBlock.pixelPtr happens to point to the beginning of a buffer beginning immediately after the buffer pointed to by modelPtr->pix32?
  • The range check resembles the problem described in https://devblogs.microsoft.com/oldnewthing/20170927-00/?p=97095: either the pointers are for the same buffer and the check is always true, or the pointers are to different buffers and the check is undefined behavior. If this is the case, I’m not aware of a good workaround: the suggestion of casting to uintptr_t requires C99, and there doesn’t appear to be anything in Tk_PhotoImageBlock that would be useful for knowing if it corresponds to data for a particular existing PhotoModel.

User Comments: jan.nijtmans added on 2021-12-14 23:05:40:

Thanks for the bug report. The check for modelPtr->pix32 is added now, and the "<=" check is modified to "<": good suggestions, thanks!

About the range check, I don't know how to improve that. Similar to 41b1406f51. So closing this one too.

I you have a better idea, feel free to re-open this issue.