...
Noncompliant Code Example (Zune 30)
This noncompliant code example shows incomplete logic when converting dates. The code appeared in the Zune 30 media player, causing many players to lock up on December 30, 2008, at midnight PST. This noncompliant code sample example comes from the ConvertDays
function in the Realreal-time clock (RTC) routines for the MC13783 PMIC RTC. The ConvertDays
function takes a This noncompliant code sample takes the number of days since the MS-DOS epoch ( January 1, 1980), and returns the corresponding day, month, and year values. This code sample takes the number of days, and computes the correct year and number of days since January 1 of the correct year.
The flaw in the code occurs when days
has the value 366, because the loop never terminates. This bug manifested itself on the 366th day of 2008, which was the first leap year in which this code was active.
Code Block | ||
---|---|---|
| ||
#define ORIGINYEAR 1980 UINT32 days = /* number of days since January 1, 1980 */ int year = ORIGINYEAR; /* ... */ while (days > 365) { if (IsLeapYear(year)) { if (days > 366) { days -= 366; year += 1; } } else { days -= 365; year += 1; } } |
...
Compliant Solution (Zune 30)
This proposed rewrite is provided by http://www.aeroxp.org/2009/01/lesson-on-infinite-loops. The loop is guaranteed to exit, as days
decreases for each iteration of the loop, unless the while
condition fails, and the loop consequently terminates.
Code Block | ||
---|---|---|
| ||
#define ORIGINYEAR 1980 UINT32 days = /* input parameter */ int year = ORIGINYEAR; /* ... */ int daysThisYear = (IsLeapYear(year) ? 366 : 365); while (days > daysThisYear) { days -= daysThisYear; year += 1; daysThisYear = (IsLeapYear(year) ? 366 : 365); } |
This compliant solution is for illustrative purposes and is not necessarily the solution implemented by Microsoft.
Risk Assessment
Failing to take into account all possibilities within a logic statement can lead to a corrupted running state, potentially resulting in unintentional information disclosure or abnormal termination.
...