Lurker News
Hi HN,

We are members of the C Standard Committee and associated C experts, who have collaborated on a new book called Effective C, which was discussed recently here: https://news.ycombinator.com/item?id=22716068. After that thread, dang invited me to do an AMA and I invited my colleagues so we upgraded it to an AUA. Ask us about C programming, the C Standard or C standardization, undefined Behavior, and anything C-related!
The book is still forthcoming, but it's available for pre-order and early access from No Starch Press: https://nostarch.com/Effective_C.
Here's who we are:
rseacord - Robert C. Seacord is a Technical Director at NCC Group, and author of the new book by No Starch Press “Effective C: An Introduction to Professional C Programming” and C Standards Committee (WG14) Expert.
AaronBallman - Aaron Ballman is a compiler frontend engineer for GrammaTech, Inc. and works primarily on the static analysis tool, CodeSonar. He is also a frontend maintainer for Clang, a popular open source compiler for C, C++, and other languages. Aaron is an expert for the JTC1/SC22/WG14 C programming language and JTC1/SC22/WG21 C++ programming language standards committees and is a chapter author for Effective C.
msebor - Martin Sebor is Principal Engineer at Red Hat and expert for the JTC1/SC22/WG14 C programming language and JTC1/SC22/WG21 C++ programming language standards committees and the official Technical Reviewer for Effective C.
DougGwyn - Douglas Gwyn is Emeritus at US Army Research Laboratory and Member Emeritus for the JTC1/SC22/WG14 C programming language and a major contributor to Effective C.
pascal_cuoq - Pascal Cuoq is the Chief Scientist at TrustInSoft and co-inventor of the Frama-C technology. Pascal was a reviewer for Effective C and author of a foreword part.
NickDunn - Nick Dunn is a Principal Security Consultant at NCC Group, ethical hacker, software security tester, code reviewer, and major contributor to Effective C.
Fire away with your questions and comments about C!

Comments (962) 182 threads

Show all comments

Showing thread 4 of 182

rwmj2 replies#
Not a question, a request: Please make __attribute__((cleanup)) or the equivalent feature part of the next C standard.

It's used by a lot of current software in Linux, notably systemd and glib2. It solves a major headache with C error handling elegantly. Most compilers already support it internally (since it's required by C++). It has predictable effects, and no impact on performance when not used. It cannot be implemented without help from the compiler.

AaronBallman2 replies#
Funny you should mention that, as that feature has come up recently in mailing list discussions. We have not seen an actual proposal for adopting it yet, but features similar semantics are being discussed as a possible idea (no promises).

FWIW, I don't think it would wind up being spelled with attribute syntax because we would likely want programmers to have a guarantee that the cleanup will happen (and attributes can be ignored by the implementation).

eqvinox#
Hopefully it'd at least be syntactically similar, so we can have an

  #ifdef __STDC_CLEANUP__
  #define my_cleanup(func) stdc_cleanup(func)
  #else
  #define my_cleanup(func) __attribute__((cleanup(func)))
  #endif
i.e. it would require that it at least goes in the same places as an attribute.
rwmj2 replies#
I believe the last proposal was in 2008 (ignore the try..finally stuff here): http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1298.pdf

So I guess it needs someone to take that and update it, also to pull up a full list of current Linux software which is using this feature (which as I say these days is a surprising amount).

eqvinox1 reply#
Here's our usage: https://github.com/FRRouting/frr/blob/master/lib/privs.h#L14...

  #define frr_with_privs(privs)                                                  \
          for (struct zebra_privs_t *_once = NULL,                               \
                                    *_privs __attribute__(                       \
                                            (unused, cleanup(_zprivs_lower))) =  \
                                            _zprivs_raise(privs, __func__);      \
               _once == NULL; _once = (void *)1)
This gives us a block construct that guarantees elevated privileges are dropped when the block is done:

  frr_with_privs(privs) {
    ... whatever ...
    break;  /* exit block, drop privileges */
    return; /* return, drop privileges */
  }

Continue this thread — 1 reply

loeg#
We use it extensively in our proprietary codebases as well, FWIW. Not real open data for me to point to, but: a few million lines of C, and a handful of billion USD in revenue. If that helps weigh in on "yes, please standardize this common practice."
rseacord4 replies#
My idea was to add something like the GoLang defer statement to C (as a function with some special compiler magic). The following is an example of how such a function could be used to cleanup allocated resources regardless of how a function returned:

  int do_something(void) {
    FILE *file1, *file2;
    object_t *obj;
    file1 = fopen("a_file", "w");
    if (file1 == NULL) {
      return -1;
    }
    defer(fclose, file1);

    file2 = fopen("another_file", "w");
    if (file2 == NULL) {
      return -1;
    }
    defer(fclose, file2);

    obj = malloc(sizeof(object_t));
    if (obj == NULL) {
      return -1;
    }
    // Operate on allocated resources
    // Clean up everything
    free(obj);  // this could be deferred too, I suppose, for symmetry

    return 0;
  }
eqvinox#
Cleanup on function return is not enough, it needs to be scope exit. We're using this for privilege raising/dropping (example posted above) and also mutex acquisition/release. Both of these really "want" it on the scope level.
rwmj1 reply#
Golang gets this wrong. It should be scope-level not function-level (or perhaps there should be two different types, but I have never personally had a need for a function-level cleanup).

Edit: Also please review how attribute cleanup is used by existing C code before jumping into proposals. If something is added to C2x which is inconsistent with what existing code is already doing widely, then it's no help to anyone.

rseacord2 replies#
Yes, we have discussed adding this feature at scope level. A not entirely serious proposal was to implement it as follows:

  #define DEFER(a, b, c)  \
     for (bool _flag = true; _flag; _flag = false) \
     for (a; _flag && (b); c, _flag = false)

  int fun() {
     DEFER(FILE *f1 = fopen(...), (NULL != f1), mfclose(f1)) {
       DEFER(FILE *f2 = fopen(...), (NULL != f2), mfclose(f2)) {
         DEFER(FILE *f3 = fopen(...), (NULL != f3), mfclose(f3)) {
             ... do something ...
         }
       }
     }
  }
We are also looking at the attribute cleanup. Sounds like you should be involved in developing this proposal?

Continue this thread — 2 replies

rwmj1 reply#
That's quite an achievement, but you've got to realise that hacks which overwrite the stack return address are not maintainable and likely wouldn't work except for a narrow range of compilers (and even specific versions of those compilers with specific options). It also won't work with stack hardening.

Also it's function-level (like golang) not scope-level (like attribute cleanup). As argued elsewhere in the this thread, golang got this wrong.
Also also, overwriting the return address on the stack kills internal CPU optimizations that both Intel and AMD do for branch prediction.

Continue this thread — 1 reply

nrclark#
Would it make sense for defer to operate on a scope-block, sort of like an if/do/while/for block instead?

That would allow us to write:

   defer close(file);
or:

   defer {
      release_hardware();
      close(port);
   }
I feel like that syntax fits very nicely with other parts of C, and could even potentially lend itself well to some very subtle/creative uses.

I feel like a very C-like defer would:

   - Trigger at the exit of the scope-level where it was declared.

   - Be able to defer a single statement, or a scope-block.

   - Be nestable, since a defer statement just runs its target
     scope-block at the exit of the scope-block where it's defined.

   - Run successive defer statements in LIFO order, allowing later
     defer statements to still use resources that will be cleaned up
     by the earlier ones.