Closed Bug 583325 Opened 14 years ago Closed 14 years ago

CheckedInt: beware of signed right shift!

Categories

(Core :: General, defect)

defect
Not set
normal

Tracking

()

RESOLVED FIXED
Tracking Status
blocking2.0 --- betaN+

People

(Reporter: bjacob, Assigned: bjacob)

Details

Attachments

(1 file, 4 obsolete files)

Attached patch beware of arithmetic right shift (obsolete) — Splinter Review
In C/C++, AFAIU, doing x >> y with x signed can result in a plain shift or in arithmetic shift, the compiler is free to decide.

The problem is that CheckedInt was doing that, and wrongly assuming that this would always be a plain shift (not an arithmetic shift). As a result, on a compiler that would generate arithmetic shifts, it could produce illegal PRBool values such as 0xffffffff.

This patch fixes that and adds some comments. We still do >> but don't rely anymore on it being a plain shift. Before casting to PRBool, we AND with 1.
Thanks to cjones for pointing out that shifting signed integers is just plain undefined, at least in the current c++0x draft spec.

This new version only uses a shift in the unsiged case.
Attachment #461648 - Attachment is obsolete: true
Wow, this was more subtle than anticipated. It turns out that x >> y is undefined for negative x, and that x << y is undefined even for positive x in a signed type if the result is non-representable. It also turns out that while signed-to-unsigned conversions are well-defined, unsigned-to-signed conversions are only well-defined if the result is representable.

Coming up with a version that's using only well-defined C++ required to know for each integral type what its unsigned variant is. This is now in integer_traits and the unit test is expanded to cover this.
Attachment #461656 - Attachment is obsolete: true
... and so, now that we are shifting only unsigned integers, we are again guaranteed that our mIsValid value is always 0 or 1 so we can do without the bit AND in valid().
Attachment #461673 - Attachment is obsolete: true
this update just fixes a couple of typos in a comment.
Attachment #461674 - Attachment is obsolete: true
Attachment #461677 - Flags: review?
Attachment #461677 - Flags: review? → review?(lw)
Attachment #461677 - Flags: review?(lw) → review+
Comment on attachment 461677 [details] [diff] [review]
beware of arithmetic right shift, take 5

http://hg.mozilla.org/mozilla-central/rev/e31957c56d36

But I forgot to ask for approval! Sorry!
Attachment #461677 - Flags: approval2.0?
Status: NEW → RESOLVED
Closed: 14 years ago
Resolution: --- → FIXED
blocking2.0: --- → betaN+
Attachment #461677 - Flags: approval2.0?
Assignee: nobody → bjacob
You need to log in before you can comment on or make changes to this bug.

Attachment

General

Created:
Updated:
Size: