Get the Current QueryPerfromanceCounter Value in Debugger - windows

Is there a way to get the current value of QueryPerformanceCounter while in the debugger? We use QPC in our code for all time values, but without the "current" time we have no way to calculate the time delta for these values.

I am Not sure what you are looking for ?
if you want to Call QueryPerformanceCounter from an extension you can use the code below compile an extension and bang it out
#include <engextcpp.cpp>
class EXT_CLASS : public ExtExtension
{
public:
EXT_COMMAND_METHOD(qpc);
};
EXT_DECLARE_GLOBALS();
EXT_COMMAND(qpc,"","")
{
LARGE_INTEGER perfcount = {0};
BOOL res = QueryPerformanceCounter(&perfcount);
if(res) {
Out("perfcounter is %I64X\n",perfcount.QuadPart);
}
}
compiled and linked with as x64 from dev cmd prompt
cl /LD /nologo /W4 /Ox /Zi /EHsc /I"C:\Program Files (x86)\Windows Kits\10\Debuggers\inc" %1.cpp /link /EXPORT:DebugExtensionInitialize /Export:%1 /Export:help /RELEASE
usage
.load .\qpc.dll
.chain
Extension DLL chain:
.\qpc.dll: API 1.0.0, built Wed Feb 2 02:56:14 2022
[path: F:\src\wdbgexts\qpc\qpc.dll]
0:000> !qpc
perfcounter is 6A0832C7711
0:000> !qpc
perfcounter is 6A0841BE77B
0:000> !qpc
perfcounter is 6A084A392A8
0:000>
if opening a shell is acceptable then you can also use powershell stopwatch
0:000> !qpc;.shell -ci "$$" "cmd /k powershell -Command 'perfcounter is {0:X}' -f [system.diagnostics.stopwatch]::GetTimestamp()"
perfcounter is 3E79CEF8BE
perfcounter is 3E79F0D3F7
C:\WINDOWS\system32>.shell: Process exited
0:000>

Related

How can I get the BSOD bugcheck code text description by code/windows API

I can get the bugcheck code and the parameters for one BSOD.
And then I can get the text descriptions from Bug Check Code Reference.
But how can I use some windows API or c++ code to get such text description from the bugcheck code and parameters.
For example, for the bugcheck code 0x9F, how can I get the text as
DRIVER_POWER_STATE_FAILURE (9f)
A driver has failed to complete a power IRP within a specific time.
with some windows API or reading from some DLL.
Or to say, how to implement similar function as WinDbg :
1: kd> !analyze -show 0x9F 0x3
DRIVER_POWER_STATE_FAILURE (9f)
A driver has failed to complete a power IRP within a specific time.
Arguments:
Arg1: 0000000000000003, A device object has been blocking an Irp for too long a time
Arg2: 0000000000000000, Physical Device Object of the stack
Arg3: 0000000000000000, nt!TRIAGE_9F_POWER on Win7 and higher, otherwise the Functional Device Object of the stack
Arg4: 0000000000000000, The blocked IRP
I saw there's API like KeGetBugMessageText(), but it's preserved by Windows itself.
Could someone help on this and give some clue or suggestion on that?
Update:
The main part of code used to execute command with 'blabb' suggestion:
#pragma comment ( lib ,"dbgeng.lib")
#include <iostream>
#include <dbgeng.h>
#include "StdioOutputCallbacks.h"
//#include <wdbgexts.h>
//WINDBG_EXTENSION_APIS64 ExtensionApis;
StdioOutputCallbacks g_OutputCb;
int main()
{
IDebugClient* DebugClient = NULL;
HRESULT Hr = S_OK;
if ((Hr = DebugCreate(__uuidof(IDebugClient),
(void**)&DebugClient)) != S_OK) {
return Hr;
}
PDEBUG_CONTROL DebugControl;
if ((Hr = DebugClient->QueryInterface(__uuidof(IDebugControl),
(void**)&DebugControl)) == S_OK) {
DebugClient->SetOutputCallbacks(&g_OutputCb);
Hr = DebugClient->OpenDumpFile("C:\\Dev\\Deem\\bug\\dcp938\\MEMORY.DMP");
if (Hr != S_OK) {
return Hr;
}
DebugControl->Execute(DEBUG_OUTCTL_THIS_CLIENT, "!analyze -show 9f 3", DEBUG_EXECUTE_DEFAULT);
DebugControl->Release();
}
// done
DebugClient->Release();
}
and in outputcallback, kept as the msdn sample:
STDMETHODIMP
StdioOutputCallbacks::Output(
THIS_
_In_ ULONG Mask,
_In_ PCSTR Text
)
{
UNREFERENCED_PARAMETER(Mask);
fputs(Text, stdout);
return S_OK;
}
But the result of the execute "!analyze -show 9f 3"(the content of Text in fputs()) is "No export analyze found".
I also try the command ".opendump C:\...MEMORY.DMP;!analyze -show 9f 3", the opendump command executed correctly, the dmp is loaded and got the text output including "For analysis of this file, run !analyze -v", but both "!analyze -v" and "!analyze -show ..." got "No export analyze found".
The command without '!' will lead to command resolve error.
I am not sure what you are looking for.
All these are #defined in bugcodes.h in windows sdk/ddk
C:\Program Files (x86)\Windows Kits\10\Include>pss DRIVER_POWER_STATE_FAILURE
.\10.0.17763.0\shared\bugcodes.h
1505:// MessageId: DRIVER_POWER_STATE_FAILURE
1509:// DRIVER_POWER_STATE_FAILURE
1511:#define DRIVER_POWER_STATE_FAILURE ((ULONG)0x0000009FL)
Or grepping the other way round
C:\Program Files (x86)\Windows Kits\10\Include>grep -ir #define.*0x0000009fl --include *.h *
10.0.17763.0/shared/bugcodes.h:#define DRIVER_POWER_STATE_FAILURE ((ULONG)0x0000009FL)
Or use DbgEng to write either a WinDbg extension or a standalone executable.
Open the dump->WaitForEvent->Executecommands !bugdump .bug****
Or you can also explore IDebugDataSpaces::****tag**** methods like read, start, next, end.
Edit
Scott Noone is probably indicating the ext.dll the inbuilt windbg extension
As i Already Stated you may need to write a windbg Analyze Extension either as an extension or as a standalone
most of these are either undocumented or poorly worded documentation
here is the dump of bugcheck codes compiled inside ext.dll which is what scott noone is probably indicating in his answer.
0:000> dps ext!g_BugCheckApiRefs l10
00007ff9`4a45ccc0 00000000`00000001
00007ff9`4a45ccc8 00007ff9`49efead0 ext!BugCheckAPC_INDEX_MISMATCH
00007ff9`4a45ccd0 00000000`00000002
00007ff9`4a45ccd8 00007ff9`49efeb60 ext!BugCheckDEVICE_QUEUE_NOT_BUSY
00007ff9`4a45cce0 00000000`00000003
00007ff9`4a45cce8 00007ff9`49efebc0 ext!BugCheckINVALID_AFFINITY_SET
00007ff9`4a45ccf0 00000000`00000004
00007ff9`4a45ccf8 00007ff9`49efec20 ext!BugCheckINVALID_DATA_ACCESS_TRAP
00007ff9`4a45cd00 00000000`00000005
00007ff9`4a45cd08 00007ff9`49efec80 ext!BugCheckINVALID_PROCESS_ATTACH_ATTEMPT
00007ff9`4a45cd10 00000000`00000006
00007ff9`4a45cd18 00007ff9`49efece0 ext!BugCheckINVALID_PROCESS_DETACH_ATTEMPT
00007ff9`4a45cd20 00000000`00000007
00007ff9`4a45cd28 00007ff9`49efed40 ext!BugCheckINVALID_SOFTWARE_INTERRUPT
00007ff9`4a45cd30 00000000`00000008
00007ff9`4a45cd38 00007ff9`49efeda0 ext!BugCheckIRQL_NOT_DISPATCH_LEVEL
0:000>
or your power failure
0:000> .shell -ci "dps ext!g_BugCheckApiRefs l150" grep -A 1 -i 09f
00007ff9`4a45d600 00000000`0000009f
00007ff9`4a45d608 00007ff9`49f04450 ext!BugCheckDRIVER_POWER_STATE_FAILURE
.shell: Process exited
0:000>
here is a complete call stackLeadign to yourQuery about !analyze -show 9f 3
Child-SP RetAddr Call Site
000000d3`6d67b768 00007ff9`49fa302a ext!GetBugCheckDescription
000000d3`6d67b770 00007ff9`49f822c2 ext!DebugFailureAnalysis::ParseInputArgs+0xc66
000000d3`6d67bb00 00007ff9`49f549c5 ext!AnalyzeBugCheck+0x10a
000000d3`6d67bbd0 00007ff9`4ae0187d ext!analyze+0x4e5
000000d3`6d67bd90 00007ff9`4ae01a31 dbgeng!ExtensionInfo::CallA+0x27d
000000d3`6d67be50 00007ff9`4ae01d0e dbgeng!ExtensionInfo::Call+0x121
000000d3`6d67c050 00007ff9`4adff9d8 dbgeng!ExtensionInfo::CallAny+0x17a
000000d3`6d67c570 00007ff9`4ae43662 dbgeng!ParseBangCmd+0xe0c
000000d3`6d67cd30 00007ff9`4ae44635 dbgeng!ProcessCommands+0xcd6
000000d3`6d67ce20 00007ff9`4ad6baf7 dbgeng!ProcessCommandsAndCatch+0x79
000000d3`6d67ce90 00007ff9`4ad6be04 dbgeng!Execute+0x2bb
000000d3`6d67d380 00007ff6`4c7b62dc dbgeng!DebugClient::ExecuteWide+0x94
000000d3`6d67d3e0 00007ff6`4c7b879a kd!MainLoop+0x514
000000d3`6d67f460 00007ff6`4c7bb55d kd!wmain+0x3e6
000000d3`6d67f700 00007ff9`857c7c24 kd!__wmainCRTStartup+0x14d
000000d3`6d67f740 00007ff9`85d8d721 KERNEL32!BaseThreadInitThunk+0x14
000000d3`6d67f770 00000000`00000000 ntdll!RtlUserThreadStart+0x21
0:000>
The Function is a simple compare return routine like
while array[i] != 0x9f skip
return String array[i]+0x8
and the detailed description is done by
void PrintBugDescription(_BUGCHECK_ANALYSIS *param_1,DebugFailureAnalysis *param_2)
EDIT
Since My last comment I was wondering
how I would go about this scenario without writing code
without having a kernel memory dump to operate on
possibly scalable to unknown remote machines
I Came up with a small python wrapper using sysinternals livekd.exe
script
:\>cat liv.py
import subprocess
import regex
foo = subprocess.run(
[r"f:\sysint\livekd", "-b" ,"-c \"!analyze -show 9f 03;q\""],
stdout=subprocess.PIPE,
universal_newlines=True
)
resta = regex.search("Reading" , foo.stdout).start()
reend = regex.search("quit:" , foo.stdout).end()
print(foo.stdout[resta:reend])
result of script execution
:\>python liv.py
Reading initial command '!analyze -show 9f 03;q'
*** ERROR: Module load completed but symbols could not be loaded for LiveKdD.SYS
DRIVER_POWER_STATE_FAILURE (9f)
A driver has failed to complete a power IRP within a specific time.
Arguments:
Arg1: 0000000000000003, A device object has been blocking an Irp for too long a time
Arg2: 0000000000000000, Physical Device Object of the stack
Arg3: 0000000000000000, nt!TRIAGE_9F_POWER on Win7 and higher, otherwise the Functional Device Object of the stack
Arg4: 0000000000000000, The blocked IRP
*******************************************************************************
* *
* Bugcheck Analysis *
* *
*******************************************************************************
Use !analyze -v to get detailed debugging information.
BugCheck 0, {0, 0, 0, 0}
Probably caused by : LiveKdD.SYS ( LiveKdD+2f4f )
Followup: MachineOwner
---------
quit:
Adding another answer as the prior answer is too cluttered and commented.
contents of directory pre compilation and linking
F:\bugdesc>ls -lg
-rw-r--r-- 1 197121 156689581 Aug 17 23:49 MEMORY.DMP
-rw-r--r-- 1 197121 600 Aug 26 01:22 bugdesc.cpp
-rw-r--r-- 1 197121 109 Aug 19 00:04 complink.bat
-rw-r--r-- 1 197121 1019 Aug 26 01:21 stdioimpl.h
contents of bat file
F:\bugdesc>cat complink.bat
cl /nologo /W4 /Od /Zi /EHsc /I"C:\Program Files (x86)\Windows Kits\10\Debuggers\inc" %1.cpp /link /RELEASE
file containing implementation of StdioOutputCallbacks
F:\bugdesc>cat stdioimpl.h
#include <windows.h>
#include <stdio.h>
#include <dbgeng.h>
#pragma comment(lib, "dbgeng.lib")
class StdioOutputCallbacks : public IDebugOutputCallbacks {
public:
STDMETHOD(QueryInterface)(THIS_ _In_ REFIID ifid, _Out_ PVOID *iface);
STDMETHOD_(ULONG, AddRef)(THIS);
STDMETHOD_(ULONG, Release)(THIS);
STDMETHOD(Output)(THIS_ IN ULONG Mask, IN PCSTR Text);
};
STDMETHODIMP
StdioOutputCallbacks::QueryInterface(THIS_ _In_ REFIID ifid, _Out_ PVOID *iface){
*iface = NULL;
if (IsEqualIID(ifid, __uuidof(IDebugOutputCallbacks))){
*iface = (IDebugOutputCallbacks *)this;
AddRef();
return S_OK;
} else {
return E_NOINTERFACE;
}
}
STDMETHODIMP_(ULONG)
StdioOutputCallbacks::AddRef(THIS) { return 1; }
STDMETHODIMP_(ULONG)
StdioOutputCallbacks::Release(THIS) { return 0; }
STDMETHODIMP StdioOutputCallbacks::Output(THIS_ IN ULONG, IN PCSTR Text){
fputs(Text, stdout);
return S_OK;
}
contents of main source file
F:\bugdesc>cat bugdesc.cpp
#include "stdioimpl.h"
//implement proper error handling and release of Interfaces
void __cdecl main(void)
{
IDebugClient *g_Client;
IDebugControl *g_Control;
StdioOutputCallbacks g_OutputCb;
DebugCreate(__uuidof(IDebugClient), (void **)&g_Client);
g_Client->QueryInterface(__uuidof(IDebugControl), (void **)&g_Control);
g_Client->SetOutputCallbacks(&g_OutputCb);
g_Client->SetOutputCallbacks(&g_OutputCb);
g_Client->OpenDumpFile("F:\\bugdesc\\memory.dmp");
g_Control->WaitForEvent(0, INFINITE);
g_Control->Execute(0, "!analyze -show 9f 3", 0);
}
compiled and linked with vs-community 2017 as x64
F:\bugdesc>complink.bat bugdesc
F:\bugdesc>cl /nologo /W4 /Od /Zi /EHsc /I"C:\Program Files (x86)\Windows Kits\10\Debuggers\inc" bugdesc.cpp /link /RELEASE
bugdesc.cpp
contents of directory post compilation and linking
F:\bugdesc>ls -lg
total 159485
-rw-r--r-- 1 197121 156689581 Aug 17 23:49 MEMORY.DMP
-rw-r--r-- 1 197121 600 Aug 26 01:22 bugdesc.cpp
-rwxr-xr-x 1 197121 406016 Aug 26 01:25 bugdesc.exe
-rw-r--r-- 1 197121 30072 Aug 26 01:25 bugdesc.obj
-rw-r--r-- 1 197121 5992448 Aug 26 01:25 bugdesc.pdb
-rw-r--r-- 1 197121 109 Aug 19 00:04 complink.bat
-rw-r--r-- 1 197121 1019 Aug 26 01:21 stdioimpl.h
-rw-r--r-- 1 197121 176128 Aug 26 01:25 vc140.pdb
executing without proper dlls and failure
F:\bugdesc>bugdesc.exe
No .natvis files found at C:\WINDOWS\SYSTEM32\Visualizers.
xxxxxxxxxxxxxxxxxxxxxxxxxxx snip
Microsoft (R) Windows Debugger Version 10.0.18362.1 AMD64
xxxxxxxxxxxxxxxxxxxxxxxxxxx snip
Loading Dump File [F:\bugdesc\memory.dmp]
xxxxxxxxxxxxxxxxxxxxxxxxxxx snip
*** Type referenced: nt!_MMPTE_TRANSITION ***
xxxxxxxxxxxxxxxxxxxxxxxxxxx snip
For analysis of this file, run !analyze -v
No export analyze found<<<<<<<<<<<<<<<<<<
copying relevent dlls from windbg installation folder
F:\bugdesc>copy ..\windbg_dlls\*.* .
..\windbg_dlls\dbgeng.dll
..\windbg_dlls\dbghelp.dll
..\windbg_dlls\ext.dll
..\windbg_dlls\symsrv.dll
4 file(s) copied.
execution and success
F:\bugdesc>bugdesc.exe
Microsoft (R) Windows Debugger Version 10.0.17763.132 AMD64
xxxxxxxxxxxxxxxxxxxxxxxxxxx snip
Loading Dump File [F:\bugdesc\memory.dmp]
xxxxxxxxxxxxxxxxxxxxxxxxxxx snip
*******************************************************************************
* *
* Bugcheck Analysis *
* *
*******************************************************************************
Use !analyze -v to get detailed debugging information.
BugCheck E2, {0, 0, 0, 0}
Probably caused by : Unknown_Image
*** Followup info cannot be found !!! Please contact "BADEV"
---------
DRIVER_POWER_STATE_FAILURE (9f)<<<<<<<<<<<<<<<<<<<<<<<
A driver has failed to complete a power IRP within a specific time.
Arguments:
Arg1: 0000000000000003, A device object has been blocking an Irp for too long a time
Arg2: 0000000000000000, Physical Device Object of the stack
Arg3: 0000000000000000, nt!TRIAGE_9F_POWER on Win7 and higher, otherwise the Functional Device Object of the stack
Arg4: 0000000000000000, The blocked IRP
xxxxxxxxxxxxxxxxxxxxxxxxxxx snip

Inspect Parameter passed to Functions with windbg

I working through some example in Windows System Programming 4th. Using windbg.exe I'm trying to inspect the parameters passed to a function (GetCurrentDirectoryA). Below is the source.
int _tmain (int argc, LPTSTR argv [])
{
/* Buffer to receive current directory allows for the CR,
LF at the end of the longest possible path. */
TCHAR pwdBuffer [DIRNAME_LEN];
DWORD lenCurDir;
lenCurDir = GetCurrentDirectory (DIRNAME_LEN, pwdBuffer);
if (lenCurDir == 0)
ReportError (_T ("Failure getting pathname."), 1, TRUE);
if (lenCurDir > DIRNAME_LEN)
ReportError (_T ("Pathname is too long."), 2, FALSE);
PrintMsg (GetStdHandle (STD_OUTPUT_HANDLE), pwdBuffer);
return 0;
}
First I dump the local variables using dv -t -v. In this case I'm interested in the pwdBuffer.
0018ff3c int argc = 0n1
0018ff40 char ** argv = 0x00582470
0018fe18 unsigned long lenCurDir = 0x775b994a
0018fe24 char [262] pwdBuffer = char [262] ""
Then I set a breakpoint at Kernel32!GetCurrentDirectoryA. Which yields the following.
00 0018ff34 00428759 00000001 00582470 005824c0 kernel32!GetCurrentDirectoryA
What I don't understand is value of the parameters to the Function. I was expecting to see 0018fe24 as one value representing pwdbuffer.
The next thing I do is gu. Which executes Kernel32!GetCurrentDirectoryA to its end.
Thereafter I dumped the pwdBuffer value that I got initially with the dv -v -t command.
0:000> da 0018fe24
0018fe24 "C:\microsoft_press\WSP4_Examples"
0018fe44 "\Utility_4_dll"
This is what I expect from the buffer. So my question is why didn't I see this 0018fe24 value passed to GetCurrentDirectory?
Try single stepping past the mov ebp, esp instruction at the start of GetCurrentDirectoryA. The numbers you're seeing look like values from your _tmain function, specifically, its frame pointer (EBP), its return address, and its arguments argc and argv (along with the hidden envp parameter). Once EBP is loaded with the correct frame pointer for GetCurrentDirectoryA, windbg may be able to display the function's arguments correctly.
The stack should show the parameters to the function on hitting the break-point not after you single step i just had similar code (without crt window Apis only) and ran it through and windbg works as expected
when analyzing unknown or potentially malware binaries one unthoughtful single step can result in fatal infection. If logic exists don't use lucky charms.
my current directory
:\>echo %cd%
C:\temp\temp\temp\temp
contents of current directory
:\>ls -l
total 12
-rwxrwxrwx 1 Admin 0 197 2015-10-10 16:29 compile.bat
-rw-rw-rw- 1 Admin 0 336 2015-10-10 16:13 getdir.cpp
-rw-rw-rw- 1 Admin 0 145 2015-10-10 16:47 wtf.txt
src code for test
:\>type getdir.cpp
#include <windows.h>
int main (void) {
PCHAR buff=0;int bufflen=0;
bufflen=GetCurrentDirectory(0,NULL);
buff = (PCHAR)VirtualAlloc(NULL,bufflen,MEM_COMMIT,PAGE_READWRITE);
if(buff){
GetCurrentDirectory(bufflen,buff);
MessageBox(NULL,buff,"Current Directory",MB_OK);
VirtualFree(buff,0,MEM_RELEASE);
}
}
compiled with
:\>type compile.bat
#call "C:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86
cl /Zi /EHsc /O2 /nologo /W4 /analyze *.cpp /link /SUBSYSTEM:Windows /RELEASE /E
NTRY:main user32.lib kernel32.lib
pause
:\>compile.bat
Setting environment for using Microsoft Visual Studio 2010 x86 tools.
getdir.cpp
Press any key to continue . . .
executed with
:\>cdb -cf wtf.txt getdir.exe
-cf command line to windbg / cdb takes a file whose content will be executed as if you type them at the prompt
the contents of wtf.txt is
:\>type wtf.txt
bp kernel32!VirtualAlloc
g
gu
? #eax
bc *
bp kernel32!GetCurrentDirectoryA
g
dd #esp l3
r $t0 = poi(#esp+8)
? #$t0
gu
da #$t0;
g
q
on the first system break
set a breakpoint on virtualalloc and run the binary
when the breakpoint is hit goup (we are interested only in the return value from this function ) and inspect eax (return value from function)
clear all breakpoints
set a breakpoint in GetCurrentDirectoryA
execute the binary again with g on hitting the breakpoint inspect the stack
with dd #esp l3
(display three dwords from Stack pointer one return address and two function parameters to the Function GetCurrentDirectoryA()
note the stack will contain the same address we previously inspected at the return of VirtualAlloc using ? #eax
save the address of buffer to a pseudo variable and go up
print the ascii string from the buffer da #$t0
exit the session
the result of this session is as follows note we got 35000 as the allocated memory address of buffer from virtual alloc and that was indeed passed to GetCurrentDirectory and that hold the string Current directory
:\>cdb -cf wtf.txt getdir.exe
0:000> bp kernel32!VirtualAlloc
0:000> g
Breakpoint 0 hit
kernel32!VirtualAlloc:
7c809af1 8bff mov edi,edi
0:000> gu
getdir!main+0x21:
00401021 8bf0 mov esi,eax
0:000> ? #eax
Evaluate expression: 3473408 = 00350000 <--------
0:000> bc *
0:000> bp kernel32!GetCurrentDirectoryA
0:000> g
Breakpoint 0 hit
kernel32!GetCurrentDirectoryA:
7c83502e 8bff mov edi,edi
0:000> dd #esp l3
0013ffac 0040102b 00000017 00350000 <------
0:000> r $t0 = poi(#esp+8)
0:000> ? #$t0
Evaluate expression: 3473408 = 00350000 <----------
0:000> gu
getdir!main+0x2b:
0040102b 6a00 push 0
0:000> da #$t0;
00350000 "C:\temp\temp\temp\temp"
0:000> g
edit all others being same just added a kb command to the script file and executed to show the stacktrace

FFI example from book cannot find -lanneclib under Windows

Error linking following the external c dll with call back example.
I have created anneclib.dll and scattered it ( and the lib) have even tried full path but still get the same error ( but with the full path) .
Error 1 error: linking with gcc failed: exit code: 1 note: "gcc"
"-Wl,--enable-long-section-names" "-fno-use-linker-plugin"
"-Wl,--nxcompat" "-static-libgcc" "-m64" "-L" "C:\Program Files\Rust
stable 1.0\bin\rustlib\x86_64-pc-windows-gnu\lib" "-o"
"obj\Debug\Anne.exe" "obj\Debug\Anne.o" "-Wl,--gc-sections"
"C:\Program Files\Rust stable
1.0\bin\rustlib\x86_64-pc-windows-gnu\lib\libstd-4e7c5e5c.rlib" "C:\Program Files\Rust stable
1.0\bin\rustlib\x86_64-pc-windows-gnu\lib\libcollections-4e7c5e5c.rlib"
"C:\Program Files\Rust stable
1.0\bin\rustlib\x86_64-pc-windows-gnu\lib\libunicode-4e7c5e5c.rlib" "C:\Program Files\Rust stable
1.0\bin\rustlib\x86_64-pc-windows-gnu\lib\librand-4e7c5e5c.rlib" "C:\Program Files\Rust stable
1.0\bin\rustlib\x86_64-pc-windows-gnu\lib\liballoc-4e7c5e5c.rlib" "C:\Program Files\Rust stable
1.0\bin\rustlib\x86_64-pc-windows-gnu\lib\liblibc-4e7c5e5c.rlib" "C:\Program Files\Rust stable
1.0\bin\rustlib\x86_64-pc-windows-gnu\lib\libcore-4e7c5e5c.rlib" "-L" "C:\Program Files\Rust stable
1.0\bin\rustlib\x86_64-pc-windows-gnu\lib" "-L" "C:\src\ann\anne.rust\anne.rust\Anne.rust\bin\x86_64-pc-windows-gnu"
"-L" "C:\src\ann\anne.rust\anne.rust\Anne\bin\x86_64-pc-windows-gnu"
"-Wl,--whole-archive" "-Wl,-Bstatic" "-Wl,--no-whole-archive"
"-Wl,-Bdynamic" "-lanneclib" "-lws2_32" "-luserenv" "-lcompiler-rt"
note: ld: cannot find -lanneclib
Using the Visual Studio Rust project.
Where should I put it ?
extern fn callback(a: i32) {
println!("I'm called from C with value {0}", a);
}
#[link(name = "anneclib")]
extern {
fn register_callback(cb: extern fn(i32)) -> i32;
fn trigger_callback();
}
fn main() {
unsafe {
register_callback(callback);
trigger_callback(); // Triggers the callback
}
}
In the error message you can see that the folder [your source folder]\bin\x86_64-pc-windows-gnu is added to the library path. You have to put your library into this folder. You may also have to add a 'lib' prefix to the library name.
Here is a small example that works for me:
A C file with a hello-function:
#include <stdio.h>
void hello() {
printf("Hello from C!\n");
}
Compile the C file to a shared library libhello.c using MinGW:
gcc -shared -o libhello.dll hello.c
The Rust file main.rs:
#[link(name = "hello")]
extern {
fn hello();
}
fn main() {
unsafe { hello(); }
}
Now you have to put (a copy of) the libhello.dll into the sub-folder \bin\x86_64-pc-windows-gnu:
+ bin
+ --- x86_64-pc-windows-gnu
+ --- libhello.dll
+ main.rs
And you should be able to compile it via
rustc main.rs
Note in order to execute the main.exe you also need a copy of the libhello.dll next to the main.exe or in the system path.

How to name a thread in Windows Performance Analyzer?

I was trying to display the names of threads in Windows Performance Analyzer (WPA) (under Windows 8.1). This tool has a column called "thread name".
I followed the famous MSDN article:
http://msdn.microsoft.com/en-us/library/xcb2z8hs(v=vs.110).aspx
However, looks like it doesn't work in WPA. And according to a 3rd-party document, only Microsoft’s Visual Studio and WinDbg debuggers support this exception.
So how can I name a thread so that its name can be displayed in WPA?
Starting in Windows 10, version 1607, you can use the SetThreadDescription() API, which is now supported in xperf/WPA:
https://randomascii.wordpress.com/2015/10/26/thread-naming-in-windows-time-for-something-better/
You can also vote for support for it to be added to other Microsoft tools here:
https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/17608120-properly-support-native-thread-naming-via-the-sett
Dont have wpa installed handy so cant answer your query but thanks for
the question it never occurred to me that this could be used native code too
could come in handy
#include <windows.h>
#include <stdio.h>
const DWORD MS_VC_EXCEPTION=0x406D1388;
//EmptyBlock,Constant in__except() and lpparam not used in ThreadProc
#pragma warning( disable : 6312 6322 4100 )
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO {
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
DWORD WINAPI ThreadProc( LPVOID lpParam ) {
int ch = 0; while(ch != 'y') { ch = getchar(); } return 0;}
void SetThreadName( DWORD dwThreadID, char* threadName) {
THREADNAME_INFO info; info.dwType = 0x1000; info.szName = threadName;
info.dwThreadID = dwThreadID; info.dwFlags = 0;
__try {
RaiseException( MS_VC_EXCEPTION, 0,
sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
}
__except( EXCEPTION_CONTINUE_EXECUTION) { }
}
void main (void) {
HANDLE hThread = NULL;
printf("\n\n\n=======Creating Thread And Naming It================\n\n\n");
if (( hThread = CreateThread(NULL,NULL,ThreadProc,NULL,NULL,NULL)) != NULL) {
SetThreadName(GetCurrentThreadId(), "\n\nMy New Shiny Thread\n\n");
WaitForSingleObject(hThread,INFINITE);
printf("Named Thread Terminated Main is terminating\n");
CloseHandle(hThread);
}
}
compiled linked and windbagged vcpp event seems to handle this exception in windbg
wonder what MAGIC Dword dbce handles
dir /b
compile.bat
threadname.cpp
type compile.bat
#call "C:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86
cl /Zi /nologo /W4 /analyze *.cpp /link /RELEASE
compile.bat
Setting environment for using Microsoft Visual Studio 2010 x86 tools.
threadname.cpp
dir /b *.exe
threadname.exe
cdb -c "sxe -c \"~*;gc;\" vcpp;g;q" threadname.exe
0:000> cdb: Reading initial command 'sxe -c "~*;gc;" vcpp;g;q'
=================Creating Thread And Naming It===================
(f84.db4): Visual C++ exception - code 406d1388 (first chance)
. 0 Id: f84.db4 Suspend: 1 Teb: 7ffdf000 Unfrozen "
My New Shiny Thread
"
Start: threadname!mainCRTStartup (00401642)
Priority: 0 Priority class: 32 Affinity: 1
y
Named Thread Terminated Main is terminating
quit:

D3D11 CreateDeviceAndSwapChain makes Visual Studio unuseable

Hi all I have a pretty odd problem.
When I step through my code from the beginning of the program its fine but when I get to the section in my code to create the device and swap chain Visual Studio starts lagging for input and becomes unuseable. My mouse also gives really delayed response. The only way to stop it is to ctrl+alt+del and close Visual Studio.
Here's the code up to the line in question.
HRESULT hr = S_OK;
RECT rc;
GetClientRect((*pWindowHandle), &rc);
UINT width = rc.right - rc.left;
UINT height = rc.bottom - rc.top;
UINT createDeviceFlags = 0;
#ifdef _DEBUG
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_DRIVER_TYPE driverTypes[] =
{
D3D_DRIVER_TYPE_HARDWARE,
D3D_DRIVER_TYPE_WARP,
D3D_DRIVER_TYPE_REFERENCE,
};
UINT numDriverTypes = ARRAYSIZE(driverTypes);
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_0
};
UINT numFeatureLevels = ARRAYSIZE(featureLevels);
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 1;
sd.BufferDesc.Width = width;
sd.BufferDesc.Height = height;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = (*pWindowHandle);
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; // allow full-screen switching
for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++)
{
m_driverType = driverTypes[driverTypeIndex];
hr = D3D11CreateDeviceAndSwapChain(NULL, m_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels,
D3D11_SDK_VERSION, &sd, &m_pSwapChain, &m_pd3dDevice, &m_featureLevel, &m_pImmediateContext);
if (SUCCEEDED(hr))
break;
}
I've got a feeling it might have to do with visual studio rather than the project since the D3D11 sample projects also do the same. They run fine but as soon as you try to pause or break VS throws a wobbly.
I've already tried repairing my version of VS2013 Update2
Is there something that can help me?
Output from the debug folder
Build started 02/11/2014 16:24:14.
1>Project "C:\Users\luckielordie\Source\Repos\3dtut2\Tutorial02_2010.vcxproj" on node 2 (Build target(s)).
1>ClCompile:
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\CL.exe /c /I..\..\..\DXUT11\Core /I..\..\..\DXUT11\Optional /ZI /nologo /W4 /WX- /Od /Oi /Oy- /D WIN32 /D _DEBUG /D DEBUG /D PROFILE /D _WINDOWS /D D3DXFX_LARGEADDRESS_HANDLE /D _UNICODE /D UNICODE /Gm- /EHsc /RTC1 /MDd /GS /arch:SSE2 /fp:fast /Zc:wchar_t /Zc:forScope /openmp- /Fo"Debug\\" /Fd"Debug\vc120.pdb" /Gd /TP /analyze- /errorReport:prompt D3D11.cpp
D3D11.cpp
Link:
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\link.exe /ERRORREPORT:PROMPT /OUT:"C:\Users\luckielordie\Source\Repos\3dtut2\Debug\D3DApplication.exe" /INCREMENTAL /NOLOGO d3d11.lib d3dcompiler.lib dxguid.lib winmm.lib comctl32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /MANIFEST /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /manifest:embed /manifestinput:"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\Include\Manifest\dpiaware.manifest" /DEBUG /PDB:"C:\Users\luckielordie\Source\Repos\3dtut2\Debug\D3DApplication.pdb" /SUBSYSTEM:WINDOWS /LARGEADDRESSAWARE /TLBID:1 /DYNAMICBASE /NXCOMPAT /IMPLIB:"C:\Users\luckielordie\Source\Repos\3dtut2\Debug\D3DApplication.lib" /MACHINE:X86 /SAFESEH /SAFESEH:NO Debug\Tutorial02.res
Debug\D3D11.obj
Debug\D3D11ResourceBuilder.obj
Debug\Game.obj
Debug\GameObject.obj
Debug\main.obj
Debug\Model.obj
Debug\Shader.obj
Debug\Window.obj
Tutorial02_2010.vcxproj -> C:\Users\luckielordie\Source\Repos\3dtut2\Debug\D3DApplication.exe
1>Done Building Project "C:\Users\luckielordie\Source\Repos\3dtut2\Tutorial02_2010.vcxproj" (Build target(s)).
Build succeeded.
Time Elapsed 00:00:01.42
EDIT:
On that line in the Output I get a line
A thread <threadnumber> has exited with code 0(0x0)
I had exactly the same problem and it was solved by updating video drivers (I have nVidia GeForce 660, and now I use 344.75, I installed it using "clean" option). Previous driver was 335 or something. Also if it doesn't help, try disabling nVidia ShadowPlay (it didn't help me though), I think some problem can lie there, if it installs some keyboard hook inside D3D.

Resources