180 likes | 448 Views
Tips & Tricks: Scrubbing Source Code For Common Coding Mistakes (FxCop And PREfast). Nicholas Guerrera TLNL06 Software Design Engineer Microsoft Corporation. Why Code Analysis?. One of a collection of strategies for improving code quality
E N D
Tips & Tricks: Scrubbing Source Code For Common Coding Mistakes (FxCop And PREfast) Nicholas Guerrera TLNL06 Software Design Engineer Microsoft Corporation
Why Code Analysis? • One of a collection of strategies for improving code quality • Identify potential issues earlier in development cycle • Problems are cheaper to fix the earlier they are identified
Code Analysis In Visual Studio Team System • Managed code analysis (FxCop) • C#, C++/CLI, VB .NET, ASP.NET • Unmanaged code analysis (PREfast) • C/C++ • Automatically suppress warnings in source • File bugs based on analysis results • Enforce code analysis policy for check-ins
Types Of Mistakes • Typographical • Misuse of API • Security issues • API design guidelines / best practices • Code complexity and maintainability • Constructs that do not perform well
Demo: Managed Code Analysis In Visual Studio Team System Nicholas Guerrera Software Design Engineer Visual Studio Team System
Example OneSQL injection vulnerability private string GetAccountNumber(string username, string password) { string cnxString = ConfigurationManager.AppSettings["ConnectionString"]; using (SqlConnection connection = new SqlConnection(cnxString)) using (SqlCommand command = new SqlCommand()) { connection.Open(); command.Connection = connection; command.CommandText = "SELECT AccountNumber FROM Users " + "WHERE (Username='" + username + "')" + "' AND (Password='" + password + "')"; return (string)command.ExecuteScalar(); } } "q' OR 'q'='q"
Example TwoNaming and design guidelines public class box{ public int height; public int width; public box(int height, int width){ this.height = height; this.width = width; this.print_to_console(); } public void print_to_console(){ Console.WriteLine("({0},{1}", this.height, this.width); } } Issues: public fields, incorrect casing, underscores Tip: Use C# refactoring to fix these!
Example ThreeGlobalization error private Font ReadFontFromSettings() { XmlDocument doc = new XmlDocument(); doc.Load(GetSettingsXmlPath()); XmlNode fontNode = doc.SelectSingleNode("Font"); float size = float.Parse(fontNode.Attributes["Size"].Value); string name = fontNode.Attributes["Name"].Value; FontStyle style = (FontStyle)Enum.Parse(typeof(FontStyle), fontNode.Attributes["Style"].Value); return new Font(name, size, style); } Issue: Missing IFormatProvider argument, defaults to CultureInfo.CurrentCulture
Example FourSerialization error public class SampleException : Exception { public SampleException() : base() { } public SampleException(string message) : base(message) { } public SampleException(string message, Exception innerException) : base(message, innerException) { } } Issue: Missing [Serializable] attribute and deserialization constructor Exception cannot be serialized or thrown across AppDomains.
Demo: Unmanaged Code Analysis In Visual Studio Team System Nicholas Guerrera Software Design Engineer Visual Studio Team System
Example OneBuffer overrun void PrintModuleFileName() { wchar_t *p = (wchar_t *)malloc(MAX_PATH); GetModuleFileName(NULL, p, MAX_PATH); printf("%S", p); } • Issues • Buffer overrun: confusion between character and byte counts • Misuse of malloc and GetModuleFileName
Example TwoArithmetic overflow long long Shift(int x, int y) { return x << y; } • Issue • Arithmetic overflow: result is cast to 64-bit after the shift may already have overflown beyond 32-bits.
Example ThreeIncorrect HRESULT usage // Call CoInitialize and return true if it succeeds. bool Initialize() { if (CoInitialize(0)) { return false; } return true; } • Issue • HRESULT and bool are semantically different, use FAILED or SUCCEEDED macros. • Success codes can be non-zero (true in a boolean context). For example, S_FALSE == 0x1
Example FourIncorrect printf usage bool PrintStuff() { printf("%s - %d", 22, "twenty-two"); printf("%s - %d", "twenty-two"); printf("%s - %d", "twenty-two", 22, 22); } • Issues • Type mismatches • Too few arguments • Too many arguments
Example FivePossible NULL dereference void DoWork(){ int x, *p; if (Condition()) { p = &x; } else { p = (int *)malloc(sizeof(int)); } *p = 27; } Issue: If Condition() returns false, p could be null Tip: Double-click on messages in the error list to see path highlighting
Where To Find Out MoreGetting started with code analysis • Hands-On Lab: Visual Studio Team System, Source Code Analysis: HOL-TLN04 • Visual Studio Team System 2005 Beta 2, CTP, or upcoming RTM • Discussions on public forums at http://forums.microsoft.com • FxCop is also available as a standalone tool from http://www.gotdotnet.com/
© 2005 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.