First Draft: Making printf @safe
Walter Bright
newshound2 at digitalmars.com
Wed Jul 17 01:09:17 UTC 2024
On 7/16/2024 5:42 PM, Walter Bright wrote:
> https://github.com/WalterBright/documents/blob/ed4f1b441e71b5ac5e23a54e7c93e68997981e9a/SafePrintf.md
Paul Backus writes:
> What I find objectionable in this case is that (a) the better interface is implemented using a bunch of compiler-internal rewrites, rather than normal D code; and (b) it shadows the existing C printf function rather than existing alongside it.
It's a pretty thin piece of paper over printf. Consider:
```
printf("%s\n", 3);
```
That's going to crash a C program. Currently, for D an error will be given.
Under this proposal, it will be rewritten as:
```
printf("%d\n", 3);
```
The rewrite will only happen for %s format specifiers.
For the following:
```
char* s;
printf("%s\n", s);
```
there will be no rewrite, but that call will be considered unsafe. For:
```
char[] s;
printf("%s\n", s);
```
that is currently rejected by the compiler. Under this proposal, it will be
rewritten as:
```
char[] s;
printf("%.*s\n", cast(int)s.length & 0x7FFF_FFFF);
```
which will make it safe.
I can't think of a case where the proposal makes any existing uses of printf
impossible. If they exist, there are workarounds:
1. use a variable rather than a string literal for the format:
```
char* fmt = "hello %s!\n";
printf(fmt, "betty");
```
2. this behavior is triggered by the function being marked as `pragma(printf)`.
Don't do that if you don't want it. Or declare printf yourself as:
```
extern (C) int printf(const(char)*, ...);
```
> If we need a safer printf for DMD that doesn't carry all the bloat and baggage of Phobos's writef, then by all means, let's write one. But let's write it in D and put it in a normal D module, instead of sneaking around and redefining printf behind our users' backs.
The printf argument checking code added in has been an unblemished win for us. C
and C++ compilers seem to be adding it, too. This is just a small improvement
over that.
More information about the dip.development
mailing list