5

We have some C code that is throwing a STATUS_STACK_BUFFER_OVERRUN error (0xC0000409) once in a while. I can reproduce that error using the C code below. I'm using Visual Studio 2013 Update 4 on Windows 7, and I'm compiling with the /EHa and /GS flags. However, I have been unable to catch the error programmatically. The code never enters my __except block; instead, Visual Studio pops up a few dialog boxes informing me of the stack corruption. I realize that once this error occurs, the state of the program is in doubt; I'm merely trying to capture the error in hopes of locating where it is occurring in our production code. Is there a way to handle this error programmatically?

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#pragma warning(disable: 4996) // strcpy

void vulnerable(const char* str)
{
   char buffer[10];
   strcpy(buffer, str); // overrun the buffer
}

int main()
{
   __try
   {
      char large_buffer[] = "This string is longer than 10 characters.";
      vulnerable(large_buffer);
   }
   __except (GetExceptionCode() == STATUS_STACK_BUFFER_OVERRUN)
   {
      printf("error"); // never getting here
   }
}
Whitney Kew
  • 215
  • 3
  • 13
  • 2
    You can't; overrunning the buffer is not guarenteed to trigger an error. Redesign your function to not rely on this. – Colonel Thirty Two Nov 24 '15 at 17:50
  • 2
    The CRT implementation assumes that the process was compromised. So SEH cannot be trusted anymore either. It intentionally bypasses it and ensures that a exception handler installed with SetUnhandledExceptionFilter() cannot see it either. All you can get is a debugger break. Which is of course the proper way to fix this bug. – Hans Passant Nov 24 '15 at 18:02
  • What are `__try` and `__except`? That is no standard C. – too honest for this site Nov 24 '15 at 18:04
  • @HansPassant: Thank you for your answer. Our code is running on a machine that doesn't have a debugger installed, and putting a debugger on the machine isn't an option, so if a debugger break is the only way to "capture" the error, do you have any thoughts as to how I can start narrowing down where this error is occurring? – Whitney Kew Nov 24 '15 at 18:38

0 Answers0