Skip to content

ICU-23615 class Length32 checks for int32_t overflows - #4396

Draft
markusicu wants to merge 11 commits into
unicode-org:mainfrom
markusicu:Length32
Draft

markusicu wants to merge 11 commits into
unicode-org:mainfrom
markusicu:Length32

Conversation

@markusicu

Copy link
Copy Markdown
Member

Draft: Please comment on the shape of the new class and its call sites.

New internal class Length32:

  • simple value class holds a non-negative int32_t string length or similar
  • also holds a reference to the caller's UErrorCode for easy ICU error propagation
  • addition and multiplication operators as needed

The common-library code is changed to use Length32 instead of C-style functions.

  • Call sites that set an error become more readable
    • Note that we do not always set the same error code
  • Call sites that do not set an error need a localErrorCode
    • Not sure what to do about this without creating yet another value class that just sets the value to 0 but does not carry a UErrorCode reference
    • Some of these call sites report an error by other means (e.g., UnicodeString.setToBogus())
    • Some of these call sites work well with a zero value if an overflow occurs
      • Should I add such a class? Length32OrZero? With an isBogus() flag to cover the other no-error call sites?

Checklist

  • Required: Issue filed: ICU-23615
  • Required: The PR title must be prefixed with a JIRA Issue number. Example: "ICU-NNNNN Fix xyz"
  • Required: Each commit message must be prefixed with a JIRA Issue number. Example: "ICU-NNNNN Fix xyz"
  • Issue accepted (done by Technical Committee after discussion)
  • Tests included, if applicable
  • API docs and/or User Guide docs changed or added, if applicable
  • Approver: Feel free to merge on my behalf

@FrankYFTang

Copy link
Copy Markdown
Contributor

need to fix the build first. Generally speaking, reasonable.

Comment thread icu4c/source/common/putilimp.h Resolved
Comment thread icu4c/source/common/putilimp.h Outdated
bool isFailure() const { return U_FAILURE(errorCode_); }

// TODO: un-inline
Length32 operator+(int32_t b) const {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You also need the int32_t + Length32 operator (which cannot be a member, so usually for the binary operators make neither a member).

I think currently, std::numeric_limits<int32_t>::max() + Length32(1, ec) would compile, but result in an unchecked (and undefined) addition via the implicit conversion to int32_t.

Add a test for that, and then fix it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Understood.
However, I would prefer to keep this simple, and not implement what we are not likely to need.

Idea: I could turn the int32_t conversion operator into an explicit getter. Call sites would need to call .get(), which is slightly less nice, but because the object doesn't automatically decay into a plain integer, we don't accidentally get bad behavior when we haven't overloaded some operator.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer simple for the user (so something that actually behaves like an integer, without having to .get() or think about which way an addition or multiplication needs to be written) over simple for the author.

I can help with writing the operators if you want, I have been writing C++ operators as a hobby for the past twelve years: https://github.com/search?q=repo%3Amockingbirdnest%2FPrincipia+%22operator%2B%22&type=code.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I much prefer the simple solution here, and the very minor inconvenience of having to .get(), rather than a complex, custom value type where we have to implement all kinds of unnecessary operators just in case someone were to use them.

You can see now what this looks like.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can see now what this looks like.

Worse, and less safe (you have moved an operation from an increment of the checked integer to an increment of the unchecked integer).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is something with all the binary operator+s in its API for all integers, all the constructors, but only one implementation of the addition and only one implementation of the overflow checking logic.

Doing this comprehensively just takes less code than having this partial pile of overloads.

https://godbolt.org/z/E1h9Kq68r

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Missing the positivity check, but you get the idea.)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, thanks.
I replaced overloads with templates.

Your code does not deal with a few things:

  • does not check for non-negative, as you noted
  • operator+() takes two Length32's but does not propagate the error code of both
  • you make the same mistake i did initially, and pass the source object's error code reference to the target
    • if the source uses its internal one, then the target must do so, too -- otherwise we get a dangling reference
    • thus, constructing a result object needs different code than constructing a fresh one

So I templatized, but I kept the simple member operators.
(I also fixed a bug: My previous operator code was writing to errorCode_ which could be the internal one, even though this is const =-)

Also, by auto-decaying to an int32_t, we still get all kinds of unchecked default operator implementations. This is why I want to keep .get().

@eggrobin eggrobin Nov 25, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, by auto-decaying to an int32_t, we still get all kinds of unchecked default operator implementations. This is why I want to keep .get().

This is good enough to replace the existing calls to uprv_add32_overflow on sizes, where it is clearly an improvement.

But if the goal is to use it all over the place to calm down the static analysers that keep complaining about overflows, it needs to behave a lot more uniformly like a checked numeric type, and so I would want deal with that by implementing the default operators in question.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My goal is to make overflow checks easier.

I assume that there is a somewhat limited set of places where we need to either deal with size_t lengths or allocate buffers with slop, or allocate buffers for appending/concatenating, etc. Clearly more places than we have been checking, but nothing like all of the integer operations in the library.

}
return {0, errorCode_};
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would expect to see at least operator- (both directions), operator--, operator+=, and operator*= (it is not unreasonable to subtract from a length, and we should then check that the result is nonnegative).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is an example (signed, so Length32 would not do, we would need some signed version of it) which would clearly benefit from +=:

bool DecimalQuantity::adjustMagnitude(int32_t delta) {
if (precision != 0) {
// i.e., scale += delta; origDelta += delta
bool overflow = uprv_add32_overflow(scale, delta, &scale);
overflow = uprv_add32_overflow(origDelta, delta, &origDelta) || overflow;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm. I had looked at the overflow checks in common, but not in i18n.

We can of course add more operators. What I don't want is having to add every possible numeric operator just to avoid the risk of a gap. I don't know how to do that if the object decays to a raw integer.

And signed... I like checking for non-negative for lengths and capacities.
Here, yes, we would need a signed type.
What are you thinking? Separate class? Template parameter? Runtime setter??

@eggrobin eggrobin Nov 25, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What are you thinking?

  1. That if we are going to do this in more than a dozen places (not just the places where we check now, the reason why we started talking about this and why you convinced yourself to do this is that we are getting pushed to check more), this needs to be fairly comprehensive.
  2. That we clearly need two types, signed and unsigned, because nonnegativity is a very common property to want to check, and because negative numbers nevertheless exist.
  3. That this then raises the question of the return type of operations: clearly a difference of positives can be negative, and a product of a positive with something signed is signed.
  4. That checked arithmetic with subtypes for positives is something that has been done already (http://www.ada-auth.org/standards/2yaarm/html/AA-3-5-4.html, http://www.ada-auth.org/standards/2yaarm/html/AA-4-5.html, http://www.ada-auth.org/standards/2yaarm/html/AA-A-1.html#p12), and that we should not reinvent this design piecemeal.
  5. That the operations whose values can be signed should return the signed type, that their sign should be checked on assignment to the unsigned type.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re .get()… I guess I can live with it, especially if we use this more and it starts propagating, marking the boundary may be OK. But commutative +, *, etc. seems like a requirement if we are going to use it widely.

Length32 + Length32 is probably also something that would then be needed; it is a bit distasteful because of the two error codes becoming one, but I suspect in practice they would both be the same and we can just pick one.

@markusicu markusicu Nov 25, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense.
Can we do this incrementally, adding features as needed?

Just looking at adjustMagnitude(), first thing is we need negatives.
Maybe add a template parameter to the class for whether it's non-negative?
And maybe spiffy typedefs for brevity?
Safe32<Type>, Length32=Safe32<NON_NEG>, Int32=Safe32<ANY> ...?

@eggrobin eggrobin Nov 25, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we do this incrementally, adding features as needed?

Yes, but I would like to keep the increments algebraically sensible, so that they are not an endless source of surprise (in particular, having n * 2 but not 2 * n seems user-hostile and harmful to readability; I notice you are flipping the arguments of an uprv_mul32_overflow when translating them to *, and the original order is the one I would have expected).

Certainly I would be fine with deferring multiplication of checked integers until we need it (let alone modulo and division).

In general when I implement operators, I follow these concepts, they are a good way of not forgetting something that would be expected to be there: https://github.com/mockingbirdnest/Principia/blob/7b84a16e0d5365f55990d455bd37b4be1ec975bb/base/algebra.hpp#L68. Some of this is application-specific (the whole homogeneous_meow stuff comes from physical quantities, though it applies to polynomials too), but perhaps it might inform us.

Note the asymmetry of affine; I am a lot less bothered about the lack of 1 + n than the lack of 2 * n.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And maybe spiffy typedefs for brevity?

Yes. We might templatize however we feel like in the implementation, but I would want callers to not know or care about it.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(I think one first increment is just the nonnegative type; once you start having that, you end up wanting quite a lot more operators, so it might make sense to leave it to a subsequent PR.)

Comment thread icu4c/source/common/putilimp.h Resolved

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants