Showing posts with label visual studio. Show all posts
Showing posts with label visual studio. Show all posts

Sunday, 15 November 2015

Intellisense Bugs

I've posted about this before, but my use of C in Visual Studio isn't supported by Intellisense, however it is supported by the compiler.  This means that my code compiles without warning or error, but it's more difficult to edit as the editor falsely claims there are errors.

So I sent a report to Microsoft via their easy to use customer feedback menu:


Some time later, perhaps several weeks, I received email from a program manager on the Visual C++ team asking for further detail.  I compiled two cases, both in the same narrow usage of C, and send them in.

Here's one related to struct initialisation.


And another related to anonymous unions.


I don't hold out hope that Microsoft will fix them any time soon, or even fix them at all.  Their focus is on meeting more recent C++ standards, from reading their blog posts, and this is a niche part of their C support.

But fingers crossed.

Tuesday, 30 June 2015

MSVC2013, Intellisense and anonymous struct/union bugs

One of the improvements in the C11 standard, is the addition of anonymous structs and unions.  This means that the unnamed element flattens, and all members of the struct or union can be referred to at the same level as the struct or union itself (as long as there are no naming conflicts).

A simplified example use I make of an anonymous struct inside an anonymous union is:

struct my_event_s {
    enum my_event_types event_type_id;
    union {
        struct {
            enum my_key_event_types key_event_type_id;
            union {
            /* Further fields here.. */
            };
        };
        struct {
            enum my_mouse_event_types mouse_event_type_id;
            union {
            /* Further fields here.. */
            };
        };
        struct {
            enum my_touch_event_types touch_event_type_id;
            union {
            /* Further fields here.. */
            };
        };
    };
};
It's a pleasure to program with. But then you reach the stage where you have a different struct, and you want to incorporate a shared anonymous struct (and likely also union) in that. In my case, it was my complete key struct, excerpted from above:
struct {
    enum my_key_event_types key_event_type_id;
    union {
    /* Further fields here.. */
    };
};
One thing you might try, is what I tried. Give the struct a tag, and than just place an anonymous reference to it in the encompassing struct or union.
struct my_key_event_s {
    enum my_key_event_types key_event_type_id;
    union {
    /* Further fields here.. */
    };
};

struct my_event_s {
    enum my_event_types event_type_id;
    union {
        struct my_key_event_s;
        struct {
            enum my_mouse_event_types mouse_event_type_id;
            union {
            /* Further fields here.. */
            };
        };
        struct {
            enum my_touch_event_types touch_event_type_id;
            union {
            /* Further fields here.. */
            };
        };
    };
};
This compiles cleanly, but intellisense will choke on it, and find errors in the code. Intellisense will accept an anonymous struct or union member defined this way within a struct itself. But the moment you try it within a union, then it will choke on not only the struct definitions it accepted up until that point, it will also choke on the union definitions.


It turns out that this is a non-standard (not part of the official C11 standard) feature that Microsoft supports.  It might be argued that usage of it should be avoided, because of this, but with GCC supporting it via the -fms-extensions flag, it is pretty portable.

Personally, I see anonymous structs and unions as a great addition to the C language, that reduce friction without introducing complexity.  And this Microsoft extension should have been a natural part of the standard.  The only downside to it, is that it's actually almost unusable when you're using Microsoft's Visual Studio!  If intellisense chokes on this, then a lot of the value of the editor is undermined, as it's help becomes misleading.

For the record, I'm using Visual Studio 2013, community edition, update 4.  There's a new release of Visual Studio 2015 coming up, which will hopefully mean fixes for this (but who really knows?)  And ideally, a new release of the community edition.

Sunday, 15 July 2012

Compiling Brogue v1.6.4 with MinGW

Brogue is a very user friendly roguelike.  It implements a lot of the things that I have always wanted whenever I play a "tile-based" text game of this kind.  That includes support for mouse over events, and giving visual indications of where on the map the selected item is, and the like..



It comes with source code, which should allow me to make my own changes, but unfortunately with programming.. it's never that simple.
In an ideal world, I could just create a new project in Visual Studio, but the code is not platform independent and requires dirent.h and associated functionality.  太麻烦了... so MinGW it is.  The option of using the Code Blocks IDE and it's version of MingW is present, but that's just more complication of a different kind.
  1. Have a MinGW/msys compilation environment set up.
  2. Open a MinGW shell.
  3. Go to the "Brogue Source" directory that comes with the Windows Brogue binaries.
  4. Download and extract: libtcod-1.5.1-mingw32.zip (from here).  It is already compiled.
  5. Download and extract: SDL-devel-1.2.14-mingw32.tar.gz (from here).  It is not necessary to compile it as the headers are all that are required.
  6. Apply patch below for "tcod-platform.c".
  7. Edit "makefile".
  8. Line 3: Correct CFLAGS with -DBROGUE_TCOD instead of -DBROGUE-TCOD.
  9. Line 23: Add the missing "line continuation" character '\'.
  10. Line 32: Correct the g++ linking command modifying "-lSDL.dll" to be "-lSDL".
  11. Line 32: Correct the g++ linking command adding "-L$(LIBTCODDIR)/" so that g++ can find "SDL.dll" and "libtcod-mingw.dll".
  12. Line 32:  Extend the g++ linking command adding "-static-libgcc -static-libstdc++" so that the compiled executable can be run without a dialog box saying "The program can't start because libgcc_s_dw2-1.dll is missing from you computer. Try reinstalling the program to fix this problem.".
This gives you a replacement "brogue.exe" binary which can be copied up to the outer "Brogue v1.6.4" directory, and does not have any further cumbersome MinGW dependencies.

Patch for "tcod-platform.c":
< #include <SDL/SDL.h>
---
> #include <SDL.h>
293c293,295
<               bufferedKey = TCOD_console_check_for_keypress(TCOD_KEY_PRESSED);
---
>               TCOD_sys_check_for_event(TCOD_EVENT_KEY_PRESS | TCOD_EVENT_MOUSE, &bufferedKey, &mouse);
>       } else {
>               TCOD_sys_check_for_event(TCOD_EVENT_MOUSE, &bufferedKey, &mouse);
390c392
<               key = TCOD_console_check_for_keypress(TCOD_KEY_PRESSED);
---
>               TCOD_sys_check_for_event(TCOD_EVENT_KEY_PRESS | TCOD_EVENT_MOUSE, &key, &mouse);

The patch makes up for what seems like custom changes to the libtcod DLL that comes with Brogue.  Out of the box, libtcod does not update the last known mouse state unless the using application polls mouse state.

Edit: Added all the other extra steps I had forgotten to mention, as I have gone through this process many times now.

Wednesday, 25 April 2012

Paint.NET file type plugin development

Paint.NET isn't very well documented in terms of what you need to do to develop a plugin.  And if your plugin is intended to add support for a new file type, rather than add a new image-related effect.. then there's even less information.  Luckily you can download a third-party template and use that as a base.

Ensure the project is set to use the .NET 3.5 framework (mine defaulted to 4.0).  If this is not done correctly, then your plugin will be ignored by Paint.NET.


Copy your compiled DLL from the Visual Studio project build directory to the FileTypes folder within your Paint.NET installation.


And that's pretty much the compile and test (or installation) cycle covered.  Debugging is another matter.  I'm not sure its possible with Visual Studio Express, but I think it is with the full version.  I had to make do with custom message boxes, but it could be worse! :-)

Friday, 16 December 2011

Gyp and libuv

One open source project that I've heard a bit about recently is libuv.  A cross-platform asynchronous IO library, it is something that I can plug into Kristjan Valur's stacklesslib module.  And all the work writing the Python bindings has already been done by Saúl Ibarra Corretgé in his pyuv project.

Anyway, I spent some time today getting it compiling for Windows and thought I would post a note about gyp, so that I could remember to avoid the same problems in future.  Gyp is a pretty handy build system. Just define the gist of what needs to be compiled in a mildly arcane mark-up, and it will churn out Makefiles, Visual Studio projects and solutions and a range of other things.  However, as with most programming related things, it is the little details that trip you up and cause you to waste your time.

Missing include files

If you are compiling with Visual Studio 2008, and it includes inttypes.h or stdint.h, errors will occur as these files will not be present.

...
libuv\include\uv.h(54): fatal error C1083: Cannot open include file: 'stdint.h': No such file or directory
...
Apparently the solution to this, after a lot of googling on what constitutes a wi-fi connection over here in New Zealand,  is to download something like the custom msinttypes versions of these files.   And then bung them somewhere Visual Studio will find it.. wherever that is.

Overriding gyp settings

If you are compiling a static library with Visual Studio using gyp, it will start with a range of default settings.  You will not be able to override these settings no matter where you put your own custom versions in your gyp configuration file.  The specific problem I had was that Python extensions are compiled with a RuntimeLibrary setting of MultiThreadedDLL and libuv is compiled with a different setting of MultiThreaded.  These are of course incompatible, and a variety of compilation errors are caused by it.
...
LIBCMT.lib(crt0dat.obj) : error LNK2005: __amsg_exit already defined in MSVCRT.lib(MSVCR90.dll)
...
LINK : warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library
LINK : warning LNK4098: defaultlib 'LIBCMT' conflicts with use of other libs; use /NODEFAULTLIB:library
LIBCMT.lib(crt0.obj) : error LNK2001: unresolved external symbol _main
build\lib.win32-2.7\pyuv.pyd : fatal error LNK1120: 1 unresolved externals
In order to force this gyp setting to change from the default, it needs to be defined within a conditional expression.  The default setting is also a conditional expression, and .. well.. work it out.  Maybe it's in the documentation somewhere, but not in a clearly stated way that I could find.

Monday, 7 June 2010

Visual Studio 2010 & profiling

Not having the ability to profile in Visual Studio 2008 Professional, rather than upgrading to the Team System variant, I chose to try obtain Visual Studio 2010 Ultimate. After recompiling all my static library dependencies, I was ready to try out the profiler.


The first result was a little demoralising.


Every function in which time was being wasted, was lumped in as part of the function body of the main function. I disabled the default exclusion of small functions from instrumentation, but that merely included a raft of unimportant functions that deserved to be excluded. A bit of googling about missing functions in Visual Studio profiling yielded the following page. While not entirely relevant, it did suggest making sure that the PDB files were present. And after a bit of project configuration changes, in addition to judicious use of ProcessMonitor to make sure they were in the right place, the problem was indeed solved.



One of my original suspicions was that the file access was a cause of the slow loading process, and indeed the above report shows that 30% of the loading time is spent there. It turns out that anytime a file is accessed by name, the routines iterated over all the files in the archive until it found the one of the given type and with the given name. By adding a dictionaries for each file type, indexing the different files to a pointer to their archive header, this should just go away.

The first solution which came to mind was Sean's Tool Box, a public domain header which includes a raft of useful C functionality, including the ability to create custom dictionaries. It provides a default string to pointer dictionary stb_sdict which is almost suitable enough to use, but the original Soulfu code only matches on the first eight characters of a filename whereas this does full string comparisons and hashes. I had to replicate and extend it, in order to get a version that suited my needs.


#define STB_DEFINE
#include "stb.h"

unsigned int sdf_file_name_hash(char *str)
{
unsigned int hash = 0;
unsigned int i = 0;
while (*str && i < 8)
{
hash = (hash << 7) + (hash >> 25) + *str++;
i++;
}
return hash + (hash >> 16);
}

stb_declare_hash(STB_noprefix, pheadermap, pheadermap_, char *, SDF_PHEADER);
stb_define_hash_base(STB_noprefix, pheadermap, void*arena;, pheadermap_, pheadermapinternal_, 0.85f,
char *, NULL, STB_SDEL, stb_sdict__copy, stb_sdict__dispose,
STB_safecompare, !strcmp, STB_equal, return sdf_file_name_hash(k);,
SDF_PHEADER, STB_nullvalue, NULL);

pheadermap *pheadermap_array[SDF_FILETYPE_COUNT];
stb.h is composed of macros so if you get an argument wrong, the C compiler more often than not gives a confusing error message. The main problem I had was not realising that the macro arguments styled along the form return function(arg); needed to be specified that way. There is a potential bug here which I ignoring for now, which is the use of !strcmp which breaks the behaviour of only checking the first eight characters.

At one stage I moved the #include to the top of the file, which caused problems. As I am developing on Windows, stb.h defines symbols that are named the same as those which come from the standard Windows headers. If these get defined before the Windows headers are first included, then the Windows headers will choke.


And the file access overhead is now removed, leaving the huge 75% of time spent within the display_loadin function. All this function does is draw the "Loadin'" text and update the progress bar below it, so this is surprisingly odd.


However this is done every iteration of any loop that partipates in updating the loading screen. By only calling this function every 1/10th of a second rather than pointlessly often, this overhead should also go away.


At this point the majority of the loading time is spent in external code, doing things like decompressing ogg or jpeg files. While it took me a night to download the Visual Studio ISO to New Zealand, and a full day to get everything compiling and profiling, it was time well spent. Possible next steps are looking at Sean's ogg vorbis or jpeg and png decoders.

Edit: Reverting the upgraded VS2010 solution, and trying the changes with VS2008 I see a decreased startup time from 3m50s to 0m25s.

Sunday, 6 June 2010

Visual Studio 2008 & profiling problems

The project I am currently working on is an open sourced project that was originally written for speed, at the cost of clarity and maintainability. While the changes the community have made to clean it up have served that purpose, they have also increased the time it takes to start the game from almost nothing to around four minutes.

When testing every change means sitting through this delay before the results can be seen, development becomes overly time consuming. In order to address this problem, I decided to profile starting up the game. I have Visual Studio 2008 Professional installed, and unfortunately it does not come with a profiler. If you want to profile with Visual Studio 2008, you need to go with its more extensive (and expensive) Team System variant. But there are references to installing standalone extras which in theory allow command line profiling with the less extensive variants.

The first step was downloading and installing the standalone profiler from MSDN. With this installed and a DOS window open, changing the current directory to that of the executable to be profiled. Then adding the profiling tools into the PATH environment variable, so that they could be used locally.

set path=%path%;C:\Program Files (x86)\Microsoft Visual Studio 9.0\Team Tools\Performance Tools


Instrumenting

Profiling the executable requires that it be instrumented.

>vsinstr _SoulFu_.exe
Microsoft (R) VSInstr Post-Link Instrumentation 9.0.30729 x86
Copyright (C) Microsoft Corp. All rights reserved.

Error VSP1011 : Unable to obtain debug information. Link with
the /Profile linker switch.

The executable that is to be profiled needs to have been linked with the /profile switch, which can be done with a simple recompile after changing the corresponding configuration option.



But now Visual Studio fails to compile the solution, with the message LNK2033: bad dll or entry point shown for several failing projects. Googling for this indicates that link.exe and msobj80.dll need to have the same version. It turns out that msobj80.dll which is located in C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE, has been clobbered by an older version during the installation of the performance tools. After more googling, I located a barely comprehensible post by an English as a second language poster, who suggested replacing it with the version in C:\Program Files\Common Files\microsoft shared\VSA\9.0\VsaEnv. Then as this Intel article indicates, killing the mspdbsrv.exe process with the task manager. After this experience, I could now recompile the solution with the required profiling switch.

Trying the instrumentation again..
>vsinstr _SoulFu_.exe
Microsoft (R) VSInstr Post-Link Instrumentation 9.0.30729 x86
Copyright (C) Microsoft Corp. All rights reserved.

File to Process:
_SoulFu_.exe --> _SoulFu_.exe
Original file backed up to _SoulFu_.exe.orig

Successfully instrumented file _SoulFu_.exe

Profiling

The process goes along these lines, the profiler is first started, then the instrumented executable is run and exercised in the ways that would benefit from profiling, then the profiler is stopped and the resulting profiling information is processed.

Starting the profiler..
>vsperfcmd /start:trace /output:soulfu.vsp

Microsoft (R) VSPerf Command Version 9.0.30729 x86
Copyright (C) Microsoft Corp. All rights reserved.
Running the instrumented executable..
>_SoulFu_.exe
Stopping the profiler..
>vsperfcmd /shutdown
Microsoft (R) VSPerf Command Version 9.0.30729 x86
Copyright (C) Microsoft Corp. All rights reserved.


Shutting down the Profile Monitor
------------------------------------------------------------
Processing the profiling data..
>vsperfreport soulfu.vsp /summary:all

Microsoft (R) VSPerf Report Generator, Version 9.0.0.0
Copyright (C) Microsoft Corporation. All rights reserved.

File opened
Successfully opened the file.
A report file, soulfu_Header.csv, has been generated.
A report file, soulfu_MarksSummary.csv, has been generated.
A report file, soulfu_ProcessSummary.csv, has been generated.
A report file, soulfu_ThreadSummary.csv, has been generated.
...
With the .vsp and .csv files in the same directory, PerfConsole can now be run. At its internal prompt, load soulfu.vsp gets it to load in the profiling information. However, the information it displayed was confused with the external and internal time percentages being large numbers rather than actual percentages. It also was unable to determine whether the data was intrument or sample, so defaulted to sample mode. This meant I was unable to see the call tree and other useful information, presuming that information would have been displayed correctly.

A little more searching indicated that I needed to set environment variables to indicate whether the instrumentation data was what classified as sampled or instrumented. I decided to try again, but profiling with explicit instrumentation, rather than sampling.

>VsPerfCLREnv /traceon
Enabling VSPerf Trace Profiling of managed applications
(excluding allocation profiling).

Current Profiling Environment variables are:
COR_ENABLE_PROFILING=1
COR_PROFILER={6468ec6c-94bd-40d3-bd93-4414565dafbf}
COR_LINE_PROFILING=0
COR_GC_PROFILING=0
Rerunning the profiler, the instrumented executable and then stopping the profiler gave me a new .vsp file for processing.

So I started the processing step again and waited..
>vsperfreport soulfu.vsp /summary:all

Microsoft (R) VSPerf Report Generator, Version 9.0.0.0
Copyright (C) Microsoft Corporation. All rights reserved.

File opened
Successfully opened the file.
A report file, soulfu_Header.csv, has been generated.
A report file, soulfu_MarksSummary.csv, has been generated.
A report file, soulfu_ProcessSummary.csv, has been generated.
A report file, soulfu_ThreadSummary.csv, has been generated.
I waited and waited. I left it going overnight, for over nine hours. It sat at around 50% usage of the CPU core it was running on for this entire time.


Next steps

At this point I gave up. Between the corrupt information shown by PerfConsole and the inability to generate .csv files for explicitly instrumentated profiling data I have wasted enough time on this. My next step is to just download Visual Studio 2010 Ultimate from MSDN and use that. I am going to have to waste more time rebuilding dependencies, but on the other hand I will get visual profiling tools and hopefully it will just work.

Friday, 4 June 2010

Visual Studio 2008 & Intellisense problems

I'm working on a solution where a source file soulfu.c, is used by two different projects. The least significant project defines the _SOULFU_LIB preprocessor definition, while the most significant project does not. When soulfu.c is edited, Visual Studio 2008 is unable to differentiate between which project the file is being edited on behalf of.

This is illustrated by the following screenshot. Visual Studio assumes that _SOULFU_LIB is defined and therefore the large section of code that is covered can only be edited without the benefits of Intellisense.


Despite a decent amount of web searching I am unable to find any reference to a solution for this problem. I did encounter one other person having this problem, but the only helpful solution they were given was to wait for Visual Studio 2010.