问题描述
我注意到MS编译器为 cstdlib
函数提供了不推荐使用的警告,比如 getenv
。 MS已经发明了自己的标准,如 _dupenv_s
。
问题1
AFAIK主要的不安全是关于重入*。由于MS的CRT被标记为多线程( / MT
),为什么不把它们替换为 getenv
与可重入的线程安全版本?是否像任何人会依赖不安全的行为?
问题2
我用GCC编译了相同的代码 g ++ -Wall -Wextra -Weff ++ -pedantic foo.cpp
并且不会产生任何警告。所以我猜这在POSIX上不是问题?这是如何解决的? (好吧,也许他们只是改变了 getenv
的行为,很高兴有这个证实)。
* 这是一种过于笼统的说法,它只是关于重入。当然,我们有像 strncpy_s
这样的东西来完全改变签名并处理缓冲区大小。但不会改变这个问题的核心
cl.exe
会突出显示潜在的安全问题,而 g ++
不是。 getenv
和 puts
以及朋友在POSIX下仍然被破坏,但是(至少对于 getenv
)标准库中没有更安全的选择。而且,与微软不同的是,GNU的人可能会看到一个标准的库调用,其潜在的安全问题比一个更安全但特定于平台的库调用更小。
I notice that MS compilers give "deprecated" warnings for cstdlib
functions like getenv
. MS has invented its own standard such as _dupenv_s
.
Question 1
AFAIK the main "unsafe" thing is about reentrancy *. Since MS's CRT is marked as "multi-threaded" (/MT
), why don't they just replace getenv
with the reentrant, thread-safe version? Is it like anybody would depend on the unsafe behavior?
Question 2
I compiled the same code with GCC g++ -Wall -Wextra -Weff++ -pedantic foo.cpp
and it doesn't yield any warnings. So I guess this is not a problem on POSIX? How is this solved? (OK maybe they just changed the behavior of getenv
, would be nice to have this confirmed).
* It's an over-generalization to say that its' only about reentrancy. Of course we have things like strncpy_s
which changes the signature completely and deals with buffer size. But doesn't change the core of this question
In a sane world, the answer would be "of course not, that would be stupid!" In this world, though, it seems there is no end of gut-wrenchingly poorly thought out undocumented behavior upon which people will stoop to depending upon. Raymond Chen has a great collection of such anecdotes (anecdon'ts?) in his blog. Such as the hideous practice of using a bug in the loader to share thread-local variables between an exe and a DLL. When you have as many customers as Microsoft does, the only safe choice is to never even risk breaking backwards compatibility.
The difference in warnings is because
cl.exe
is going out of its way to highlight a potential security problem, andg++
isn't.getenv
andputs
and friends are all still broken under POSIX, but (at least forgetenv
) there isn't a more secure alternative in the standard library. And, unlike Microsoft, the GNU folks probably see a standard library call with potential security problems as a lesser evil than a more secure but platform-specific library call.
这篇关于警告C4996:与POSIX上的GCC相比,此功能或变量可能不安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!