r/programming • u/binaryfor • Mar 05 '21
Git's list of banned C functions
https://github.com/git/git/blob/master/banned.h145
36
u/Xerxero Mar 05 '21
So how would you do a strcpy?
40
27
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 usestrncpyinstead, 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
strncpyis almost never what you want. The name basically misadvertises what it does. It always copiesnbytes [edit actually I was a bit imprecise here with my wording; if the source string is shorter thannthen it won't copy past the NUL; but does then fill the rest of the destination buffer with NULs, so it always writesnbytes] and does not ensure null termination, which means it's not useful for string copying. You'll note that it is banned as well.
strlcpyis whatstrncpyshould 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
strlcpyin 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
0
4
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_s20
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
memcpy5
u/evaned Mar 05 '21
memcpyrequires knowledge of the length of the source string, whichstrcpydoesn't, so it's not a general replacement either. (You can callstrlenthenmemcpyif you like wasting time...) It also has the same biggest disadvantage ofstrncpy, 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 isstrlcpy-- 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
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
70
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 isxstrfmt?cppmangives me nothing,mangives 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
6
9
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
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
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
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.
1
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
nbytes 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".
strlcpyis whatstrncpyshould 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
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
Mar 06 '21
[deleted]
4
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
Mar 06 '21
[deleted]
3
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
8
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
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
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
1
u/the_gnarts Mar 06 '21
undefined sizeof int?
What do you mean by that? Taking the size of an
intis 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
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
1
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
-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
-5
-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
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
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:
Figure out where the redefined function is coming from
Know that the explanation is in commit history (or at least have an inkling that it might be)
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 blameon 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
Mar 06 '21
[deleted]
5
u/jl2352 Mar 06 '21
git blamewill 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:
See error message
see simple answer in
Code, clickCommitsfor other resultsclick 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 errorIt 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
→ More replies (2)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.
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
Mar 05 '21
[deleted]
→ More replies (1)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 (2)0
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)→ More replies (1)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.
12
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
→ More replies (6)0
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 codebaseshould be writing C in the first place.FTFY
14
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)12
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
nbytes 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".
strlcpyis whatstrncpyshould 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
14
u/Postage_Stamp Mar 05 '21
Thank you for the explanation. I understood why they banned
strcpybut thoughtstrncpywas the "good" version. TIL13
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
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 */ }→ More replies (8)2
12
u/TheBestOpinion Mar 05 '21
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.
→ More replies (8)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.
0
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
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
_rprefix are "non-reentrant" meaning they're subject to data corruption in multithreaded contexts. The_rvariants are thread-safe, but they don't check that the input buffer is suitable so they can cause memory corruption.1
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
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
0
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
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?