193 posts

JSR 305: a silver bullet or not a bullet at all?

Posted by Mikhail Ksenzov   March 30th, 2009

JSR-305 is a Java Specification Request intended to improve the effectiveness of static analysis tools operating in Java 5+ environments. The idea here is that one can use special purpose annotations in order to provide static analysis tools with hints regarding the behaviour and side effects of methods.

An example of such annotations can be found in the presentation ‘Annotations for Software Defect Detection’ by William Pugh, who is masterminding the whole spec. Here we go:

 1: void test() {
 2:    if (spec != null) fFragments.add(spec);
 3:    if (isComplete(spec)) fPreferences.add(spec);
 4: }
 6:
 5: boolean isComplete(AnnotationPreferences spec) {
 6:    return spec.getColorPreferenceKey() != null
 7:        && spec.getColorPreferenceValue() != null
 8:        && spec.getTextPreferenceKey() != null
 9:        && spec.getOverviewRulerPreferenceKey() != null;
10: }

What’s wrong with the snippet above? Well, the check for null on line 2 shows that the developer expects that the value of ‘spec’ can potentially be null, but it is still passed to method ‘isComplete’. Later, ‘isComplete’ attempts to dereference the value, which causes a NullPointerException.

According to Dr. Pugh, the best way to detect this issue statically is to force a developer to add the annotation @Nonnull to the method signature like this:

5: boolean isComplete(@Nonnull AnnotationPreferences spec) {

In this way, a basic static analysis tool that can minimally track ‘spec’ as a potential suspect for ‘null’ can issue a warning when the @Nonnull annotation is contradicted (that is, when ‘spec’ is passed to ‘isComplete’ as a parameter).

There are two problems with this approach:

  • it forces the developer to do work that rightly should be performed by a static analysis engine
  • it takes time to write the annotation for static analysis, but it takes even more effort to maintain the annotations and the actual code base in a consistent state.

In reality, the proposals behind JSR-305 exist to enable a tool intended for single function analysis (so-called intra-procedural analysis) to act as if it were performing whole program analysis by requiring the developer to state expected behaviour up front (whether or not that behaviour is actually expressed correctly in the developer’s code).

In contrast, this same scenario is supported by a whole program static analysis tool (so-called inter-procedural analysis) without developer intervention:

  1. First, a complete call-graph of the system is built, and then all the methods are ordered so that called methods are processed prior to callers — such an ordering allows the tool to generate all the necessary information about, in this instance, the method ‘isComplete’ by the time the analysis of the method ‘test’ begins.
  2. During the analysis of ‘isComplete’, the tool records the fact that the incoming argument ‘spec’ is dereferenced.
  3. Next, the method ‘test’ is analyzed. In this method, the variable ‘spec’ is checked for null, so it is tracked as a potential suspect for an exception. Using the information generated about ‘isComplete’ the tool can reliably issue a warning on line 3, since it already knows that ‘isComplete’ dereferences the incoming argument.

So that example applies to a simple unconditional dereference scenario. In more complicated cases, Dr. Pugh proposes to use the annotation parameter ‘when’, with one of the following values:

  • ALWAYS
  • NEVER
  • MAYBE
  • UNKNOWN

For example: ‘@Nonnull(when=When.NEVER)’ means that a value is always null in the given context.

This specification seems to be a compromise between the amount of information provided by a developer to a static analysis tool and the amount of effort a developer has to put into it, a compromise that does not seem to be a particularly good solution here. First of all, the amount of information provided in such a manner is insufficient to provide accurate analysis, and secondly this seems to be too much work for the developer, especially when this work can be avoided.

Let’s examine how conditional value dereferencing is supported by whole program static analysis tools:

 1: void test() {
 2:     entity.qualifiedName = null;
 3:     saveName(entity, false);
 4: }
 5:
 6: boolean    saveName(Entity entity, boolean qualified) {
 7:    String name;
 8:    if (qualified)
 9:        name = entity.qualifiedName.trim();
10:    else
11:        name = entity.name.trim()
12:
13:     save(name);
14: }

In this example, an inter-procedural static analysis tool would first analyze the method ‘saveName’. A good analysis engine should be able to record the fact that this method only dereferences ‘entity.qualifiedName’ if the second parameter, ‘qualified’, is set to ‘true’. This, it would appear, is a deal more detailed than one can practically achieve by adding @Nonnull(when=When.XXX) annotations, even with all the work the annotation implies for the developer.

Next, the method ‘test’ would be analyzed. A good static analysis tool will naturally keep track of ‘entity.qualifiedName’ because of the assignment to ‘null’ on line 2 and its therefore potential use in an exception causing context. However, given that the actual call to ‘saveName’ on line 3 uses ‘false’ as its second argument, such a tool will not issue a warning that would in reality be a false positive, since the knowledge gained from analyzing ‘saveName’ disqualifies any potential warning due to the conditional relationship between arguments.

In summary, JSR-305 proposes a whole roster of interesting ideas for using annotations to enhance static analysis of Java code, and NPE detection seems to be only one aspect of this specification request. In upcoming blog posts, we shall continue the discussion of proposed annotations as well as offering our own ideas about how and when annotations should be used in static analysis.

  • email
  • Twitter
  • LinkedIn
  • Reddit
  • DZone
  • Digg
  • Slashdot
  • del.icio.us
  • Technorati
  1. Mikko Kauppila

    The tragedy is that Java designers chose to make all variables non-final and nullable by default. This makes inter-procedural analysis difficult since the analyzer cannot assume pretty much anything. Also, classes are non-final by default, which makes inter-procedural analysis even harder (since dynamic dispatch due to inheritance may occur).

    I disagree about the maintenance cost associated with annotations. This is akin to saying that unit tests are bad since they need to be updated whenever contracts change. Maintaining the annotations — or unit tests, for that matter — means that you’re managing the correctness of your code, which is only right.

    The last snippet (with methods “test” and “saveName”) you present is indeed hard to analyze. However, it can be argued that it duplicates information: whether the entity has a qualified name is a property of the entity itself, and should not be passed as a separate parameter (“boolean qualified”). My humble opinion is that programmers should strive to write code that’s easy to analyze.

    Otherwise, your post was good and informative.

  2. Fabrizio Giudici

    I agree with Mikko’s second paragraph: indeed I think the time spent to put annotations and ensure they are consistent is very well spent, as it forces you to be precise with your design. Also, if you adopt standard practices such as using mostly @NotNull (e.g. by using NullObject or SpecialCase patterns) the amount of work is really reduced.

    The fact that things in Java are not final by default is no excuse for developers not using the “final” keyword as much as possible ;-)

  3. Ex Boyfriend

    Not that I’m impressed a lot, but this is a lot more than I expected for when I stumpled upon a link on SU telling that the info is quite decent. Thanks.

Now’s the time to invest in developer productivity.

Posted by Mike Laginski   March 24th, 2009

As software managers you’re undoubtedly being asked to do more with less in this economy. With companies continuously being forced to cut costs, the first shoe to drop is when you are told you need to cut headcount.

The second shoe drops the day after the painful deed is done and you look into the eyes of the team members that are left behind and try to put a positive spin on your world – their world. And that is when reality really hits home.  Less people, same number of problems.  No one “downsized” the backlog of customer requests, the bugs, the schedule expectations or the previous team’s workload.

At this point two groups form; the group of managers that simply puts their head down and grinds it out until things turn around (hoping things don’t get worse…which is really a do nothing strategy and those rarely work)…or the group that decides to be bold and innovative.  The natural inclination is to say the latter approach is too risky but in reality it is actually less risky, just more visible and more likely to be positively received by your team and your management.

The dev organizations best positioned to come out of this economic downturn stronger, are the ones with dev leaders that are focused on how to do things differently.  Agile development and further process automation with advanced tools become the mechanism to strongly position these dev teams for the better days ahead.  Why? Because just like every bubble, every downturn eventually ends.  As a dev manager, your real focus needs to be on what you want your team and your company to look like coming out of the downturn – heads down, battered and bruised but glad to be alive -  or lean and mean supported by a finely automated dev infrastructure and ready to capitalize on new opportunities.

By focusing on new approaches and automation, you  are helping your team feel they can get in front of the workload they have been presented with during these very challenging economic times. Automation is critical.  Tools such as continuous integration, refactoring, and code analysis all help eliminate wasteful, demoralizing “redo’s” of stupid mistakes they probably would not have made if they were not so maxed out, or if they were more familiar with the latest project you had no choice but to drop on their lap.  They see a way to spend more time on interesting, and challenging, innovation rather than just constant debugging.

“Hunker down” seems to be the mantra of our times, but “hunker down smart” and you and your team will be more readily positioned for the better days ahead.

  • email
  • Twitter
  • LinkedIn
  • Reddit
  • DZone
  • Digg
  • Slashdot
  • del.icio.us
  • Technorati

Avionics Software Development and DO-178B

Posted by Brendan Harrison   March 18th, 2009

Today, I had a chance to connect with Connie Beane, the Director of Certification and Safety Critical Software for ENEA Embedded Technology, Inc. Connie has a deep background in safety-critical avionics systems development as a Federal Aviation Administration Designated Engineering Representative (DER) with authority for design assurance level A systems, software and complex electronic hardware. Her additional experience includes 12 years with the FAA in the Transport Airplane Directorate as a Project Officer, Federal representative and Secretary of the RTCA committee SC-180, which produced DO-254, as well as 8 years at Boeing as a Lead Engineer in Boeing Commercial and Boeing Aerospace Divisions.

I wanted to talk to her more about avionics software development, specifically give Kloctalk readers some additional background on the DO-178B guidance that’s used in avionics software development.

[Brendan]:  Can you describe the short version of the history behind this guidance, its purpose, and use in the industry?
[Connie]: In the early 1990’s Boeing was developing the 777 aircraft, which included very software intensive systems.  As a result, industry began using software development and verification tools as a means of developing software more efficiently. The FAA saw this trend as a concern since many of these tools were being used with very little human oversight. When DO-178B was published in 1992, a section on Tool Qualification was included.

[Brendan]:  Is DO-178B guidance only used by teams developing software for commercial aircraft or is it used elsewhere?
[Connie]: DO-178 was developed for commercial aircraft, however, today DO-178B is being used for much more.  It is being used for commercial systems which aid aircraft such as ground based navigation and communication systems. Interestingly, it’s also now being used in military applications both airborne and ground based.

[Brendan]: What’s the most common misunderstanding people have about DO-178B?
[Connie]: That it involves much more than good engineering practices.  DO-178B was developed by government and industry.  They incorporated good engineering practices and some additional activities to ensure safe, reliable software.

[Brendan]: What are a few of the core software development best practices that are required by DO-178B?
[Connie]: Quality Assurance audits, requirements traceability, robustness testing, standards for design, coding and verification.

[Brendan]:  Sounds like a pretty rigorous approach to software development, which of course is a good thing given its safety-critical nature. What kind of cost burden does DO-178B add to a typical project?
[Connie]: That depends on whether the software being developed is performing highly critical functions or not.  For highly critical software, the cost of developing to DO-178B could double the average development cost.

[Brendan]:  Switching gears a bit to your role at ENEA. Out of the full range of DO-178B service offerings you provide, what’s the most common problem you’re brought in to solve?
[Connie]:  Probably the most common issue is a project that is behind schedule and needs to be certified to meet a customer deadline.

[Brendan]:  What’s the biggest change you’ve seen in aircraft systems development during your career?
[Connie]:  Growth in use of software and complex electronic hardware to develop highly integrated avionics systems.

[Brendan]: What do you think the future holds for this guidance? Do you see it evolving in a particular direction that’s different from where it is now?
[Connie]: There is an international committee currently working on the next version of DO-178. This committee is addressing issues such a object-oriented design, model based development, and further defining qualification of software tools.  This committee is also developing a companion guideline to DO-178 which will be applied to ground based software.

[Brendan]: Any final thoughts?
[Connie]:  Companies resist embracing DO-178.  However, once a company has the processes and procedures in place to ensure compliance to DO-178, their software development process is easily understood, repeatable, and maintainable.  This translates to software which is reliable, understandable, traceable and maintainable.

  • email
  • Twitter
  • LinkedIn
  • Reddit
  • DZone
  • Digg
  • Slashdot
  • del.icio.us
  • Technorati
  1. Remya

    Could you please explain to me what is Robustness Test in Avionics Proejcts and what are the Test scenarios that must be identified under this section?

  2. Anil Kumar .T

    If you broadly classify the kind of tests, they are nominal test and robustness test.
    for eg: the requirement states that the Nose Angle shall be in the range 30 to 60 deg.

    Nominal are those tests in which we drive the values for nose angle 30 , 50, 60 and the system behaves as desired.
    Robustness cases are those cases which are checked that the system has some defensive mechanism when values other than in range 30 to 60 are provided.

Using Iteration Offsets in Agile Development

Posted by Todd Landry   March 9th, 2009

I thought for today’s topic I would delve into something that many organizations have to confront when moving to Agile that is, how to structure their iterations. Many organizations will find that iterations work better if development, testing, and documentation are all done within the same iteration period. Other organizations prefer to offset the testing and/or documentation ½ or a full iteration period after the development is complete. Having lived through both, I thought it might be useful to briefly list the good, and not so good of iteration offsetting.

First the good:

* Testing and documentation are not given features that have been completed at 5 pm on the last day of an iteration, and then expected to have their work done by the following Monday.
* Many dev features are totally complete prior to documentation or testing, so the doc and test teams can start their iteration running, rather than crawling.
* The documentation team is provided with some insight as to the “big picture” of a feature (and not just a standalone story in an iteration) and can plan their documentation for those features with that information in mind. This could help reduce rework on their part.

Now the not so good:

* Development can be drawn back into a previous iteration for bug fixes.
* If demo’ing iterations is a standard part of your process, it could contain a number of bugs since it hasn’t been through any formal testing yet.
* Communication is fragmented…some teams talking about Iteration x, some about Iteration x-1.
* Possible confusion, and more difficult to manage since there are multiple iterations on the go.

Is this list complete? Probably not…but hopefully it will give you something to think about if you’re either starting Agile development, or are struggling with your current implementation. For many projects, the negatives outweigh the positives on this list. As a Product Manager, I’ve seen that many situations where offsets as described above just don’t work. If that’s the case for you, then one possible approach that I’ve seen work is to implement a code freeze 3 days prior to the end of an iteration, and the developers then become part of the testing team.

My personal preference having worked in both scenarios, is to have dev, test, and documentation all occur within the same iteration. Now, my reason is somewhat selfish…when an iteration finishes, I want to show what we’ve done with some level of comfort of the quality and then be able to close the book on that iteration at that point. If that is the approach you prefer, here is a good blog about how to set up such an iteration. Of course, as with most things Agile, there’s never a “right” answer; it’s about finding the right iteration methodology that works for your team’s culture and project goals.

  • email
  • Twitter
  • LinkedIn
  • Reddit
  • DZone
  • Digg
  • Slashdot
  • del.icio.us
  • Technorati

On Test Strategy

Posted by Johanne Leduc   February 24th, 2009

Testing can have many goals: to assess quality, to assess conformance to specification, to help managers decide whether or not to ship, etc. These all affect a test team’s approach.  Very often, it seems that “Finding Important Bugs Early” is the tester’s primary goal during a development cycle in an agile environment. It’s the ideal: find a quality impacting issue as quickly as possible after it was introduced so that the code is fresh in developer’s minds. “Finding Important Bugs Early” is a goal shared by countless test teams.

It struck me as odd, then, that James Whittaker of JW on Test in his excellent “The Future of Software Testing” series (Part 4), stated that in the future, we need to “close the gap between when a bug is created and when that same bug is detected.” In my opinion, why wait? There are plenty of things we can do to close that gap right now!

The most efficient tactics I’ve seen are the following: early involvement of testers in the development process, good unit testing, code inspection, static code analysis, continuous integration, and effective use of stubs.

Early involvement of testers is not a new concept; it’s already a part of good test process practices. For example, it is a key area of TPI (Test Process Improvement) known as the “moment of involvement”. As a bonus, I’ve always found that testers make great requirement appraisers; not only can they help assess that a requirement is verifiable, but also that it is complete, consistent and unambiguous.  Keeping testers in the loop is especially important in an agile setting where it can help make the documentation barely sufficient, as recommended by this type of development process.

We all know that unit tests are your “first line of defence” for testing executable code. To the developers to whom this task most often falls, I encourage you to ask your test team for help should the need arise. A good test team member has a way of seeing testing from a unique perspective. Use this hidden resource! You can pay the favour back when it’s time for them to use a new automation framework. It’s worth it: a good unit test suite can find many problems early that can be hard to diagnose later downstream.

Code inspection is another early detection tool. Used effectively, it can find logic and design problems at the source, not as a symptom (i.e. when system testing will stumble upon the issue). Moreover, there is no prerequisite of compilation to start it! The same is true for static code analysis. We all know the benefits so apply early, apply often, and save a lot of trouble later on.

For environments that are not of that kind where you “throw the product over the wall” to be tested, continuous integration is necessary. Otherwise, your process may be hindering the test team’s effort to Find Bugs Early. Should your testers be validating last week’s code? Last month’s? If they are, they have no chance of finding your most immediate problems. Don’t forget about bug interactions. It frequently happens that a bug is hidden behind another bug; fix one and possibly expose a slew of others. I heard a question asked once that truly captures the idea: “Why is it that when a bug dies, all the others come to its funeral?” You won’t know who’s in attendance if you’re not testing the latest code.

You may recall that I mentioned the effective use of stubs at the beginning of this post. I hope it piqued your curiosity. It’s something I learned by observing effective testers over the years. When a widget comes off the conveyor belt, they don’t wait for the thingamajig it screws into to start testing. The thingamajig may not be ready for another week! They instead whip up a mock-up of the thingamajig that works somewhat like the real thingamajig and try out their widget, pronto! Very often, the combination doesn’t work as expected and they must ask themselves: are their assumptions about the thingamajig wrong or is it the widget itself? It’s a good thing they didn’t wait until next week to discover this potential problem! This type of experiment enables early integration testing: the component didn’t work correctly in its intended environment. This prompts an investigation into the root cause: is it a bug in the component or a poorly defined interface between two components? Beware however, software stubs can fall into the same trap as a test oracle: you can make it as complex as the real thing if you’re not careful.

These are but a few of the tools for Finding Important Bugs Early. There are many other testing approaches that are not addressed here (so don’t throw away your regression tests!) This post focussed on the “early” part of the goal. What about tactics for the “important” part? Good question! I might be coerced into a follow up post one day…

  • email
  • Twitter
  • LinkedIn
  • Reddit
  • DZone
  • Digg
  • Slashdot
  • del.icio.us
  • Technorati

In-phase defect containment

Posted by Brendan Harrison   February 16th, 2009

Here’s Gwyn chatting about general software development challenges, in particular the whole goal of “in-phase defect containment” – i.e. identifying and correcting defects in the same development phase they’re created. Near the end of the video, there’s a short discussion on how this objective fits in an Agile context. With Agile’s focus on the frequent delivery of working software, in-phase containment becomes even more important, even though it’s more often associated with more formal methodologies such as CMMI and Six Sigma.

  • email
  • Twitter
  • LinkedIn
  • Reddit
  • DZone
  • Digg
  • Slashdot
  • del.icio.us
  • Technorati
  1. Zoonirord

    Thank you!

Lambda expressions in C++

Posted by Denis Sidorov   February 11th, 2009

Have just stumbled across the lamda module in boost (popular C++ general-purpose library known for extensive usage of templates and influence on C++ standard committee).

A quote:

The primary motivation for the BLL (Boost Lambda Library) is to provide flexible and convenient means to define unnamed function objects for STL algorithms …

for_each(a.begin(), a.end(), std::cout << _1 << ' ');

My first thought was: "Hmm ... a macro?" It appears it is not. The <code>_1 object is a lambda placeholder, and should be read as first parameter of lambda expression (a.k.a. unnamed function). In fact the std::cout &lt;&lt; _1 &lt;&lt; ' ' expression is automatically converted into a function-like object, that can be used with most STL algorithms (like for_each, find_if, etc.) So, instead of writing this (a traditional STL way): template <typename T> struct my_printer : public std::unary_function<void, T> {      void operator()(const T &x)      { std::cout << x << ‘ ‘; } }; // … for_each(a.begin(), a.end(), my_printer<my_element_type>());

You can use the above expression, and C++ compiler automatically creates anonymous class that represents an unnamed function. The trick is that all this "behind-the-scene" work is expressed in terms of C++ templates and heavily relies on automatic type inference, and operator overloading. Essentially the module has to overload every possible C++ operator that can be applied to the lambda placeholder, "delay" the evaluation of expression and "wrap" the computation into a callable object.

This approach apparently simulates Lisp lambda expressions (hence the name of the module) and Smalltalk/Ruby code blocks:

Smalltalk

a do: [ :⁣x | Transcript show: x; show: ' ' ]

Ruby

a.each { |x| print x, " " }

Lisp (Scheme)

(for-each (lambda (x) (display x) (display " ")) a)

Lambda expressions and code blocks are essential part of these languages and one of the things that make them consistent and fun to use. Now, this library is trying to adopt this concept into C++.

Pretty cool, but the following limitations lead me to think that this C++ implementation of lambda expressions is far from complete:

  • Boost lambda expressions are not true closures (you can not refer to "non-local" data from the block)
  • Some operators (most notably "." and assignment) can not be overloaded this way, so i = _1 and _1.my_field does not work and requires some extra C++ tricks
  • Can not use statements in this kind of code blocks, works only with expressions
  • If you make a simple mistake in this kind of lambda-expression (or change some related interface), the C++ compiler will gladly present you with a pile of human-unreadable error messages with about a dozen template instantiations with names that do not fit a line of text (no matter how wide your LCD panel is), using each other ... that's a common problem of all non-trivial template libraries

After all, this demonstrates that C++ templates and type inference are indeed powerful concepts, but still not powerful enough to redefine/extend the language in consistent way.

Another problem with this kind of smart C++ tricks is that it creates an illusion of simplicity. As always with C++ - you can not rely on this simplicity, unless you know the details of what's under the hood. If you dare to ignore implementation details you risk losing control over your own code one day.

  • email
  • Twitter
  • LinkedIn
  • Reddit
  • DZone
  • Digg
  • Slashdot
  • del.icio.us
  • Technorati
  1. Olivier Dagenais

    You forgot C#:

    
    a.ForEach( x => Console.Write( "{0} ", x ) );
    

    Full program below:

    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    namespace OliIsCool
    {
      public class Program
      {
        public static void Main(string[] args)
        {
          var examples = new List { "C++", "Smalltalk", "Ruby", "Lisp (Scheme)", "C#" };
          examples.ForEach( x => Console.Write( "{0} ", x ) );
        }
      }
    }
    

    …which anybody with the .NET Framework 3.5 can compile as follows:
    c:\WINDOWS\Microsoft.NET\Framework\v3.5\csc.exe lambda.cs

    Cheers,
    - Oli

  2. Denis Sidorov

    To Olivier: You are right – a lot of other modern languages adopt this concept one way or another. I could have referred to Java closures (http://www.javac.info/closures-v05.html) and Python lambda expressions as well.

    I have included Lisp and Smalltalk because that’s where the original idea of lambda expressions and code blocks was implemented first. And code blocks are important part of Ruby’s flexible syntax – one of the reasons why it has become so popular.

    All these languages used to have this concept as part of original language design – Lisp/Smalltalk/Ruby would be completely different languages if there were no code blocks/lambda expressions.

    In C++/C#/Java lambda expressions are just yet another convenient extension …

  3. Symonds

    Very Nice blog with a ton of informative information. Can you recommend any decent forums or social groups to join that cover these types of topics. Also, I really appreciate the fact that you approach these topics from a stand point of knowledge and information instead of the typical “I think” mentality that you see so much on the internet these days.

Resource Leaks in C#

Posted by Alen Zukich   February 3rd, 2009

I’m picking up the theme of the CWE Top 25 today (see posts below for more detail on the list itself, or check out this blog posting for a more exhaustive description) as we run into what is described as CWE-404 all the time in managed code environments.

Although most C/C++ developers recognize explicit resource management as an issue, I’ve recently found out talking to some of our customers that they are totally unaware of the need to worry about such things in Java and especially C#. I even had one customer tell me in the context of C# that the CLR will “take care” of the issue. While it’s perhaps true that eventually the Finalize() method might take care of many resources, professional developers really should take the utmost care in dealing with precious unmanaged resources like file handles, graphics handles, or database connections.

A simple but surprisingly common example in C# illustrates the point:

using System;
using System.IO;

class Blah
{
static void Main()
{
StreamReader r = null;
r = File.OpenText (“blah.txt”);
if (r.EndOfStream) return;
Console.WriteLine (r.ReadToEnd());
}
}

The StreamReader class used here encapsulates an unmanaged resource, the underlying file handle that the O/S allocates to the CLR during the call to OpenText(). As you can see, that unmanaged resource is never released back to the O/S (until such time as the application terminates, of course).

A simple statement:

r.Close();

in a finally block would clean it up.  Calling Close directly is okay but it is crucial to make sure you put that in the finally block.  The most common resource leaks that I see static analysis tools find are the ones where you see a developer has been smart enough to dispose of his resource but there is another path (such as an exception that can be thrown on a method) where the resource is not disposed.

Another easier way to dispose of the resource is to apply the “using” statement, which calls Dispose on an IDisposable object automatically for you. This code:

using (Streamreader r = File.OpenText (“blah.txt”))
{

}

is the same as writing:

Streamreader r = File.OpenText (“blah.txt”);
try
{

}

finally
{
if (r != null)
((IDisposable)r).Dispose();

}

So make sure you know that you need to dispose of certain resources.  In fairness, these can be hard issues to detect, particularly in an inter-procedural context, but good regimented use of code reviews, coupled with a good static analyzer should get you well on your way.

  • email
  • Twitter
  • LinkedIn
  • Reddit
  • DZone
  • Digg
  • Slashdot
  • del.icio.us
  • Technorati
  1. Top 5 C# quality bugs | Kloctalk

    [...] referenced by it becomes lost, but related resources are not disposed.  See my previous blog post on how some people miss this and what you need to do to fix [...]

  2. Another Resource Leak | >kloctalk

    [...] the resource leak checker.  For those not familiar with a resource leak, take a look at a previous post.  Although resource leaks apply across most languages, the place where this question keeps [...]

Software Complexity, Lines of Code and Digital Derby

Posted by Brendan Harrison   January 27th, 2009

Many of us have seen the # of lines of code (LOC) stats that get thrown around as a metric for illustrating how complex software development has become:

  • The U.S. Army’s Future Combat System is estimated at 60 million lines of code (MLOC)
  • The software that runs the Boeing 787 is almost 7 MLOC, triple that of the 777
  • GM says future cars will have >100 MLOC (that sounds high, but hey, <insert GM joke here>)

So, yes there’s a lot of code out there, it’s growing, and it’s getting more complex. It’s tough to put these numbers into perspective… Jack Ganssle has a clever column that does just that:

  • A million lines of code printed out would be 18,000 pages
  • A million lines of code will typically have 100,000 bugs pre-test
  • A million lines of code costs $20m to $40m

I won’t try to compete with Jack on the stats front since that column speaks for itself, and it’s not just the mission/safety critical systems that are trying to deal with the challenges of more code, more complexity, and less time (as in time-to-market). The consumer market is no different. Guess how much code is in the Xbox HD DVD Player? Not the whole system, just the player? 4.7 MLOC. Heck, you could fly an airplane with all that code (hopefully most of it can also be re-used on a non-obsolete disc format). Just as a point of comparison to today’s gaming systems, ask yourself how many software engineers worked on this “game system”:

Yes, I had to throw Digital Derby under the bus didn’t I? Not because I don’t have fond memories of playing this game that was about the size of carry-on luggage. In fact, I played it until the poor little conveyor belt just stopped working and I put up with the, ahem, limitations in the technology. I was actually quite patient (more patient than I am now with technology) and gave my little Digital Derby second and third chances to work properly.

More code, more complexity, impatient customers, and very little margin for error – these are the trends that are driving tool and process automation across the board in the SDLC.

  • email
  • Twitter
  • LinkedIn
  • Reddit
  • DZone
  • Digg
  • Slashdot
  • del.icio.us
  • Technorati
  1. phoenix life insurance

    Interesting stats, particularly the number of pages per million lines of code and the cost. It’s mind boggling and staggering.

  2. kelly Lossett

    Hey there.. I have a similar website… How do you control the spam? I get a ton like every day, and it takes so much time to delete it all..

  3. ProGamingWorld

    Hey! Can I ask what’s this template you are using in your blog? thanks.

CWE Top 25

Posted by Gwyn Fisher   January 13th, 2009

Another year, another list of the most obvious things that competent developers should already know how to avoid? This one even has the NSA backing it, as well as the usual laundry list of pimping vendors attempting to make PR out of anything remotely related to homeland security… Quick, where do I sign up?

OK, perhaps that’s a bit cynical, but I have to say that my usual reaction to any web application-centric security laundry list is that most developers in that space write crap code, so why should we be surprised, or expect that a new list of world-ending doom and gloom will make any difference? I mean, why the heck is SQL Injection still a cause for concern? Haven’t we learned to write prepared statements yet? According to the widely quoted experts, SQL Injection and input validation alone comprised 1.5M exploits last year. Sigh…

Was nice to see some level-headed reporting in amongst all the hyperbole, however. My favorite quote of the day comes from the BBC article linked above, with Patrick Lincoln from SRI International saying:

“The real dedicated serial attacker will probably find a way in even if all these errors were removed. But a high school hacker with malicious intent – ankle-biters if you will – would be deterred from breaking in.”

Ankle-biters. Oh, the irony… All this money being spent on what? A barrier to deter script kiddies…

Maybe it’s just me, but I can’t help myself reflecting back to 1999. If you had code you’d written properly, that wasn’t lazy, that was expected to be around for a while, you simply weren’t cool enough to grab the big Y2K contracts. You weren’t cool enough to be worried about airplanes falling out of the sky. You were just a decent programmer doing a decent job.

Now of course, all the cool kids are worried about web site security. Why? Well as with everything that sounds noble and just on the outside, it probably has something to do with money, let’s face it. And cool-looking eye glasses with those little wire frames (oh yeah, you know you want them…). Because now you’re not a maintenance coder, you’re a code forensics expert. You’re not patching up some piece of garbage that should never have left the test server, you’re implementing cutting-edge perimeter security measures. You’re not hiding your head in shame about just how misguided our industry has become, you’re trumpeting it on the front page of every news outlet in the world…

And if you’re really cool you’re already fitting yourself out for your Steve Jobs lookalike outfit, because now, people, now we have the NSA telling us that the world is going to hell in a hand-basket, but if we’re quick enough, if we throw enough buzzwords around, maybe we’ll land ourselves a cushy gig as a maintenance programmer. Err.. I mean an architecturally-motivated, build-security-in, leading-from-the-trenches, application security infrastructuralizer kind of guy. Yeah, that sounds about right…

OK, don’t get me wrong… buzzwords aside, CWE is an awesome endeavor being run by some very smart and motivated people. And hey, this list will probably help me sell more of my software, which is always good, right?

But will this list of the Top 25 “dumb mistakes” change the world? Will it lead to a greater comfort for those of us waiting for the next terrorist attack to scare us senseless? Somehow I doubt it… But maybe, just maybe, it’ll stop grandma’s password making its way to the Ukraine next month. And that’s kind of the point. Web sites don’t run the world, but they can ruin it for you in a very personal way. Missiles aren’t going to fall out of the sky if your web site is vulnerable to path injection (or at least, let’s really hope not), but if your bank account is suddenly not yours anymore they might just as well have done.

But much as Hollywood’s brief dalliance with attempting to relate to developers by having some idiot repeatedly generate a 404 while “hacking the man” was obviously insane, hoping that a new list (“Larger and now with added scare factor!!!”) will have much impact on the security of things outside of web sites (like embedded device controller logic, or missile guidance systems, or air traffic management environments, or stop lights, or stuff that really, you know, matters) seems to this consumer to be equally off-base.

As an educational instrument I wish it all the success in the world. Better web applications would make lots of peoples’ lives easier. I’d really like to be able to visit any old web site and think that my personal details (“likes rock climbing, sushi and long beach walks…”) aren’t automatically open season for anybody with half a brain and too much time on their hands.

But here’s the bottom line: you don’t get security by enforcing a list. CWE is way, way bigger than this list of “Most Dangerous Programming Errors.” And it needs to be. So don’t go buying that shiny new product because it “Conforms to CWE 25” (or whatever this thing lands up being called). And don’t use the Top 25 to interview your new security consultant. Because what’s outside that list is just as important as what made the cut. Security is a big deal, it’s not a list.

  • email
  • Twitter
  • LinkedIn
  • Reddit
  • DZone
  • Digg
  • Slashdot
  • del.icio.us
  • Technorati
  1. saphywollussy

    yo, kloctalk.klocwork.com great name for site)))
    ————————

  2. MaryKate

    Good morning! Very interesting subject.
    Certainly can be and so!

  3. Fleedsist

    kloctalk.klocwork.com – cool sitename man)))
    ————————