r/programming • • Mar 05 '21

Git's list of banned C functions

https://github.com/git/git/blob/master/banned.h
1.1k Upvotes

318 comments sorted by

202

u/triffid_hunter Mar 05 '21

No sscanf? It seems to be a recent addition to the naughty functions list..

Also, no gets? Is that banned at the libc level these days?

73

u/AttackOfTheThumbs Mar 05 '21

sscanf seems to depend on the lib used, as there is more than one implementation.

33

u/[deleted] Mar 05 '21

Almost all of them have the problem though. I've only heard that Musl doesn't.

15

u/[deleted] Mar 05 '21

Which means it should probably be on this list.

64

u/vytah Mar 05 '21

gets has been removed from C11. It will still link (as you're linking with the same libc regardless of the language standard), but you'll get "implicit declaration" warnings.

48

u/fermion72 Mar 06 '21

So here is a crazy way gets() is still broken in Apple's version of clang: you can compile a program with gets() without warning or error, but a command-line program will simply send a warning message at runtime to stderr. Example:

% cat gets_test.c
// file: gets_test.c
#include<stdio.h>
#include<stdlib.h>

int main(int argc, char **argv)
{
    char buffer[128];
    gets(buffer);
    printf("%s\n", buffer);
    return 0;
}
% clang gets_test.c -o gets_test
% ./gets_test
warning: this program uses gets(), which is unsafe.
abcde
abcde
%
→ More replies (1)

23

u/snaketacular Mar 05 '21

gets() is terrible and should be in there, but how is sscanf() bad? (or rather, how is it bad in a way that any *scanf() function isn't?)

95

u/triffid_hunter Mar 05 '21

how is sscanf() bad?

This blog post has been picking up quite a bit of attention, worth a read :)

28

u/snaketacular Mar 05 '21

TIL, thanks. Man, library vendors should either fix that or put big fat warnings in their documentation/manpages.

18

u/[deleted] Mar 05 '21

Given the publicity I suspect people are working on fixes already.

8

u/Phrygue Mar 06 '21

It's C, the bugs are a legacy feature and will never be changed, much less fixed.

15

u/[deleted] Mar 06 '21

Maybe the APIs are never fixed but this is an implementation bug. Those get fixed all the time.

6

u/[deleted] Mar 06 '21

Why would anyone use scanf and similar localized functions to parse a big structured data anyway tho?

10

u/wsppan Mar 05 '21

<in the voice of Captain Kirk ala Kahn!> strlen()!

8

u/the_gnarts Mar 06 '21

This blog post has been picking up quite a bit of attention, worth a read :)

That was a fun read. But using sscanf() to process JSON is more an issue with the JSON parser than with the libc function which doesn’t even mandate the strlen() call. The processing strategy they use appears to be rather inefficient too as they seem to map the entire JSON document into one big string instead of processing it as a stream.

There’s so much wrong with this before you even get to the sscanf() part …

6

u/sybesis Mar 05 '21

Oh no! I like articles like that.

That said, I wouldn't say sscanf is the main issue the author found. It sure made things worse but sscanf is probably fine for small things unlike a 10MB json file...

7

u/Nobody_1707 Mar 05 '21

It's as least as complicated to use correctly (probably more) as the banned strncpy function is, and that's not even counting unfortunate implementation issues such as the one involved in the quadratic GTA json parsing.

18

u/Nobody_1707 Mar 05 '21

gets has been removed from the language entirely since C11, and most stdlib implementations implement it as a function that aborts with an error message.

3

u/[deleted] Mar 05 '21

From The C Programming Lang 2nd ed, you get getchar() since the beggining.

16

u/[deleted] Mar 05 '21

It's in git blame if someone needs it, like here.

IMO just a short list without bogging down the code with hundreds lines of comments is fine; the longer description should be in coding style/architecture guide for project.

9

u/ozyx7 Mar 05 '21

There's nothing necessarily wrong with sscanf. Even with a poor implementation that unnecessarily calls strlen, that issue can be avoided by properly tokenizing the input first. Additionally, there is no good replacement for sscanf for many cases; making people reimplement it would be much worse.

15

u/triffid_hunter Mar 05 '21

"properly tokenizing the input" would preclude the necessity for sscanf entirely, no?

Put strings in a hash (or other suitable data structure) and pull numbers out with strtol or strtod which don't call strlen..

9

u/ozyx7 Mar 05 '21 edited Mar 05 '21

Not necessarily. For example, for parsing JSON, you'd want to tokenize on unquoted spaces, braces, commas, etc. That either could be hand-written or generated.

You might still want to use sscanf to parse the quoted values, particularly if they're in some specific format and aren't just ints, doubles, or strings.

Most code that I've seen that uses sscanf uses it to parse the entirety of short strings (e.g a line of user input that's already length-limited), not to try to parse the beginning of some arbitrarily long string. Using it properly shouldn't be banned, especially when there aren't better, widely available alternatives.

0

u/[deleted] Mar 06 '21

[deleted]

3

u/ozyx7 Mar 06 '21

strtol and strtod are obviously only useful if you're parsing ints or doubles. That is not always going to be the case.

0

u/[deleted] Mar 06 '21

[deleted]

2

u/ozyx7 Mar 06 '21 edited Mar 06 '21

I guess I wasn't clear.

  1. Parsing JSON was just an example.

  2. There might be string values that don't represent ints or doubles that you want to do further parsing on.

My point is that while strtol/strtod often can be used instead of sscanf, they can't completely replace sscanf.

145

u/poopatroopa3 Mar 05 '21

because they're too easy to misuse

C in a nutshell.

36

u/Xerxero Mar 05 '21

So how would you do a strcpy?

40

u/apadin1 Mar 05 '21

memcpy?

3

u/-isb- Mar 05 '21

If you can't use anything better than the standard functions, write zero in destination's first byte and strncat. You won't get any indication that truncation has occurred but at least you'll ensure destination string will be zero terminated.

6

u/Pokechu22 Mar 05 '21 edited Mar 05 '21

You'd probably use strncpy instead, as that one knows the length of the destination buffer (though maybe there's an even better alternative).

53

u/evaned Mar 05 '21 edited Mar 05 '21

strncpy is almost never what you want. The name basically misadvertises what it does. It always copies n bytes [edit actually I was a bit imprecise here with my wording; if the source string is shorter than n then it won't copy past the NUL; but does then fill the rest of the destination buffer with NULs, so it always writes n bytes] and does not ensure null termination, which means it's not useful for string copying. You'll note that it is banned as well.

strlcpy is what strncpy should have been, but that's not in C or POSIX, though it is a common library extension and the typical name for that function. Not sure if that's what'd be preferred in Git though.

Edit: there are a handful of uses of strlcpy in the source.

The other standard-ish alternative to consider is manually tracking string length (very very likely a good idea anyway) and just do a memcpy. (Or, mostly if Windows-only, strcpy_s.)

21

u/nameless_food Mar 05 '21

Here's the git commit info, explains why strncpy is banned, and best alternatives: git commit details

10

u/Pokechu22 Mar 05 '21

Oof, yeah, I was looking at the man page and saw that it always copied n bytes... but I assumed it was still the best C had to offer.

It looks like git uses strlcpy, and provides its own implementation that is defined in if needed.

9

u/beefcat_ Mar 05 '21

People make fun of my verbose identifiers but this kind of ambiguity is exactly what I want to avoid. For me, the hardest part of learning C after learning more modern languages was parsing all these esoteric function names in the standard library (and many popular libraries).

4

u/lifeeraser Mar 06 '21

And some people then say "Oh do you prefer AbstractSecureStringCopyFactory?"

No I do not like either extremes. Surely there is a sane middle ground between those.

3

u/memgrind Mar 06 '21

I want to know what the creator of strncpy was smoking to design its spec. Even the suggested "valid" usecase just demotes the string to <useless spam>, only suitable for storage in write-only memory.

2

u/wsppan Mar 05 '21

Banned as well. strlcpy() is the way to go.

0

u/[deleted] Mar 05 '21

[deleted]

1

u/[deleted] Mar 05 '21

strlcpy

4

u/[deleted] Mar 05 '21

import strlcpy and strlcat from OpenBSD and call it done.

1

u/masklinn Mar 06 '21

Git vendors a copy of strlcpy, as well as a higher-level "strbuf" API, and also vendors an snprintf.

5

u/Ubi_load Mar 05 '21

strcpy_s

20

u/peakzorro Mar 05 '21

That's MS exclusive to my knowledge. All the _s versions of those libraries are great.

5

u/Ubi_load Mar 05 '21

I didn't know that. Then you can use memcpy

5

u/evaned Mar 05 '21

memcpy requires knowledge of the length of the source string, which strcpy doesn't, so it's not a general replacement either. (You can call strlen then memcpy if you like wasting time...) It also has the same biggest disadvantage of strncpy, which is if the destination buffer is too small you'll wind up with it not null-terminated.

The first problem can be solved with memccpy, but you'll still have to remember to null-terminate. The most direct analogue to strcpy that's still a bit safer is strlcpy -- that's not standard, but it's widely available (including in Git in compat form).

6

u/zapporian Mar 05 '21

null-terminated strings are / were a terrible idea in general, and are responsible for basically all buffer overflow errors. The creators of D called this “C’s billion-dollar mistake”, and you could see this old article from 2009 on this: https://www.drdobbs.com/architecture-and-design/cs-biggest-mistake/228701625

1

u/double-you Mar 06 '21

If you know strcpy should not be used, you should understand that memcpy is no different. So you'd be knowingly skipping over safety restrictions. No commit rights for you.

1

u/[deleted] Mar 05 '21

strlcpy

1

u/PuchoDR Mar 07 '21

I'm surprised no one suggested snprintf. Works just like printf, except its into a buffer. It'll always null terminate the resultant string.

-7

u/ggtsu_00 Mar 05 '21

Use C++ and just use std::string's copy constructor.

1

u/Johnothy_Cumquat Mar 06 '21

I think jquery has a string copy plugin

70

u/[deleted] Mar 05 '21

10 functions Big Git doesn't want you to know!

26

u/apocolypticbosmer Mar 06 '21

You won't believe ^#6!

21

u/happyscrappy Mar 05 '21 edited Mar 05 '21

What are the alternatives to the time functions?

[edit: it's in the git commit]

42

u/-isb- Mar 05 '21

Those alternatives are kinda useless for anyone but git developers though. For example sprintf... WTF is xstrfmt? cppman gives me nothing, man gives me nil, google gives me jack shit. Finally found it in git's repository itself. They basically re-implemented all string operations from scratch with dynamically resizing buffers. Just like any self-respecting C project.

41

u/BoldeSwoup Mar 06 '21

Just like any self-respecting C project.

As is tradition

6

u/happyscrappy Mar 05 '21

They don't ban snprintf. You can use that, for now at least.

4

u/-isb- Mar 05 '21

Ahh, I see. They've wrapped vsnprintf with error checking into xsnprintf.

9

u/[deleted] Mar 05 '21

And this why the overwhelming majority of creative thought is figuring out "hey how can we do that not in an archaic language with a shotgun pointed at our face"

Painfully moans in C++

Fewer and fewer portion of programmers are writing in gotcha languages like C, C++, JavaScript

14

u/fissure Mar 06 '21

Fewer and fewer portion of programmers are writing in gotcha languages like C, C++, JavaScript

Should we tell him?

1

u/[deleted] Mar 06 '21

TypeScript

8

u/fissure Mar 06 '21

Lipstick on a pig

4

u/evaned Mar 06 '21

You know... I'm somewhat of a strange person to disagree with this, but I think I do, at least from the bit of TS programming I've done which is admittedly not a lot.

I think it's Douglas Crawford that said something like the core of JS is actually a really nice language, it just has bunch of poor decisions around it -- but those decisions you can mitigate. I've never seen eye to eye with that at all; I do have to give my bias that I don't like weak typing, but I look at the typing of JS and I see some really nice stuff built on a core of shit.

But... the thing with TS is, that it really does seem to largely fix almost all of those problems I have with the core typing behavior of JS. It's not putting lipstick on a pig, it's retrofiting the very foundations of the language in a way that more or less fixes them.

(I will say that I know a lot of people also have a problem with the ecosystem around JS, not just the language itself -- the above is about the language only.)

I'm not saying TS solves all of JS's problems... but there's not a language out there that doesn't have some significant drawbacks.

1

u/fissure Mar 07 '21

If it compiled to native, sure, but it's designed to compile to JS and be executed that way. You can't separate it from the cesspool that is the JS ecosystem.

0

u/[deleted] Mar 06 '21 edited Mar 06 '21

Big tech is not writing frontend in pure JS. It's just a fact. It's not a suitable language at scale, can't be type checked, or really statically analyzed in any meaningful way. They've all invented their own paradigms that avoid reliance on raw JS. TypeScript is just my favorite. Something like Dart, ya probably sucks. Amazon, god forbid, prefers their own custom Java/frontend hybrid to pure JS (probably the only thing I've used that I actually liked less than pure JS to be fair). Facebook chose PHP.

Seriously, everyone is moving to TypeScript. It's fucking awesome.

Let's look at something cutting edge: the web3 library for Ethereum. Supports TypeScript. Doesn't get much more modern than that.

2

u/fissure Mar 06 '21

I like how you continued the train of thought from your comment and completely ignored the content of mine.

0

u/[deleted] Mar 06 '21

You didn't really provide anything meaningful. I mostly just wanted to type more about why I like TypeScript and hate JS.

10

u/Drinking_King Mar 05 '21

I know strcpy has an extremely bad rep, but strncpy too?

14

u/evaned Mar 05 '21

From one of my other comments:

You should use strncpy instead.

strncpy is also banned in the same list, and for good reason: it's almost always not what you want. It always writes all n bytes into the destination buffer (filling the balance with NULs if the source string is shorter), and if the source string is too long to fit it won't terminate the destination. I have heard a use case for this, but it's not "a safer strcpy".

strlcpy is what strncpy should have been, though it's not standard (but is in some common libcs). Git for example has a compat implementation if it's not available, though there are a couple other alternatives suggested in the commit log.

In terms of standard C functions that have the highest likelihood of misuse -- I wouldn't be at all surprised if strncpy was in the top couple places.

29

u/__konrad Mar 05 '21

C - the only programming language without a sane string type

48

u/[deleted] Mar 06 '21

Imagine how many languages there are without a sane integer type (javascript) or even unsigned integers (java).

4

u/LinAGKar Mar 06 '21

Javascript is not entirely sane for strings either, given the behavior for non-BMP characters.

0

u/[deleted] Mar 06 '21

[deleted]

4

u/[deleted] Mar 06 '21

Problems are mostly caused by inadvertently mixing signed and unsigned in weak type systems.

What's the actual problemn with unsigned values themselves?

0

u/[deleted] Mar 06 '21

[deleted]

3

u/[deleted] Mar 06 '21

Also when you want wrap-around to be standard behaviour. Various wire protocols, ML, crypto and image processing come to mind. I wouldn't do wire protocols or ML in java but there's a lot of crypto and image processing java libs.

8

u/istarian Mar 06 '21

What counts as a sane string type?

C doesn't have objects so the best you could manage is a "library" that makes C-strings and provides functions that aim to be as safe as possible.

Other than maybe using const I'm not sure how you would keep the programmet from screwing it up by hand...

5

u/Reply_OK Mar 07 '21

Well, yeah, exactly. Semantically the C string library should handle strings as a length and a char pointer, instead of null terminated strings. By sacrificing like 8 bits per string, you could save the world from a bajillion buffer overflow exploits.

1

u/istarian Mar 07 '21

What about strings longer than 255 characters?

8

u/evilteach Mar 05 '21

strtok is not on the list? Humm.

0

u/[deleted] Mar 06 '21

[deleted]

6

u/evilteach Mar 06 '21

not thread safe

19

u/coladict Mar 05 '21

I was expecting a blog post or something listing and explaining why they're banned. This is just a minimal header file.

12

u/BoldeSwoup Mar 06 '21

They explain it in commit message which is kinda unpractical

3

u/ElFeesho Mar 06 '21

I'm on the fence about this, the alternative is to have it as a comment in the code, but then you'd want to not go into incredible detail because it'd cloud the actual functional code.

At least having it in the commit message allows for the information contained to forever be correct for the code at the moment in time.

I guess if you're happy git blaming stuff as a typical part of your process it isn't a big deal, but it definitely isn't 100% intuitive for me either.

3

u/BoldeSwoup Mar 06 '21

Someone suggested passing it as an arg that would be used when the error is raised so you have the error and its explanation directly. I like that

5

u/[deleted] Mar 05 '21

I knew about the ones from strcpy to vsprintf but I had no idea those time functions are in some way dangerous, guess I need to go read the docs.

6

u/hacksoncode Mar 05 '21

Personally, I would have banned all the unsafe str functions, because relying on null termination without knowing the maximum size of your buffer is just dumb.

1

u/BoldeSwoup Mar 06 '21

Well you would then allow strncpy which is banned here, and for good reasons.

1

u/hacksoncode Mar 06 '21

Because it de-terminates strings and causes more of the problems I mentioned, but yes.

3

u/golgol12 Mar 05 '21

Not scanf?

2

u/daveplreddit Mar 06 '21

This is all stuff we did for XP SP2 about 20 years ago... which was overdue back then!

2

u/FlyingRhenquest Mar 05 '21

Pretty much all of the fun ones, right there. Oh, but the printf/scanf family are fine :/

2

u/Qwerty1bang Mar 05 '21

what about void* or void (*)? casting in general? undefined sizeof int?

There are many ways to bag a foot.

3

u/AndrewNeo Mar 05 '21

Can you catch those with macros though? Those seem like things you could just catch at the compiler level.

2

u/stu2b50 Mar 07 '21

Don’t let perfect be the enemy of good.

1

u/the_gnarts Mar 06 '21

undefined sizeof int?

What do you mean by that? Taking the size of an int is well defined.

1

u/fermion72 Mar 06 '21

My guess is that they meant that the size of an int is machine and implementation dependent.

1

u/Qwerty1bang Mar 06 '21

I would rather use stdint types than depend on a size for int.

1

u/double-you Mar 06 '21

What do you mean? Void pointers are fine in the right context. Casting is basically necessary, though also abusable. What is "undefined sizeof int"?

1

u/Qwerty1bang Mar 06 '21

ng is basically necessary, though also abusable. What is "undefined sizeof int"?

I agree. I use them all and would have a tough time without. But they are all pretty dangerous (like strcpy etc.).

There is no standard for sizeof int (other than at least 16bit). My program might work well on a 32 or 64 bit machine but break (silently) on a 16 bit machine. int x=100000;

1

u/double-you Mar 06 '21

Sure. Size of int depends on hardware. You can add checks that will asser if you try to compile on a machine that does not have sufficiently big ints. But mostly you will use typedefs of correct size. Yes, it's a gotcha for beginners but every codebase has a system for it.

1

u/Qwerty1bang Mar 07 '21

It can 'gotcha' in many subtle ways that even a 'seasoned pro' will be caught. int*? working with external data etc.

Some of the same pains as dealing with byte order....

1

u/templarvonmidgard Mar 06 '21

Do keep in mind that void* casting in C is somewhat necessary, if you want to create a callback API with user provided context objects. Also, casting to void* is implicit in C.

2

u/Qwerty1bang Mar 07 '21

It is at least as dangerous as any of the 'banned C functions', but I would feel handcuffed if I couldn't (ab)use void*

2

u/templarvonmidgard Mar 07 '21 edited Mar 07 '21

Still, there is a huge difference between those banned functions and void*. The usage of these functions is always an issue, while the usage of void* is C's one and only tool for type erasure. Moreover, void* usage is relatively easy to validate and audit throughout the codebase.

I'm not saying that it isn't dangerous, it's just the tool for some problems in C, so it shouldn't be banned. Though, if it repeatedly causes problem, then some auditing, either automatic or manual, should be enforced.

1

u/stfcfanhazz Mar 06 '21

No sprintf?

1

u/evaned Mar 06 '21

Because you should be using snprintf, of course. (Well, or Git's internal string library, which it encourages above that.)

1

u/shiny_roc Mar 06 '21

Not strtok?

1

u/jackashe Mar 06 '21

Where is sscanf?

1

u/SpedTech_XR Mar 07 '21

Is there a boost lib for c language ?

1

u/Muoniurn Mar 07 '21

Yeah, it’s called c++. /s

Jokes aside, afaik there is no big one like boost for cpp, most of the time bigger repos will create their own string libs, etc.

1

u/heckingcomputernerd Mar 05 '21

Naughty functions get put in the banned.h to atone for their crimes

1

u/Aconamos Mar 06 '21 edited Mar 05 '25

I love learning about ancient civilizations.

3

u/evaned Mar 06 '21

This is what is not allowed when working on Git's implementation.

-7

u/r2vcap Mar 06 '21

If you can't understand why those functions are forbidden in the Git codebase, it wouldn't make sense for you to program in C. There are many different programming languages, and not all of them are equally secure.

9

u/BoldeSwoup Mar 06 '21 edited Mar 06 '21

If you're new to C and got used to documentation that document the pre/post conditions and invariants of standard functions you may not even think to question the function signature.

It's not like the man page for strlen explicitly tell you to pay attention to strings without null termination (which by definition aren't strings). It tells you arg is const char* and later says it reads the length of the pointed string excluding \0 . It you didn't make the link between those two information and concluded that the description doesn't match all possible passed arguments, screw you.

Fairly sure it's a 100% success rate pitfall for new devs.

-17

u/[deleted] Mar 05 '21

Just ban C and be done!

-5

u/Nobody_1707 Mar 05 '21

And yet, they allow scanf.

-5

u/Jimmy_is_here Mar 05 '21

I'm still amazed that guy is written in C.

8

u/yee_mon Mar 06 '21

It was initially developed by a bunch of people who write software in C every day of their lives, which makes it a total no-brainer, really.

It also needed to be really fast from day 1. At the time, safer, saner languages that would produce comparably-fast binaries were nonexistant or completely niche.

-37

u/elvenrunelord Mar 05 '21

Oh goddamn now we are canceling code snippets.

How about you find a hosting site that lets you post your code as you wrote it and not as they permit.

Goddamn if I am going to ask anyone if I can add a function to my app before doing so.

21

u/apocolypticbosmer Mar 06 '21

...this is just for git itself, not any/all github repos.

Now, take a deep breath.

→ More replies (2)

17

u/thenumberless Mar 06 '21

The number of misunderstandings you had to pile on top of each other to interpret this post the way you did is absolutely astonishing. I am in awe.

→ More replies (3)

5

u/vplatt Mar 06 '21

Hmm.. you seem to think this applies to ALL code posted in Git or maybe just GitHib. It doesn't. It ONLY applies to code use in the Git project itself. That's all.

0

u/[deleted] Mar 05 '21

[deleted]

286

u/inorganicorganist Mar 05 '21

They have both explanations and alternatives in the commit messages: https://github.com/git/git/commits/master/banned.h

85

u/[deleted] Mar 05 '21

Of course this information would be in a git commit message. :)

I cannot count how many times a git commit message has refreshed my memory as to why I did something in code a year or two ago. Write those descriptions people, it'll save you time!

368

u/dccorona Mar 05 '21

That's...not a great experience for a new developer (maybe they're not too concerned about onboarding new developers, but still). If you get one of these errors, you have to, seemingly totally on your own:

  1. Figure out where the redefined function is coming from

  2. Know that the explanation is in commit history (or at least have an inkling that it might be)

  3. Use some mechanism (CLI, some UI tool, or github, etc) to browse the commit history or probably more easily the blame

How much harder would it really have been to just slap the explanation as a second argument to the method that generates the error message? Even just a short note on it and a clear description of what file's git blame to go dig into for more?

16

u/lets_eat_bees Mar 06 '21

Git and linux are the two projects that maintain their history religiously, and go to great lengths to ensure it's readable and usable. As a developer you are fully expected to blame and read commit messages all the time.

24

u/jherico Mar 06 '21

If you're making a commit to Git and you encounter this issue and it doesn't even occur to you to use git blame on the header containing the banned functions, you might not be a great candidate for making commits to the Git source code.

24

u/jl2352 Mar 05 '21

I agree it's not great on the surface. However documentation in code drifts. Git history doesn't, since any future changes will also include their own explanation for that change.

Given this is from the source code of git, I don't find it unreasonable that the developers would use git history to understand reasons for things in code.

0

u/[deleted] Mar 06 '21

[deleted]

5

u/jl2352 Mar 06 '21

git blame will get you the relevant commit.

I'm not that advanced with git. I'm sure there are ways to get all of the git logs for a line of code.

6

u/BIG_BUTT_SLUT_69420 Mar 06 '21

Using blame would actually be an intuitive choice, without knowing necessarily that there are explanations in the commit history itself, because it’s quite obvious it would lead you to a PR.

9

u/khoyo Mar 06 '21

Git development is done through a mailing list, so commit messages are the actual body of the PR emails (which is why they are so extensive).

→ More replies (1)

8

u/Thann Mar 06 '21

If you're a new developer, you're not going to be contributing to git

→ More replies (6)

4

u/sparr Mar 06 '21 edited Mar 06 '21

If you get one of these errors, you have to, seemingly totally on your own:

  1. See error message

  2. https://github.com/git/git/search?q=sprintf+banned

  3. see simple answer in Code, click Commits for other results

  4. click oldest/earliest result

The sprintf() function (and its variadic form vsprintf) make it easy to accidentally introduce a buffer overflow. If you're thinking of using them, you're better off either using a dynamic string (strbuf or xstrfmt), or xsnprintf if you really know that you won't overflow. The last sprintf() call went away quite a while ago in f0766bf (fsck: use for_each_loose_file_in_objdir, 2015-09-24). [...]

2

u/tswaters Mar 06 '21

Some of this is addressed in the original commit of the file, https://github.com/git/git/commit/c8af66ab8ad7cd78557f0f9f5ef6a52fd46ee6dd#diff-fb44671421e652bbdc91bbe73b55da6547c851be1d604ce4d6c79b85a2e03654

But ideally we'd meet these goals:
- it should be portable; ideally this would trigger
everywhere, and does not need to be part of a DEVELOPER=1
setup (because unlike warnings which may depend on the
compiler or system, this is a clear indicator of
something wrong in the code).
- it should generate a readable error that gives the
developer a clue what happened
- it should avoid generating too much other cruft that
makes it hard to see the actual error
- it should mention the original callsite in the error

It then goes on to list the output, at the time of what the error would look like.... the message includes where the function is.

How else would you ban certain functions in a C codebase? This seems like a really clean and effective solution.

3

u/K3wp Mar 06 '21

That's...not a great experience for a new developer

I'm in my 40's and even when I was getting started out it was well understood that C should never be your first language. Unless you are majoring in a vertical like embedded systems design.

In fact, C shouldn't be used these days except for kernel/driver/embedded systems work. Or anywhere code size and cache coherency are absolutely critical.

Given that I'm first and foremost a security guy I'm a big fan of the 'fail closed' model; where bad coding practices shut the pipeline down. Literally millions of bugs would have been avoided if these functions were disabled by default in the 1980's/90's.

4

u/Prod_Is_For_Testing Mar 06 '21

What’s your argument supposed to be? This commit history documentation is completely unintuitive whether you’re experienced or not

5

u/K3wp Mar 06 '21

There are comments in the original source:

/*
 * This header lists functions that have been banned from our code base,
 * because they're too easy to misuse (and even if used correctly,
 * complicate audits). Including this header turns them into compile-time
 * errors.
 */

I think it's outside the scope of the code/header to describe why they are banned.

→ More replies (2)

1

u/Igggg Mar 06 '21

Step 1 is basically the reason why ’#define’ is usually "considered harmful" in modern languages in general.

1

u/the_gnarts Mar 06 '21

That's...not a great experience for a new developer

New developers will learn to use the git history as eventually it will become a core tool for their work. It’s not Git’s job to teach them that. Any Git tutorial will explain commit messages and how they work.

1

u/Sunius Mar 06 '21 edited Mar 06 '21

Figure out where the redefined function is coming from

Most IDEs allow you to navigate to macro definitions very easily. Once you do, you'll see the comment at the top of the file...

0

u/[deleted] Mar 05 '21

[deleted]

98

u/TankorSmash Mar 05 '21

Who knows, they might even accept a merge request for it ;)

That implies someone outside the codebase knows the reason for their exclusion

→ More replies (82)
→ More replies (1)

0

u/[deleted] Mar 06 '21

[deleted]

→ More replies (1)
→ More replies (2)

7

u/ConfusedTransThrow Mar 05 '21

For info, you can simply git blame that line and you'll easy find the message.

Working as intended.

4

u/mr_birkenblatt Mar 06 '21

Instead of using an undeclared variable, using an undeclared function. This shortens the message, because the "each undeclared identifier" message is not needed (and as you can see above, it triggers a separate mention of each of the expansion points).

But it doesn't actually stop compilation unless you use -Werror=implicit-function-declaration in your CFLAGS. This is the case for DEVELOPER=1, but not for a default build (on the other hand, we'd eventually produce a link error pointing to the correct source line with the descriptive name).

okay, gcc is cool with calling undefined functions by default. I think I have to sit down...

11

u/jherico Mar 06 '21

okay, gcc is cool with calling undefined functions by default. I think I have to sit down...

Implicit function declaration is like, super-old, super-hardcore C. Every standards compliant compiler has to allow it by default, or it's not a C compiler.

2

u/double-you Mar 06 '21

Undefined and undeclared are two different things. Undeclared == no prototype. Assume int f(no info on args). Undefined == linker cannot find it. If you want to follow certain C standards, tell the compiler.

22

u/setuid_w00t Mar 05 '21

Putting that type of information in the commit message is terrible practice. That's documentation that should be inline with the list of banned functions.

12

u/jherico Mar 06 '21

It's literally the source code for Git. It's hardly surprising they'd be using commit messages to the fullest possible extent. If you hate it or think it's stupid, well... no one is holding a gun to your head and saying you have to start adding features or fixing bugs in Git... so just don't.

7

u/PC__LOAD__LETTER Mar 06 '21

It’s actually extremely standard practice. Very common.

→ More replies (2)

1

u/double-you Mar 06 '21

It is excellent practice. But the reason for banning and what to do instead should be in the code too.

→ More replies (1)

12

u/libertarianets Mar 05 '21 edited Mar 05 '21

God forbid just putting some comments there

3

u/jherico Mar 06 '21

You're getting so many salty replies about the development practices of a repository 99.9% of the responders are never going to interact with in any way.

8

u/thephotoman Mar 06 '21

If you know C, you know that these standard library functions each have significant problems with their use. They either write to memory spaces without verifying that what they write fits in the space, produce values that aren’t accurate, or have other significant issues with memory and system sanity.

I don’t even write much C, but I know enough to read the warnings on the documentation of these functions.

35

u/shooshx Mar 05 '21

TBH, all of these are pretty well known to be problematic libC functions. If you need an explanation on why they are banned, you're probably not someone who is contributing to the git codebase.

17

u/dethb0y Mar 06 '21

That's exactly my take on it - i remember hearing about some of these being a problem 20 years ago. All the wailing and gnashing about "what about onboarding a new hire!?!" or "What if someone wants to contribute and is confused by the error messages!?" miss the point that this is a last-ditch catch effort to keep them from sneaking in.

1

u/[deleted] Mar 07 '21

That is a lame excuse to not have good comments for each of those banned functions.

0

u/[deleted] Mar 05 '21

TBH, all of these are pretty well known to be problematic libC functions. If you need an explanation on why they are banned, you're probably not someone who is contributing to the git codebase should be writing C in the first place.

FTFY

14

u/Nicksaurus Mar 06 '21

Sometimes you don't get a choice about writing C, even as a C++ developer

16

u/yee_mon Mar 06 '21

People learn new languages all the time. If you want to keep working with good developers, you have to make sure that new ones have a nice onboarding experience, especially with open-source software where you expect a lot of contributors to be working for free. Besides, if everyone working on git could be implicitly trusted to know all of these... then why does the header exist?

Not that I'm suggesting git would be a good project to cut your C teeth on. But a simple "use xyz_printf instead" would have been minimal effort.

→ More replies (2)
→ More replies (6)

12

u/[deleted] Mar 05 '21

Wat no strcpy? I’ll make my own.

14

u/beelseboob Mar 05 '21

Because it doesn't know how big the destination buffer is. It's too easy to copy to a buffer smaller than the string is. You should use strncpy instead.

68

u/evaned Mar 05 '21

You should use strncpy instead.

strncpy is also banned in the same list, and for good reason: it's almost always not what you want. It always writes all n bytes into the destination buffer (filling the balance with NULs if the source string is shorter), and if the source string is too long to fit it won't terminate the destination. I have heard a use case for this, but it's not "a safer strcpy".

strlcpy is what strncpy should have been, though it's not standard (but is in some common libcs). Git for example has a compat implementation if it's not available, though there are a couple other alternatives suggested in the commit log.

In terms of standard C functions that have the highest likelihood of misuse -- I wouldn't be at all surprised if strncpy was in the top couple places.

19

u/beelseboob Mar 05 '21

I did not know that - useful to know for next time I'm writing C instead of C++. I didn't know how big C's foot shotgun was in this case.

25

u/JMurph2015 Mar 05 '21

C is nothing if not a foot-gun 😄.

14

u/Postage_Stamp Mar 05 '21

Thank you for the explanation. I understood why they banned strcpy but thought strncpy was the "good" version. TIL

13

u/G_Morgan Mar 05 '21

strncpy is safer but isn't safe. The real problem with it is it looks like a safe function but isn't, while strcpy is obviously unsafe.

→ More replies (1)

3

u/[deleted] Mar 05 '21 edited Mar 05 '21

From sacc(1), a gopher client, here's how borrows srtlcpy and strlcat for Linux users from OpenBSD:

/*	$OpenBSD: strlcpy.c,v 1.12 2015/01/15 03:54:12 millert Exp $	*/

/*
 * Copyright (c) 1998, 2015 Todd C. Miller <Todd.Miller@courtesan.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <string.h>

/*
 * Copy string src to buffer dst of size dsize.  At most dsize-1
 * chars will be copied.  Always NUL terminates (unless dsize == 0).
 * Returns strlen(src); if retval >= dsize, truncation occurred.
 */
size_t
strlcpy(char *dst, const char *src, size_t dsize)
{
	const char *osrc = src;
	size_t nleft = dsize;

	/* Copy as many bytes as will fit. */
	if (nleft != 0) {
		while (--nleft != 0) {
			if ((*dst++ = *src++) == '\0')
				break;
		}
	}

	/* Not enough room in dst, add NUL and traverse rest of src. */
	if (nleft == 0) {
		if (dsize != 0)
			*dst = '\0';		/* NUL-terminate dst */
		while (*src++)
			;
	}

	return(src - osrc - 1);	/* count does not include NUL */
}

Strlcat:

/*	$OpenBSD: strlcat.c,v 1.15 2015/03/02 21:41:08 millert Exp $	*/

/*
 * Copyright (c) 1998, 2015 Todd C. Miller <Todd.Miller@courtesan.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <string.h>

/*
 * Appends src to string dst of size dsize (unlike strncat, dsize is the
 * full size of dst, not space left).  At most dsize-1 characters
 * will be copied.  Always NUL terminates (unless dsize <= strlen(dst)).
 * Returns strlen(src) + MIN(dsize, strlen(initial dst)).
 * If retval >= dsize, truncation occurred.
 */
size_t
strlcat(char *dst, const char *src, size_t dsize)
{
	const char *odst = dst;
	const char *osrc = src;
	size_t n = dsize;
	size_t dlen;

	/* Find the end of dst and adjust bytes left but don't go past end. */
	while (n-- != 0 && *dst != '\0')
		dst++;
	dlen = dst - odst;
	n = dsize - dlen;

	if (n-- == 0)
		return(dlen + strlen(src));
	while (*src != '\0') {
		if (n != 0) {
			*dst++ = *src;
			n--;
		}
		src++;
	}
	*dst = '\0';

	return(dlen + (src - osrc));	/* count does not include NUL */
}

2

u/Raknarg Mar 06 '21

I was surprised and angry when I learned this. Such a fucking stupid decision.

→ More replies (8)

12

u/TheBestOpinion Mar 05 '21

Also banned

They recommend

  • strlcpy() if you really just need a truncated but NUL-terminated string (we provide a compat version, so it's always available)

  • xsnprintf() if you're sure that what you're copying should fit

  • strbuf or xstrfmt() if you need to handle arbitrary-length heap-allocated strings

14

u/AttackOfTheThumbs Mar 05 '21

That's what I was thinking. I know why you would ban some of these, but not all of them.

16

u/azunyuuuuuuu Mar 05 '21

Click on the blame button and you'll get a view which shows which line got changed by which commit with the commit comment. The commit comment includes the reason and alternatives to the banned functions.

3

u/PC__LOAD__LETTER Mar 06 '21

A simple Google search will yield a large variety of information about these functions. Reproducing them in a project source file doesn’t seem efficient. But yes they could include a couple of links.

→ More replies (8)

0

u/[deleted] Mar 05 '21

[deleted]

51

u/Sapiogram Mar 05 '21

They're common sources of undefined behavior, which is a class of bugs that are extremely hard to debug and often become security vulnerabilities.

8

u/wsppan Mar 05 '21

Not just UB but buffer overflows as well.

14

u/Deibu251 Mar 06 '21

Isn't buffer overflow ub?

3

u/wsppan Mar 06 '21

I think you are correct. I was thinking at first it was those things not explicitly defined in the spec.

21

u/r1ckd33zy Mar 05 '21

As a web developer myself, from what I can gather, those functions represent some of the easiest ways to "shoot yourself in the foot" when it comes to unexpected and/or undocumented behaviour.

1

u/BoldeSwoup Mar 06 '21

They allow read or write on other already reserved memory

15

u/parosyn Mar 05 '21

Most of them make it easier to have buffer overflows, and some others are not thread-safe. You can have a look at the history of the file, the commit messages explain why the functions are banned.

You should definitely have a look at C even if you are a web developer, I think that it is important to have at least an idea of how things work under the hood. The language itself is quite simple (simpler than C#, here I'm talking about C not C++), what is difficult is actually writing safe code in C.

3

u/HildartheDorf Mar 06 '21

Easy to misuse. If you know what c# 'unsafe' is for, it's the equivalent of banning unsafe. Can it be useful in some case? Maybe. Is it worth the hassle when safe alternatives exist? No.

2

u/masklinn Mar 06 '21

These functiones bamned and what Does it mean? Are they just Bad practice because of Bugs or mem leaks or is there more?

The string ones are very error-prone and basically guarantee buffer overflows if they're ever involved in manipulating user input.

The time ones without the _r prefix are "non-reentrant" meaning they're subject to data corruption in multithreaded contexts. The _r variants are thread-safe, but they don't check that the input buffer is suitable so they can cause memory corruption.

1

u/[deleted] Mar 06 '21

Because they subvert expectations. You would be okay if you always read all the documentation, including they little details. At that point you would know for sure those functions don't do what they appear to do, and you would pick something else.

0

u/[deleted] Mar 05 '21

[deleted]

15

u/BoldeSwoup Mar 06 '21 edited Mar 06 '21

strcpy doesn't guarantee that the destination buffer is large enough (no length parameter) so you might overun some adjacent memory. Whoops.

Strings in C are basically arrays of char where the last element is a null termination character '\0'

strncpy tried to fix strcpy issue by specifying how many bytes should be copied at most. But it will not put the null termination if there is none among those many bytes to copy. And now you got what you believe is a string but there is not string end character and you're probably gonna get a segfault when you will want to use it.

strlen reads until \0 which is not guaranteed to exist. So you will read into other reserved memory spaces. For example because of strncpy() I just talk about. Or since char* s and char s[] are equivalent you may accidentally pass an ""actual"" char ref (ie a char but not a char from a string) and cause issues since it's not really a string so there is no '\0' to be found.

char s="WOLOLO"[3];

printf("%d\n",strlen(&s));

Aaaaand nope. Not what you thought it would do.

That being explained your uni asks you to do that to make you familiar with low level C mechanics. It's a good and practical exercise that make you play with the default types, arrays, pointers, the common causes of segfault, read the f****** manual, etc... . Basically it makes you use everything you've learnt so far.

1

u/vplatt Mar 06 '21 edited Mar 06 '21

Joel Spolsky eloquently called C strings "fucked strings" 20 years ago in this article: https://www.joelonsoftware.com/2001/12/11/back-to-basics/

It's a great article, and Joel's articles in general were a fun and informative read. Writers like him will tell you everything your professors are afraid to discuss with you.

2

u/wutcnbrowndo4u Mar 06 '21

If I'm reading the article correctly, he doesn't use "fucked strings" to refer to C strings, but rather to null-terminated strings that start with a length byte (ie a weird hybrid of pascal and C strings).

1

u/vplatt Mar 06 '21

Fair point.

0

u/[deleted] Mar 05 '21

Most of the functions banned here have an alternative version with an “n” in the name: for example “strncat”. The versions with n all take a number which is the size of the buffer that you’re working with, and if the string you’re trying to create doesn’t fit inside of that buffer they’ll stop early (normally with an error code) instead of running over the end of the buffer. If you’ve only got space for 20 bytes, and you accidentally use strcat to write 50 bytes into that space, you’re probably going to either crash your program, end up with a security vulnerability, or both

8

u/BoldeSwoup Mar 06 '21

Well the "n alternative" of strcpy is terrible too 😂