diff options
author | JosiahWI <41302989+JosiahWI@users.noreply.github.com> | 2022-06-03 19:51:58 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-06-03 20:51:58 -0400 |
commit | 8e5bd82c4d19c405fbb4f2592bf91ad8b110294b (patch) | |
tree | 62121dbae3e3d9da5578de10d2adf06143dcae10 /src/mapgen | |
parent | 575caa8015fe420ce5e709d6c137036dfc0262ef (diff) | |
download | minetest-8e5bd82c4d19c405fbb4f2592bf91ad8b110294b.tar.gz minetest-8e5bd82c4d19c405fbb4f2592bf91ad8b110294b.tar.bz2 minetest-8e5bd82c4d19c405fbb4f2592bf91ad8b110294b.zip |
fix integer overflow in mapgen (#11641)
* fix integer overflow in mapgen
Some calculations involving the magic seed had overflow because the result of an intermediate arithmetic step could not fit in an s32. By making the magic seed unsigned, the other operand in the equation will be cast to unsigned, and possibly other operands or intermediate operands. This will result in unexpected behavior if an operand is negative, which is technically possible, but logically should not happen.
* comment noise2d bitshift
While working through the code I was momentarily concerned that the right bitshift in noise2d could fill ones in some cases. It turns out that with signed integers, this is indeed true, but this one is shifting an unsigned integer, so the behavior is as expected. I put a comment here to clarify this, in case someone else wonders the same thing down the line.
* noise2d and noise3d unittests
I have added 3 tests each for noise2d and noise3d, testing all zero inputs, a very large seed (case which caused UB in the old implementation) and some fun primes I picked for no particular reason. This should be sufficient to demonstrate that the behavior of the new implementation has not changed. I used uniform initialization because it is a good feature of C++11. Please do not explode.
* uncomment the noise2d bitshift
This reverts commit 583b77ee9f1ad6bb77340ebb5ba51eb9a88ff51c. It's a
well-defined language semantic; it doesn't need to be commented.
* code cleanliness
Diffstat (limited to 'src/mapgen')
-rw-r--r-- | src/mapgen/mapgen.cpp | 3 |
1 files changed, 2 insertions, 1 deletions
diff --git a/src/mapgen/mapgen.cpp b/src/mapgen/mapgen.cpp index d767bd264..1f2ac491e 100644 --- a/src/mapgen/mapgen.cpp +++ b/src/mapgen/mapgen.cpp @@ -238,7 +238,8 @@ u32 Mapgen::getBlockSeed(v3s16 p, s32 seed) u32 Mapgen::getBlockSeed2(v3s16 p, s32 seed) { - u32 n = 1619 * p.X + 31337 * p.Y + 52591 * p.Z + 1013 * seed; + // Multiply by unsigned number to avoid signed overflow (UB) + u32 n = 1619U * p.X + 31337U * p.Y + 52591U * p.Z + 1013U * seed; n = (n >> 13) ^ n; return (n * (n * n * 60493 + 19990303) + 1376312589); } |