Posts

Showing posts with the label Debug

Debug a C/C++ application which requires root privileges using Eclipse CDT

Image
Spanish version / Versión en Español Hi! It's been a long time, but this blog is not dead! It just happened that so far, I haven't ran into a case which hadn't been documented by someone else already. I am glad to inform that today, I found good enough reason to make a post, since the information was already in the web, but scattered among different sites. So I am putting it together here for future reference. Going back to the problem described in the title: initially, you would think that for a scenario like this, the only way is to run Eclipse itself with root privileges. However, security concerns aside, doing so would imply losing all the Eclipse settings, because they would be associated to the original non-root user. The optimal solution would be to refactor the application to avoid requiring root privileges. Sometimes, that can be achieved without even touching the app's source code. For example, it might be possible to define a user group with the...

Depurar una aplicación C/C++ que requiere privilegios de root usando Eclipse CDT

Image
Versión en inglés / English version ¡Hola! Ha pasado mucho tiempo, ¡pero este blog sigue con vida! El problema fue que en todo este tiempo, todos los temas con los que me topé ya estaban documentados en detalle en la web. Es un placer informar que hoy encontré una buena razón para postear, ya que la información estaba en la web, pero desperdigada entre diversos sitios. Así que la recopilé aquí para referencia futura. Volviendo al problema mencionado en el título: inicialmente, uno pensaría que para un escenario así, la única solución sería ejecutar Eclipse con privilegios administrativos, o sea como root . Sin embargo, más allá de los potenciales problemas de seguridad, hacer eso implicaría perder toda la configuración de Eclipse, porque la misma está asociada al usuario original, que no es root . La mejor solución sería refactorizas la aplicación para que no requiera privilegios administrativos. A veces, eso puede hacerse incluso sin tocar el código fuente. Por ejemplo, ...

How to handle a Win32 Unhandled Exception error in a Release build

Image
Spanish version / Versión en Español You might have run into this scenario: a Windows application, which uses native/unmanaged C++, works perfectly fine in your development box. But in the productions environment, it crashes and a message like this one appears: Sometimes, that exception can be caught with a try-catch block. But in other cases such as an Access violation, division by zero and similar ones, it can't be caught. Windows offers a specific solution for this: the __try - _except block, but it has some limitations . Specifically, it can only capture SEH exceptions. And those must be enabled on a project basis for this to work. A better alternative, which is the one we'll analyze next, consists in using the SetUnhandledExceptionFilter function from the Kernel32.lib library . This allows us to catch the exception, but how can we get more information? Well, it is possible to obtain a stack trace by using additional functions from the psapi.lib and dbghlp...

Cómo manejar Win32 Unhandled Exception en Release

Image
Versión en inglés / English version Probablemente se hayan topado con este escenario: una aplicación Windows, que usa C++ nativo/no manejado, funciona perfecto en la máquina de desarrollo. Pero en las máquinas de los clientes a veces sale un message box similar al siguiente: A veces, esa excepción puede capturarse con un bloque try-catch. Pero en ciertos casos como Access violation, división por cero y similares, no se puede capturar. Una alternativa específica de Windows es usar un bloque __try - __except, pero tiene sus limitaciones . Concretamente, sólo puede capturar excepciones de tipo SEH. Y las mismas deben estar habilitadas a nivel proyecto. Una mejor alternativa, que es la que estudiaremos a continuación, consiste en usar la función SetUnhandledExceptionFilter de la biblioteca Kernel32.lib. Esto nos permite capturar la excepción, ¿pero cómo obtener más información? Es posible obtener un stack trace usando unas funciones auxiliares de las bibliotecas psapi.lib ...

C++: Project always out of date when running in Visual Studio

Spanish version / Versión en Español A little while ago, I ran into a weird problem. My application compiled fine in Visual Studio 2010, but when I tried to Debug it, it would ALWAYS say that a certain C++ project (always the same one) was out of date and asked me if I wanted to build it. But if I had just done so! The first thing you'll want to try is to do a full clean and build of your solution. If after that the problem is still there, try this: Enable logging for C++ projects build. Download, unzip and run DebugView from SysInternals. Those people make great tools, check them out! Add a filter to Debug View using the name of your project. If you don't do this, DebugView will drown you in a sea of log messages. Build again. Take a look at DebugView's log messags. In my case, my error was something like this [42216] Project 'YourCrazyProject.vcxproj' not up to date because build input 'YourWackyReference' is missing. Delete or fix th...

C++: Proyecto siempre desactualizado al correr en Visual Studio

Versión en inglés / English version Hace poco me pasó que compilaba mi aplicación exitosamente, pero al correrla el Visual Studio 2010 me decía que cierto proyecto estaba desactualizado y que si quería compilarlo. ¡Pero si acabo de compilarlo, macho! Bueno, la solución es arremangarse y activar los mensajes de log del compilador de C++, algo que los de Mocosoft dejaron bastante oculto. Resumiendo: Probar haciendo un Clean Solution y compilando otra vez. Si eso no resuelve el problema, seguir al paso 2. Activar el logging para la compilación de proyectos C++. Bajar, descomprimir y ejecutar DebugView de, cuándo no, SysInternals. Unos capos. Agregarle un filtro al DebugView con el nombre de nuestro proyecto. Si no hacemos esto, nos ahogaremos en un mar de mensajes. Compilar de nuevo. Buscar un mensaje de este estilo: [42216] Project 'TuProyectoLoco.vcxproj' not up to date because build input 'TuDependenciaColgada' is missing . Borrar o corregir esa ...

Tracking down exceptions in Visual Studio 2008

Spanish version / Versión en Español If you ever looked at Visual Studio's Output window and saw a "first chance exception" message and a weird error which is not even documented in the MSDN, and you were not patient enough to debug step by step until the line popped up in the Output window again, I have a solution for you. It also applies if you want the Visual Studio debugger to break every time an exception is thrown and/or unhandled by your code. The secret is Visual Studio's Debug->Exceptions dialog. Here we can check which exceptions to track down, including .NET, native C++, ATL and stuff. In the particular case of C++ exceptions, for this mechanism to work, certain conditions must be met: When installing Visual Studio, the C++ runtime was installed In the C++ project's general properties, "Use of MFC" is set to "Use MFC in a static library" or "Use Standard Windows Library". In the project's properti...

Rastreando excepciones en Visual Studio 2008

Versión en inglés / English version Si alguna vez miraron el Output del Visual Studio y vieron "first chance exception" y un mensaje raro que no aparecía documentado ni en la MSDN, y no les daba la paciencia para hacer paso a paso con el debugger hasta que apareciera la línea en el Output, ésta es la solución. También si les salta alguna excepción de .NET y el Visual no les pone el breakpoint cuando eso ocurre. El secreto está en el diálogo Debug->Exceptions. Aquí podemos tildar las excepciones que queremos detectar, para que se ponga un breakpoint cuando salten. Pueden ser generadas por .NET, el runtime de C++, ATL y otras yerbas. En el caso particular de las excepciones de C++, para que este mecanismo funcione, debe cumplirse que: Al instalar el Visual, se instaló el runtime de C++ En las propiedades generales del proyecto, "Use of MFC" está seteado en "Use MFC in a static library" o "Use Standard Windows Library". En las...