175 points · by ingve · 8y ago · 184 comments
That would allow cleanup and other such actions without resorting to such hacks as: "goto cleanup" pattern, separate functions, fake for loop to break out of, ...
It would be nice to have this be a part of the standard.
You can do it in the 20-year-old version of it, and draft versions many years before that.
Edit: Ah, I see; you're more worried about them turning C into the next C++ :) I might even agree some days.
/**
* GCC and Clang extension to call cleanup function at exit
* from the function with pointer to given function as argument.
*/
#define defer(func) __attribute__((cleanup(func)))
#ifdef _CRUST_TESTS
// Sample destructor, to test defer
static void _tst_charp_destroy(char * * value) {
if(*value) {
free(*value);
*value = NULL;
}
}
// Test case
it(defer, "must deallocate object at the end of the function") {
defer(_tst_charp_destroy) char * s = calloc(1, sizeof(char));
(void)s;
}
#endifD has scope(exit){...} which is similar to constructs like defer {...}
Many things can be done in some form with macros and the C11 generic keyword if they have to be, but defering statements to run on scope exit is still elusive as something that can be relied upon.
The issue with cleanup on scope exit is that this introduces ambiguous code-flows. You would need to demonstrate a strong advantage, beyond making life easier for the writer of the code.
EDIT: Sorry for the confusion, I misread the article and thought this was about C++2x.
If they would add that feature, you could use macros to get constructor and destructor like behavior (as long as it's within the same scope, you could write a macro that constructs your object, and in addition contains something like "at scope exit: run this function"), which would be super useful and as far as I'm aware not very complex for the compiler (as all they have to do is run some code whenever exiting scope) nor very far outside of the spirit of C (it's still very low level, just a small convenience feature with interesting implications, especially when used with macros).
It is the result of starting with C, and then accommodating a massive, sustained sequence of feature requests, exactly like ones we are seeing in this thread.
Everyone thinks that if just their pet feature request is added to C and everyone else's ideas are rejected, it will still be C.
But then you also want templates of course to get rid of your void*. And oh, wait, what's that? A cross-platform thread implementation (well, sort of, depends on platform)? A string thing which I can search without strstr? Anonymous functions which capture? Auto? Gimme gimme :]
https://stackoverflow.com/questions/2053029/how-exactly-does...
But who are we to ask..? Just programmers, i.e. mere mortals nobody really cares about. :-)
https://www.boost.org/doc/libs/release/libs/scope_exit/doc/h...
// WTFPL
class Finally {
std::function<void()> f;
public:
Finally(std::function<void()> f) : f{f} {}
~Finally() {f();}
void disable() { f = [](){}; }
};
Which looks much prettier: socket* s = open_socket(); // or whatever
Finally cleanup_socket{[](){ close_socket(s);}};
// optionally, to keep it alive:
cleanup_socket.disable();
Am typing on mobile. No guarantees about syntax errors. I still need to look into where the right places to put r value references and/or std::move are, but for the most part, I never put anything other than a pointer in the closure so I'm not worried about copy constructor cost.I disagree.
> to run code when leaving a scope, no matter how you leave
This, and various other features, were already added to C long ago. The resulting dialect was called C++.
Are you implying that people who want new features in C should just migrate to C++ because it has even more features? Or that C is perfect as-is and anyone who wants to add new features to it should bug off to another language? Or that this particular feature is somehow equivalent to (or a slippery slope toward) adding a whole set of OOP features to C, so we might as well take that to its logical conclusion?
C is a great language, and I love working with it. But constexpr is something I really feel would improve the language (by eliminating the need for complicated #define macros). C++14's constexpr was a breath of fresh air when I first used it. It basically lets me write real code which evaluates at compile-time and can generate constants. I'd love to see constexpr ported over to C.
Fernando Boretti: https://github.com/eudoxia0/cmacro
Looking forward to this one, specially since Annex K ( Bounds Checking Interfaces) has proven to have not solved anything and is now scheduled for possible removal.
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1969.htm#ad...
These other ones are also interesting from security point of view.
> Add a new calling conventions with error return for library functions that avoids the use of errno
> Extend specifications for enum types
> Add a simple specification of nullptr, similar to C++
It has solved the usual bounds errors on those who use it. I.e MS, Embarcadero and safeclib. Since glibc, musl and freebsd libc refuse to use the Annex K it's easy to blame just them, not the safe extension, which do serve their goal.
With safeclib you even get compile-time checks, more than with the simple _FORTIFY_SOURCE=2 checks. Only Android Bionic got a bit better lately. safeclib is as fast or even faster than the fragile assembler bits in glibc.
> Add a new calling conventions with error return for library functions that avoids the use of errno
That's of course part of Annex K.
What's urgently missing is still a proper string API. ASCII str* goes nowhere, wide char wcs* is not widely used, 80% use utf8. wcslwr, wcsfc, wcsnorm are even missing. The whole u8* string API is missing, and not even discussed. ICU, libutf8 and libunistring don't get you far. coreutils still cannot handle non-ASCII strings.
A situation which is described on the field report I linked to.
Only C++ compilers like Visual C++ which provide overloaded versions of Annex K without size parameter thanks to the improved C++ type system, do actually provide a real usable version of Annex K.
But then it isn't C anylonger.
That's wrong, check the implementation.
C++ only has advantages because there g++ is not as broken as gcc with constexpr, but clang since 5.0 is doing fine.
Since this as a whole is among the least consistently implemented and (arguably based on the number of questions it generates) least well understood aspects of the standard it's nice to see some authoritative efforts to clarify the intended behaviors.
As in a standard alloca?
Not sure about the Small C dialect from early 80's.
https://gustedt.wordpress.com/2016/08/17/effective-types-and...
arc4random is in complete POSIX limbo as far as I can tell. First started as a rename to posix_random[1] and then OpenBSD slammed the door shut by withdrawing it and now we're at risk of getting the worst of both worlds with Linux's getrandom[2].
This alone will make C incompatible with its original platform, PDP/11 where char is either 7 or 9 bits.
C didn't run on the PDP-7.
Being either 7-bit or 9-bit would be a choice for 36-bit hardware. Wikipedia's list of 36-bit hardware is: MIT Lincoln Laboratory TX-2, the IBM 701/704/709/7090/7094, the UNIVAC 1103/1103A/1105 and 1100/2200 series, the General Electric GE-600/Honeywell 6000, the Digital Equipment Corporation PDP-6/PDP-10 (as used in the DECsystem-10/DECSYSTEM-20), and the Symbolics 3600 series.
Truncation can cause security bugs, and it is generally awful behavior. There is no silver bullet here: the programmer must not be a dummy about buffer sizes. Pretending otherwise is unhelpful.
Even better (someone please correct me if necessary) why isn't the very concept of "undefined behavior" completely removed? What good does it accomplish in a language?
You mean CHAR_BIT==8 as mandated by POSIX?
1. CHAR_BITS == 8, and
2. the compiler is required to make uint8_t an alias of unsigned char.
Point 2 is there so that you can cast to uint8_t safely, which some cryptographic code tends to rely on. If uint8_t is just any integer type, there's no safe cast to uint8_t due to strict aliasing rules[1]. That's what I want to fix. CHAR_BITS == 8 if uint8_t exists is just a collateral.
[1] https://cellperformance.beyond3d.com/articles/2006/06/unders...
Both are fine. For modern code with no global state, especially the multithreaded kind, everything is better than the errno.h mess.
In fact there's a Charter describing it better than I can:
Now, how do those error-related proposals violate it? Such as:
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2289.pdf
It seems to be very delicate about being backwards-compatible.
errno.h isn't so much builtin to C. It's just part of the standard libary, and more so of POSIX. It's only used for interfacing with the OS. And it's not that bad, since errno is a thread local variable.
Yes, errors are just data. And everything is data, including the code itself, right? It a question of abstractions introduced to the language and the program at question.
errno.h is bad. It's inconvenient, it's global, even if it's a thread-local something, it's cumbersome to use.
AFAIK, there are 2 error-related proposals for inclusion. One is making errors special, the other is a bit more generic. Both would improve on the current situation.
> It a question of abstractions introduced to the language and the program at question.
I don't think these kind of abstractions are in the spirit of C. As it says in the Charter linked here, "provide only one way to do an operation".
A more acceptable way to me would be allowing multiple return values in general. But maybe there are technical reasons why this is not done. Or it has to do with the complexities that such a mechanism would add to the expression syntax.
You cannot take sizeof a function, and you can't copy functions around, for instance. The address of a function is a value ("data"), but not the function itself.
I do like how Go does the posix interface where errors are handled as multiple return statements and cleanups using defer.
I mean, security trumps convenience and uptime, right guys? Y'all do build your functions with domain and range in mind, right guys?
It is not used for reporting. Rather, various functions in C and POSIX return an indication that some exceptional situation has occurred. Then errno holds a value which classifies the cause of that situation. It doesn't report the error.
(In the case of portable ISO C, we can't even depend on that; we must set errno to zero before calling most library functions. If that function fails, then if errno is nonzero, it has a value pertaining to that function.)
Some newer functions in POSIX return the errno value, like pthread_mutex_lock. That makes sense when the return value has no other purpose like "bytes processed" or whatever. The errno values are positive, so they combine poorly with in-band signaling.
Anyway, optimizing is possible based on the return value: like putting the expected success case into the hot code path or whatever.
It's just a macro for a function like:
#define errno (*__get_errno_location())
This is equivalent to having getter-setter functions, like in Microsoft's Win32 API, which has GetLastError and SetLastError.Does anyone have more information about this proposal?
C actually comes pre-equipped in a pretty nice position with its default 8 bit char data type (which is perfect for UTF-8).
The POSIX standard however, I agree is in serious need of an overhaul for locale features and you‘re probably better off ignoring it completely and just going ICU these days anyways - though then you have to go the extra length to still use the OS provided means (LC_* env under Unix) to get to the user‘s preferred locale.
But once you have that, yeah, ICU is probably the way to go for actual string formatting.
The reason there is a "standard library" is to make portability possible.
they're proposing to add u8 as a character constant prefix.
There are C++2x proposals to add a green thread/goroutine style mechanism. I'm not convinced that it's something which belongs in the C core language or C standard library though.