save data from visual studio memory window - visual-studio

Is any possiblility to save some buffer in any binary file, to view in standalone hex editor.
For example, can I save data from memory window in VS to hex dump, but not as ASCII ?

user142207 has done a great job investigating VS internals, I recommend that solution.
I have another way that was invented by my colleague, Sergey S.,
which is very useful:
Windows:
Use a couple of functions ReadProcessMemory/WriteProcessMemory. It needs a standalone app that calls these functions with a target process id like:
dumper.exe <debugged process id> <memory_start_addr> <memory_length>
This app can be called directly during the VS debug session(compared to Linux, which doesn't have such a possibility). We can capture the memory address in the watch window, then pass the address to the dumper and voila. As user142207 says in his article, it's very useful in long-time recompiled projects.
Linux/MacOS has different approaches. For example: from the gdb console, use command dump memory. This command can also be used directly during the debug session.

StNickolay has the answer that references some tool called "dumper" but, somehow, I was unable to find it around the net (also, user142207 is long gone). So I created the very same tool - it opens up running process (even with a debugger attached) and copies portion of its memory into the file. Very useful when you want to store some structure for later and don't want to struggle with VS Memory View "copy" output. Enjoy!
https://github.com/Alexx999/Dumper

I don't know if this helps, but you can use WinDbg's .writemem command. It takes a filename and a memory range and dumps it (as binary) to the disk.

There is an extension for that: https://marketplace.visualstudio.com/items?itemName=OvidiuIonescu.VSDebugTool. It opens its console in VisualStudio window and allows dumping memory to file and a couple of other memory operation (enter "help" in the console for details).
Also, some hex editors (e.g. Hex Editor Neo) can browse process memory as an ordinary file. Maybe you'll find a free editor with this feature too.

The watch window in the Visual Studio debugger can run functions, if you are debugging your own code, you can just add some function to your code for saving a buffer to file and call it from the watch window.
for example:
void WriteToFile(char* name, void* buffer, size_t size)
{
FILE* fp;
fopen_s(&fp, name, "wb");
fwrite(buffer, 1, size, fp);
fclose(fp);
}
Then just type something like this in the watch window:
WriteToFile("c:\\temp\\dump.dat", buffer, len)

I suspect that you can get what you want from the ClrMD, you can then same the data however you want.
If you literally want a core dump then WinDbg might be what you're looking for?
There is also this post on MSDN Blogs: https://blogs.msdn.microsoft.com/dondu/2010/10/24/writing-minidumps-in-c/
It describes how to create dump-ish things in .NET programmatically.

Related

How can I stop the execution window from closing immediately?

Using Windows, I entered a command in my cmd window to run an executable file that has your basic "Hello, world!" line printed by the program. When I enter the "start out.exe" command though, a window opens and closes in a quick second. I'm guessing that this window is the window where the hello world message is being printed, but it closes so quickly (maybe because the program is finished). Is there some sort of setting I have that is causing the window to close immediately? Is that just the default? And if so, is there a setting or something that I can change to prevent the window from closing immediately (without changing the nature of the program)? Thanks in advance for your help. I've seen some similar questions, but the ones I have seen are specifically for Linux/Unix or suggested to change the program itself.
If you possess .PDB files, generated at build time (symbols of .EXE file) and required .DLL libraries for your program (In your case those might not be required due to the simple nature of a "Hello World" program), you could try to open the executable as project in Visual Studio and attach a debugger to it, using breakpoints to stop program executions before main returns. This article shows how to do it as a proof of concept.
Open .EXE file by opening VS and navigating to File-Open-Project/Solution and selecting the executable file, then right-click on your "solution" and press Debug-Start new instance. PDB and DLL files should be in the same folder as EXE file.
If you also don't have source code available of the program, follow this advice in order to try to debug it:
To effectively debug you’ll also need the source code that was used to build the EXE, even for just a few files that you care about. You’ll need to locate those files and open them in Visual Studio. If the source code isn’t the exact same as the source code that was built the EXE Visual Studio will warn you when you try to insert a breakpoint and the breakpoint won’t bind. That behavior can be overridden from the Breakpoint Settings peek window. In the settings peek window click on the Must match source link text and then check the box to allow mismatched source, as illustrated below. Of course, with mismatched source you never really know what’s going to happen, so use at your peril.
Disclaimer: I'm not really sure how this method is effective without source files, but I think it's the closest to your answer without changing the actual program.
As another option, you can try invoking your executable file by creating a custom program that invokes the program and redirects its stdout and stderr, like this, for example, or using pipes, check there. The custom program would eventually create a process using as executable your original .exe program and do something with stdout/stderr, for example showing them in your custom program console or saving the output to a file, thus allowing you to read your original program output without the window closing issue (Of course, the original window will still close itself, but I don't think it would matter for you too much).
Or if you want a quick'n'dirty way, you could try to capture the program output by making an invoker Java program. Replace commands array with your program executable name with arguments:
Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-get t"};
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}

Visual Studio 2010 - Memory Window - Edit Value

I tried looking on MSDN, Google and Stack Overflow and I couldn't find an answer to what I'm looking for.
Is there a way to edit, through the Memory Window, the code at a given address? I use the Disassembly Window to get the address of the instruction I would like to overwrite, find it in the Memory Window but "Edit Value" is grayed out. Any reason why? Is it because my code gets cached and VS prevents me to edit it? Is there a way to change that through project settings?
Thank you
The application is consisted of data parts and executable parts of code. Windows forbids the changes to executable parts by default, but this can be changed from the code with VirtualProtect function (also pay attention to remarks and FlushInstructionCache).
Maybe your ultimate goal is not to change some code from debugger, but something else that can be achieved differently. What do you really want?

How to get ONLY w3wp instances when specifying performance counters for Perfmon/LogMan on Windows?

Hopefully this question has a simple answer i'm overlooking! I have an IIS webserver with multiple sites on it. In Perfmon, they show up as w3wp#1, w3wp#2, etc... I'm writing a Logman script that will collect performance counter data using the counters/instances that I specify and I want to ONLY collect any w3wp worker processes.
I've tried a couple ways, but no luck:
\.NET CLR Memory(*w3wp*)\
\.NET CLR Memory(w3wp#*)\
\.NET CLR Memory(w3wp*)\
I've looked at the documentation here, and it seems like it claims to support wildcards, but not partial matches. I'm not sure what to make of that. Is there any way accomplish what I want? Hope I explained this well enough. Let me know if more details are needed.
Thanks!
There is a way to display the instance by appending Process Id to it. Since ProcessId do not change it helps determining the correct instance. This post describes the method - Perfmon: Identifying processes by PID instead of instance.
Relevant part from the link:
Making below registry change will display processes in the format of **ProcessName_PID** instead of **ProcessName#1**.
Click Start, click Run, type regedit, and then click OK.
Locate and then click the following registry subkey:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance
On the Edit menu, click New, and then click DWORD Value.
Right-click New Value #1, click Rename, and then type ProcessNameFormat to name the new value.
Right-click ProcessNameFormat, and then click Modify.
In the Data value box, type one of the following values, and then click OK:
1: Disables PID data. This value is the default value.
2: Enables PID data.
Exit Registry Editor.
Warning: Serious problems might occur if you modify the registry incorrectly by using Registry Editor or by using another method. These problems might require that you reinstall the operating system. Microsoft cannot guarantee that these problems can be solved. Modify the registry at your own risk.
Important: If you enable this feature, you may be unable to monitor process-specific information by using third-party utilities or custom-made programs, and this functionality may change at any time in the future without notice.
Hope it helps someone.
I came up with a custom batch script that find the application pool ID, PID, and associates it with the IIS worker process in question. From there, I can manually FIND and REPLACE a generic placeholder in my perfmon configuration file to start collecting for the specific site(s). I can supply some details if there is interest.

Follow program execution through .DLL in hex representation

Is there a way to follow a program's execution through DLL code in hex?
For example, I want to see what sections have just been read when I press a button. It has to work for x64 DLL's.
Thanks!
Yes you load the process into debugger and single step it.
Load the project in visual studio.
Press 'Play' or F5 to start the program in the debugger.
You will need to eventually halt execution sometime so you can start stepping through code or assembly code. You can do this by inserting a breakpoint, or breaking the execution by hitting the break command in the visual studio IDE.
Once halted, you can right click in the code view window, and select "Show Disassembly". Then it will show you the machine instructions.
Also in the watch window in the visual studio debugger, the right click pop up menu has an option to display all variables as hexidecimal. I'm beginning to prefer hex myself lately, because I can see invalid memory patterns easier.
You can use the tool at http://ircdb.org to log function calls arbitrary DLLs.
It's name is SocketSpy, because initially it was created for tracing winsock.dll only, but it does allow you to trace other dlls.
From http://fixunix.com/programmer/95098-tracing-library-dll-calls-win32.html
Use Option->Default Break Point List
Menu to add or remove soft breakpoints
from attached DLLs. Put soft
breakpoints only at function you need
to maximize execution time.
Soft breakpoint means that socketspy
does not stop at this breakpoint, only
log breakpoint information. Hard
breakpoint means that socketspy DOES
STOP at this breakpoint, and
Breakpoint dialog is opened. Specify
what calls should be captured ALL,
FROM EXE FILE or from DLLs (Combobox).
Specify log file File->Open Log File
menu if you want to save function
DLLs' calls into the text file, enable
logging (check box).
Then select a new or already action
process (Select Process button). The
tool can be used in NT/2000/XP only
Alternatively, there is StraceNT, which can trace arbitrary Dlls. It is available for free from http://www.intellectualheaven.com/default.asp?BH=projects&H=strace.htm
I've not used it, but I once stumble upon an Intel tool, which samples the context of the Instruction Pointer, and is able to use symbol files to convert IP to an actual function name... VTune maybe?
I guess there might be other such tools
UPDATE: aka. "statistical profilers"...
Debugging using IDE does not show you the assembly language equivalent of the execution of an IL instruction. You need to write your own hooks to a proper disassembler.

Visual Studio 2008 - show heap

Is it possible to view the heap and stack during debugging?
AFAIK, the main windows you'd want to use are the Locals (Ctrl + Alt + V, L) and Autos (Ctrl + Alt + V, L) windows which MSDN has as:
The Locals window displays variables local to the current context or scope. Usually, this means the procedure or function you are currently executing. The debugger populates this window automatically. In Visual C#, when the Exception Assistant is disabled, the Locals window also displays a pseudovariable $exception whenever there is an active exception. You can expand the pseudovariable to see details of the exception.
The Autos window displays variables used in the current line of code and the preceding line of code. For native C++, the Autos window displays function return values as well. Like the Locals window, the Autos window is populated automatically by the debugger.
...and for the Stack there's the Call Stack window (Debug -> Windows -> Call Stack) or Ctl + Alt + C.
However, I get the feeling this isn't what you're after.
If you are looking for an "in-memory" view you might be able to make use of Visual Studio's Memory windows which can be accessed from the Debug -> Windows -> Memory -> Memory x menus (where x is 1-4) or Ctrl + Alt + M, 1-4.
As a few people have now mentioned, there are a couple of other external tools which are quite useful for memory debugging (I use mainly SysInternals tools and the Debugging Tools for Windows).
You need the "Call Stack Window"...
http://msdn.microsoft.com/en-us/library/a3694ts5.aspx
By using the Call Stack window, you can view the function or procedure calls that are currently on the stack.
And for the Heap, the "Memory Window"...
http://msdn.microsoft.com/en-us/library/s3aw423e(VS.80).aspx
The Memory window provides a view into the memory space used by your application.
"Restoring Hidden Debugger Commands" may also be useful...
http://msdn.microsoft.com/en-us/library/9k643651(VS.80).aspx
As you get into debugging memory, other debuggers will be more useful. As someone suggested, WinDbg is excellent for memory debugging. I use IDA Pro Disassembler a lot myself.
You can view the call stack while debugging, but I assume that's not what you're looking for. You might want to try Windbg and SOS, which are GREAT for debugging memory issues. A bit steep on the learning curve, but the payback is HUGE.
Microsoft Debugging Tools for Windows
If you actually want to look at the raw memory for some reason you can open the "Memory" debug window from "Debug->Windows->Memory" and write the address you want to look at in the edit box. You can also write in the edit box any expression which evaluates to an address and it'll show you that address, for instance &variable
This is not very useful for actually looking at variables because you'll have a tough time parsing the raw bytes into meaningful values but it can be useful for debugging situations where you suspect there are buffer overruns or memory that is overwritten unexpectedly. It is particularly useful when used in conjunction with data-breakpoints.
I know this is an old question, but I figured I'd update it anyway...
Visual Studio 2015 comes with the Memory Usage Monitor built right in to the Diagnostic Tools panel. If you take snapshots before, during, and after what you want to inspect, you can retroactively peek at the heap view of those snapshots.
Hope this helps someone.

Resources