Sdl checks в visual studio как отключить
I am using Visual Studio 2013 Preview, although I'm sure I've seen it in earlier versions. When creating a new project using the wizard, I select C++, Win32 Console Application, and there is an option to enable Security Development Lifecycle Checks on my project. Could someone explain exactly what this option does to my code/project?
2 Answers 2
The /sdl switch is described here. It turns some warnings into errors, which does not affect your code. Furthermore, it applies the /GS check more aggresively.
Don't expect too much from it. The Microsoft SDL is really a workaround for 1980's style C programming. Even it you use 20th century C++, you don't need it. E.g. operator+(std::string, std::string) is both safe and portable. Microsoft's SDL solution here in contrast is not portable, nor is it safe - the idea behind /GS is to find errors with C string handling at runtime and abort the program, limiting the consequences but not making it safe.
Strings is not the only cause of memory errors. /sdl can help you identify use of unitialized variables, among other things.
@JørgenFogh: You're describing the C4700 warning, for which you don't need /sdl. It's a Level-1 warning; you need to turn off all warnings before C4700 disappears. If your developers are doing that, you've got problems which SDL won't solve either.
Performs limited pointer sanitization. In expressions that do not involve dereferences and in types that have no user-defined destructor, pointer references are set to a non-valid address after a call to delete. This helps to prevent the reuse of stale pointer references. Performs class member initialization. Automatically initializes all class members to zero on object instantiation (before the constructor runs). This helps prevent the use of uninitialized data associated with class members that the constructor does not explicitly initialize.
@Motes: You should've written it as a separate answer. This is way more helpful than a (derisive) answer this comment is placed for. Additionally the link given there is bad. It should be this.
Включает рекомендованные проверки жизненного цикла разработки безопасности (SDL). Эти проверки изменяют связанные с безопасностью предупреждения в ошибки и устанавливают дополнительные функции создания безопасного кода.
Синтаксис
Remarks
/SDL включает надмножество базовых проверок безопасности, /GS предоставляемых и переопределений /GS- . По умолчанию /sdl параметр имеет значение OFF. /sdl- отключает дополнительные проверки безопасности.
Проверки времени компиляции
/sdl позволяет применять эти предупреждения как ошибки:
Включаемые/sdl предупреждения | Эквивалентный параметр командной строки | Description |
---|---|---|
C4146 | /we4146 | Унарный оператор "минус" был применен к беззнаковому типу, что приведет к получению результата без знака. |
C4308 | /we4308 | Отрицательная целая константа преобразуется в беззнаковый тип, что, вероятно, приведет к получению бессмысленного результата. |
C4532 | /we4532 | continue Использование ключевых слов, break , или goto в __finally / finally блоке имеет неопределенное поведение во время аварийного завершения. |
C4533 | /we4533 | Код инициализации переменной не выполняется. |
C4700 | /we4700 | Используется неинициализированная локальная переменная. |
C4703 | /we4703 | Используется потенциально неинициализированная локальная переменная-указатель. |
C4789 | /we4789 | Переполнение буфера при использовании определенных функций среды выполнения C (CRT). |
C4995 | /we4995 | Использование функции, помеченной директивой pragma deprecated . |
C4996 | /we4996 | Использование функции, помеченной как deprecated . |
Проверки во время выполнения
Если /sdl включен, компилятор создает код, выполняющий эти проверки во время выполнения:
Ограничена очистка указателя. В выражениях, не затрагивающих разыменование и в типах, не имеющих пользовательских деструкторов, ссылки на указатели устанавливаются в недопустимый адрес после вызова delete . Такая очистка помогает предотвратить повторное использование устаревших ссылок на указатели.
Инициализирует указатели членов класса. Автоматически инициализирует члены класса типа указателя до nullptr создания экземпляра объекта (перед запуском конструктора). Это помогает предотвратить использование неинициализированных указателей, которые конструктор не инициализирует явным образом. Инициализация указателя члена, созданного компилятором, вызывается при условии, что:
Объект не выделяется с помощью пользовательского (определенного пользователем) operator new
Объект не выделяется как часть массива (например new A[x] ,)
Класс не управляется или не импортируется
Класс имеет определенный пользователем конструктор по умолчанию.
Для инициализации с помощью созданной компилятором функции инициализации класса элемент должен быть указателем, а не свойством или константой.
Установка данного параметра компилятора в среде разработки Visual Studio
Перейдите на страницу свойств Свойства конфигурации>C/C++>Общие.
Enables recommended Security Development Lifecycle (SDL) checks. These checks change security-relevant warnings into errors, and set additional secure code-generation features.
Syntax
Remarks
/sdl enables a superset of the baseline security checks provided by /GS and overrides /GS- . By default, /sdl is off. /sdl- disables the additional security checks.
Compile-time Checks
/sdl enables these warnings as errors:
Warning enabled by /sdl | Equivalent command-line switch | Description |
---|---|---|
C4146 | /we4146 | A unary minus operator was applied to an unsigned type, resulting in an unsigned result. |
C4308 | /we4308 | A negative integral constant converted to unsigned type, resulting in a possibly meaningless result. |
C4532 | /we4532 | Use of continue , break , or goto keywords in a __finally / finally block has undefined behavior during abnormal termination. |
C4533 | /we4533 | Code initializing a variable will not be executed. |
C4700 | /we4700 | Use of an uninitialized local variable. |
C4703 | /we4703 | Use of a potentially uninitialized local pointer variable. |
C4789 | /we4789 | Buffer overrun when specific C run-time (CRT) functions are used. |
C4995 | /we4995 | Use of a function marked with pragma deprecated . |
C4996 | /we4996 | Use of a function marked as deprecated . |
Runtime checks
When /sdl is enabled, the compiler generates code that does these checks at run time:
Does limited pointer sanitization. In expressions that don't involve dereferences and in types that have no user-defined destructor, pointer references are set to a non-valid address after a call to delete . This sanitization helps to prevent the reuse of stale pointer references.
Initializes class member pointers. Automatically initializes class members of pointer type to nullptr on object instantiation (before the constructor runs). It helps prevent the use of uninitialized pointers that the constructor doesn't explicitly initialize. The compiler-generated member pointer initialization is called as long as:
The object isn't allocated using a custom (user defined) operator new
The object isn't allocated as part of an array (for example new A[x] )
The class isn't managed or imported
The class has a user-defined default constructor.
To be initialized by the compiler-generated class initialization function, a member must be a pointer, and not a property or constant.
To set this compiler option in the Visual Studio development environment
Open the project's Property Pages dialog box. For details, see Set C++ compiler and build properties in Visual Studio.
Select the Configuration Properties > C/C++ > General property page.
Set the SDL checks property by using the property drop-down control. Choose OK or Apply to save your changes.
Enables recommended Security Development Lifecycle (SDL) checks. These checks change security-relevant warnings into errors, and set additional secure code-generation features.
Syntax
Remarks
/sdl enables a superset of the baseline security checks provided by /GS and overrides /GS- . By default, /sdl is off. /sdl- disables the additional security checks.
Compile-time Checks
/sdl enables these warnings as errors:
Warning enabled by /sdl | Equivalent command-line switch | Description |
---|---|---|
C4146 | /we4146 | A unary minus operator was applied to an unsigned type, resulting in an unsigned result. |
C4308 | /we4308 | A negative integral constant converted to unsigned type, resulting in a possibly meaningless result. |
C4532 | /we4532 | Use of continue , break , or goto keywords in a __finally / finally block has undefined behavior during abnormal termination. |
C4533 | /we4533 | Code initializing a variable will not be executed. |
C4700 | /we4700 | Use of an uninitialized local variable. |
C4703 | /we4703 | Use of a potentially uninitialized local pointer variable. |
C4789 | /we4789 | Buffer overrun when specific C run-time (CRT) functions are used. |
C4995 | /we4995 | Use of a function marked with pragma deprecated . |
C4996 | /we4996 | Use of a function marked as deprecated . |
Runtime checks
When /sdl is enabled, the compiler generates code that does these checks at run time:
Does limited pointer sanitization. In expressions that don't involve dereferences and in types that have no user-defined destructor, pointer references are set to a non-valid address after a call to delete . This sanitization helps to prevent the reuse of stale pointer references.
Initializes class member pointers. Automatically initializes class members of pointer type to nullptr on object instantiation (before the constructor runs). It helps prevent the use of uninitialized pointers that the constructor doesn't explicitly initialize. The compiler-generated member pointer initialization is called as long as:
The object isn't allocated using a custom (user defined) operator new
The object isn't allocated as part of an array (for example new A[x] )
The class isn't managed or imported
The class has a user-defined default constructor.
To be initialized by the compiler-generated class initialization function, a member must be a pointer, and not a property or constant.
To set this compiler option in the Visual Studio development environment
Open the project's Property Pages dialog box. For details, see Set C++ compiler and build properties in Visual Studio.
Select the Configuration Properties > C/C++ > General property page.
Set the SDL checks property by using the property drop-down control. Choose OK or Apply to save your changes.
Enables recommended Security Development Lifecycle (SDL) checks. These checks change security-relevant warnings into errors, and set additional secure code-generation features.
Syntax
Remarks
/sdl enables a superset of the baseline security checks provided by /GS and overrides /GS- . By default, /sdl is off. /sdl- disables the additional security checks.
Compile-time Checks
/sdl enables these warnings as errors:
Warning enabled by /sdl | Equivalent command-line switch | Description |
---|---|---|
C4146 | /we4146 | A unary minus operator was applied to an unsigned type, resulting in an unsigned result. |
C4308 | /we4308 | A negative integral constant converted to unsigned type, resulting in a possibly meaningless result. |
C4532 | /we4532 | Use of continue , break , or goto keywords in a __finally / finally block has undefined behavior during abnormal termination. |
C4533 | /we4533 | Code initializing a variable will not be executed. |
C4700 | /we4700 | Use of an uninitialized local variable. |
C4703 | /we4703 | Use of a potentially uninitialized local pointer variable. |
C4789 | /we4789 | Buffer overrun when specific C run-time (CRT) functions are used. |
C4995 | /we4995 | Use of a function marked with pragma deprecated . |
C4996 | /we4996 | Use of a function marked as deprecated . |
Runtime checks
When /sdl is enabled, the compiler generates code that does these checks at run time:
Does limited pointer sanitization. In expressions that don't involve dereferences and in types that have no user-defined destructor, pointer references are set to a non-valid address after a call to delete . This sanitization helps to prevent the reuse of stale pointer references.
Initializes class member pointers. Automatically initializes class members of pointer type to nullptr on object instantiation (before the constructor runs). It helps prevent the use of uninitialized pointers that the constructor doesn't explicitly initialize. The compiler-generated member pointer initialization is called as long as:
The object isn't allocated using a custom (user defined) operator new
The object isn't allocated as part of an array (for example new A[x] )
The class isn't managed or imported
The class has a user-defined default constructor.
To be initialized by the compiler-generated class initialization function, a member must be a pointer, and not a property or constant.
To set this compiler option in the Visual Studio development environment
Open the project's Property Pages dialog box. For details, see Set C++ compiler and build properties in Visual Studio.
Select the Configuration Properties > C/C++ > General property page.
Set the SDL checks property by using the property drop-down control. Choose OK or Apply to save your changes.
Читайте также: