7 ms·
Perfecting GLFW for Zig, and finding lurking undefined behavior that went unnot
- losvedir 5y agoCan anyone provide some context? I don't know what GLFW is, and the blog post doesn't really explain. From Googling, I see what it is now, but I don't really have a sense of how important GLFW bindings are. Is this very niche? Or, like is this a major contribution to game development? For that matter, is this mainly going to help Zig game developers, or is this a bit of tooling for everyone, kind of like zig cc?
- slimsag 5y agoAuthor here, sorry for the missing context. GLFW is very popular among game developers for opening graphics windows in a cross-platform way. This helps just Zig game developers for now, it's not a major contribution to game development (though I hope other things I do with Mach engine in the future will be.) I do think with some minor tweaks this could be used to make bindings for GLFW in other languages easier to install, e.g. by just requiring `zig`, but I haven't done that here.
- losvedir 5y agoThanks! No need to apologize, I'm not in your target audience, and that's fine. Was just curious, is all.
- hsn915 5y agoglfw is very widely known because it's usually one of the recommended libraries to use when starting out graphics programming. It basically a cross platform library to create a window and initialize an opengl context .. or something like that. (It's been _many_ years since I last used it).
- iamcreasy 5y agoIs it safe to say that SDL is a strict superset of GLFW?
- slimsag 5y agoI think that is a reasonable statement. SDL includes other functionality like image loading, audio, etc. whereas GLFW is primarily focused just with getting a window with a graphics context for OpenGL/Vulkan/etc set up.
- cyber_kinetist 5y agoSDL’s advantage is that it supports more platforms (like mobile and Switch), and is much more battle-tested with hundreds of games using it, including Valve’s ones. Many people seem to use SDL for only windowing and input and seem okay with it.
- bmitc 5y agoThis documentation has a good description of capabilities of it and alternatives. https://www.khronos.org/opengl/wiki/Related_toolkits_and_APIs#Context.2FWindow_Toolkits https://www.khronos.org/opengl/wiki/Related_toolkits_and_API...
- abainbridge 5y agoThe article discusses some undefined behaviour resulting from shifting an unsigned char left by 24 places. Any idea why the compiler wasn't warning about that? It seems like it would be easy to implement that warning in the compiler. I feel that I'm missing something.
- quag 5y agoThat’s the point made at the end of the article. The compiler check does exist, but because it isn’t defaulted to on, no body in 6 years use it. Zig has the checks on by default, so the first time someone used it, they found and fixed it for everyone. > Anybody using GLFW could have enabled UBSan in their C compiler. Anybody could have run into this same crash and debugged it in the last 6 years. But they didn’t. Only because Zig has good defaults, because it places so much emphasis on things being right out of the box, and because there is such an emphasis on having safety checks for undefined behavior - were we able to catch this undefined behavior that went unnoticed in GLFW for the last 6 years.
- seba_dos1 5y agoI have fixed similar issues in Allegro and SDL (which are libraries that cover a superset of GLFW's scope) because I do use UBSan in my projects. Unfortunately, I haven't used GLFW in any project yet, so I couldn't fix this one :) (the point on good defaults stays valid though)
- abainbridge 5y agoI was expecting a compile time warning and thought ubsan shouldn't be necessary. But CUViper explains why the UB can only be caught at runtime.
- dundarious 5y agoInteger promotion happening is known at compile time, so it’s still a fair point to expect a compile time warning.
- fyrn- 5y agoI've actually found this bug before, but since I've been stuck on a six years out of date version of GLFW, I assumed it had been fixed and just wrote a ticket to update GLFW. It was wild to see this in my feed today!
- ncmncm 5y agotl;dr: Glfw is a library used most often by beginners learning graphics programming [but also in production systems]. A bit of code in that library shifts a char value c left by 24 places, yielding a 32-bit int value. If the top bit of the char (c & 0x80) is 1, that shifts it into the sign bit of the int, changing its sign, which is Undefined Behavior, and the compiler is free to do anything, including both what you wanted, and crashing. Compiling with "undefined behavior sanitizer" on, as Zig does by default, traps the event, causing the requested crash. Building without sanitization, nothing notices, and everything "just works". A simple way to fix this would be to shift [wrong: c by 24u, "(c << 24u)"][right: "(unsigned(c) << 24)"], eliminating the Undefined Behavior while producing an identical instruction sequence, and all would be well. Among permitted behaviors is launching missiles and just not even executing. In this case the compiler was not able to prove that a char value with the high bit set certainly would or certainly could not appear in that context. If it could prove it could not, then there would be no UB and everything would be fine. If it could prove such a value would appear, then it would consider itself justified in deleting all the code both after and leading up to the misuse, back to the point where a choice determined whether to enter the erroneous bit, and also the code making the choice, and likely the code that computes the value used in making the choice. Perhaps surprisingly, this happens all the time and makes our programs smaller and faster than they would be otherwise. Still, people often complain about it. If your testing does not exercise the code path that was deleted, then even with the UB sanitizer turned on, you might not notice that the compiler would have, without, chosen to delete that code. But deleting it is more likely to get your mistake noticed. The most common source of this particular brand of UB is multiplying int values where the product does not properly fit in an int result. (Even Rust allows this, although it can be persuaded to trap misuses, with some care.) You might be tempted to do all your multiplications with unsigned ints, but you do not really get better results that way; often that just makes it even harder to find mistakes.
- jchw 5y agoIt should be made clear that glfw is also used by production software as well; I’ve spotted it in games, and also my terminal emulator of choice (kitty.) It is often a reasonable alternative to SDL if you just want to get a window with an OpenGL or Vulkan context and don’t need many of the other features SDL offers.
- secondcoming 5y agoI enabled ubsan on a local build of our code. It found some issues, but good god the build time was atrocious! I doubt it's something you could enable on a CI pipeline.
- wffurr 5y agoWe run sanitizers nightly, but not as part of presubmit checks. It strikes a good balance between productivity and safety.
- vlovich123 5y agoI’ve always run sanitized builds as presubmit without any meaningful issue. It’s always nicer to have these issues caught before code gets merged into a shared repo. The long part of things is code review anyway so waiting on a build isn’t the biggest deal in the world.
- wffurr 5y agoThat's great if it's fast enough. For some builds, like the GP and mine, it's extremely slow.
- vlovich123 5y agoMy point is I've run really big builds (i.e. taking about an hour to build non-sanitized) & we still did sanitized builds pre-submit. How big is the disparity you're seeing between sanitized & non-sanitized builds?
- wffurr 5y agoAn hour, ouch. That's pretty long. We try to keep our presubmit under 10 minutes, and that's already frustrating. I can't figure out how to dig the numbers out of our CI infrastructure for the nightly sanitizer runs.
- daneel_w 5y ago"The GLFW code is pretty popular, and it’s been around for 6 years." More than 15 years, in fact. I contributed a few changes to the OS X side back in 2005.
- setr 5y agoI think he meant 6 years is that function was introduced
- david2ndaccount 5y agoYet another example of unnecessary undefined behavior in C as a consequence of needing to run on dead hardware. Bit shifting should clearly be defined to be operating on the underlying bits, with the resulting value being whatever that bit pattern would be on the target architecture.
- justincormack 5y ago“Whatever that bit pattern would be on the target architecture” is the original understanding of undefined.
- eximius 5y agoZig, Rust, and (as much as I hate it) WASM seem to be doing magical things for several years running.
- travisgriggs 5y agoSeems like a cool project and kudos to the authors attentions to detail. These lines tickled my Bone of Irony: > No installing apt packages. No dealing with missing header errors. It should just work out-of-the-box, and for every platform I think it’s interesting/ironic because at some point the layers of header files were pitched as a way of making things more modular and better. A means of simplifying. Aptitude was meant to do the same thing. Simplify a process that was formerly seen as icky and complicated. The author could have just as well mentioned just about any other software install/deploy/configure technology. In the end it always seems that yesteryears “it makes things easier” is eventually derided and replaced with a some new simple straightforward mechanism. As whatever the new approach is, scales in time and application, it takes the place of what it derided and becomes the new derided. One big merry go round.
- AndyKelley 5y agoThere is a key difference here- if your build instructions include "install this package using apt" then you are limiting your developers to using Ubuntu or Debian, and even then limiting it to a particular version range within those distros. If your build instructions are "zig build" then that works for everyone, on every platform: Windows, macOS, Linux (all distros!), FreeBSD, etc., and it works for all versions of them.
- saagarjha 5y agoI mean, the build instructions could also say "install this package" and then you install it however your distribution does it.
- user-the-name 5y agoInstalling a package to build some code is just fundamentally wrong, though. Why am I making unspecified, permanent changes to my underlying operating system in order to build a random piece of code? That just make no sense, and it is insane that this is the standard way of doing things.
- flohofwoe 5y agoA little while ago I tinkered a bit with automatically generating "more idiomatic" language bindings from C-APIs by parsing the AST-dump output of C headers from Clang (a better approach would be to use libclang I guess, but the JSON AST dump is good enough for simple C headers). The parsed AST information is then further processed by a language-specific script which replaces some "C-isms" with target-language concepts (things like replacing pointer/size pair structs with target-language-slices). This could be further helped by custom annotations on the C-API, but so far I'm just looking for special type name patterns in the C headers. IME making C-APIs "binding friendly" even helps with making the C API a bit safer (for instance by providing a size to each data pointer). Anyway... currently it's good enough to automatically generate Zig bindings for my Sokol libraries, but I think with a bit more work a more robust and universal tool could be created with essentially does the same thing but more flexible. Microsoft is doing something similar now to expose the Windows APIs to C++ and Rust, but as far as I have seen this is on a whole different complexity level than my handful of python scripts ;) Here's a bit more detailed information: https://floooh.github.io/2020/08/23/sokol-bindgen.html https://floooh.github.io/2020/08/23/sokol-bindgen.html
- phendrenad2 5y ago> the left operand, which starts out as unsigned char, will get promoted to int This is a big flaw in C. Quietly promoting an unsigned type to a signed type, simply because it was added to by a signed number? And that signed number is deterministically known to be > 0? C has major problems like this, you don't even need to look to UB to run into them. I think mixing signed and unsigned values should always give you a stern warning, explaining the pitfalls, and yet (a) the warning you get is some useless Chernobyl error light like "mixing signed and unsigned values" and (b) that warning is probably not enabled easily, without bringing in lots of stupid warnings too.