I'm trying to figure out how to use Event Tracing for Windows... but I'm failing.
Why does this code give me the error code ERROR_WMI_INSTANCE_NOT_FOUND?
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <Wmistr.h>
#include <Evntrace.h>
#include <evntcons.h>
ULONG NTAPI EtpEtwBufferCallback(IN PEVENT_TRACE_LOGFILE Buffer) { return TRUE; }
VOID NTAPI EtpEtwEventCallback(IN PEVENT_TRACE EventTrace) { }
int _tmain()
{
LPCTSTR loggerName = KERNEL_LOGGER_NAME;
EVENT_TRACE_LOGFILE logFile = {0};
logFile.LoggerName = const_cast<LPTSTR>(loggerName);
logFile.ProcessTraceMode = PROCESS_TRACE_MODE_REAL_TIME;
logFile.BufferCallback = EtpEtwBufferCallback;
logFile.EventCallback = EtpEtwEventCallback;
TRACEHANDLE hTrace = OpenTrace(&logFile);
ULONG result = ProcessTrace(&hTrace, 1, NULL, NULL);
// result is ERROR_WMI_INSTANCE_NOT_FOUND
_tprintf(_T("%u\n"), result);
}
From the ProcessTrace docs, ERROR_WMI_INSTANCE_NOT_FOUND means "the session from which you are trying to consume events in real time is not running or does not have the real-time trace mode enabled".
You can start the NT Kernel Logger using tracelog from the Windows Driver Kit, though I don't have the WDK to hand so I haven't tried it.
This article explains how to start the NT Kernel Logger yourself.
Related
I'm trying to develop a simple chat program using Boost. I came accross strange situation. I use netcat to listen at specific port while I run the program that's sending a simple text. Connection is established but the text is messed up. Actually instead of whole line I sometimes get one random characters or two. Im putting the code down below:
#include "lib/client.h"
#include <boost/asio.hpp>
#include <boost/asio/io_service.hpp>
#include <iostream>
#include <thread>
#include <string>
int main(int argc, char* argv[]){
if(argc != 3){
std::cout << "Wrong use. After specifying executable, add host and port\n";
return 0;
}
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver(io_service);
auto endpoint = resolver.resolve({argv[1],argv[2]});
Client c(io_service, endpoint);
std::thread t([&io_service](){ io_service.run();});
std::string text = "Welcome host!";
c.add_msg_to_deque(text);
t.join();
c.close();
return 0;
}
And here are client methods:
#include "../lib/client.h"
#include <boost/asio.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/array.hpp>
#include <deque>
#include <iostream>
#include <string>
void Client::connect(boost::asio::ip::tcp::resolver::iterator endpoint){
boost::asio::async_connect(socket, endpoint,
[this](boost::system::error_code ec, boost::asio::ip::tcp::resolver::iterator)
{
if (!ec)
{
}
});
}
void Client::close()
{
ios.post([this]() { socket.close(); });
}
void Client::add_msg_to_deque(const std::string& msg){
ios.post([this,msg](){
write_msg_deque.push_back(msg);
send_msg();
});
}
void Client::send_msg(){
boost::array<char,128> buf;
std::string temp_string = write_msg_deque.front();
std::copy(temp_string.begin(),temp_string.end(),buf.begin());
boost::asio::async_write(socket, boost::asio::buffer(buf,temp_string.size()),[this](boost::system::error_code ec, std::size_t){
if(!ec){
write_msg_deque.pop_front();
if(!write_msg_deque.empty())
send_msg();
}
else{
socket.close();
}
});
}
You are using async_write with local data it is bad idea. async_write returns immediately. After calling async_write your method send_msg terminates, so local data (buf array) is destroyed before your message is sent. You can use a synchronous version of IO functions to send data or keep buf as member of your class to provide data exists until data is sent successfully.
In my Qt5 C++ client, I'm wanting to detect when a user running Windows or OSX has locked the screen, then simultaneously lock my client application.
I have yet to come across a Qt5 class that provides this function, so I'm wondering if I'll need to write an OS-specific library. Does anyone have any experience doing something like this?
Thanks!
On windows you can use below code:
mywidget.cpp
#include "mywidget.h"
#include <Windows.h>
#include <WtsApi32.h>
#include <QDebug>
MyWidget::MyWidget(QWidget *parent) : QWidget(parent)
{
WTSRegisterSessionNotification((HWND)this->winId(), NOTIFY_FOR_THIS_SESSION);
}
MyWidget::~MyWidget()
{
WTSUnRegisterSessionNotification((HWND)this->winId());
}
bool MyWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
if (eventType != "windows_generic_MSG") return false;
MSG *msg = static_cast<MSG*>(message);
switch (msg->message) {
case WM_WTSSESSION_CHANGE:
qDebug() << "session change: " << msg->wParam;
}
return false;
}
project.pro
...
LIBS += -lwtsapi32
...
reference1
reference2
Is possible to get the name of a console in Windows? Just like is done by the C function ttyname in Unix systems
You can use the WinAPI GetConsoleTitle function to retrieve it.
You might find links to all of the console functions useful.
You didn't specify a language, so here's the one in C++ from MSDN
#include <windows.h>
#include <tchar.h>
#include <conio.h>
#include <strsafe.h>
int main( void )
{
TCHAR szOldTitle[MAX_PATH];
TCHAR szNewTitle[MAX_PATH];
// Save current console title.
if( GetConsoleTitle(szOldTitle, MAX_PATH) )
{
// Build new console title string.
StringCchPrintf(szNewTitle, MAX_PATH, TEXT("TEST: %s"), szOldTitle);
// Set console title to new title
if( !SetConsoleTitle(szNewTitle) )
{
_tprintf(TEXT("SetConsoleTitle failed (%d)\n"), GetLastError());
return 1;
}
else
{
_tprintf(TEXT("SetConsoleTitle succeeded.\n"));
}
}
return 0;
}
as stated on the official documentation (closehandle API description).
If the application is running under a debugger, the function will throw an exception if it receives either a handle value that is not valid or a pseudo-handle value.
For this reason the following code can be used to detect if a program is being debugged (since handle 0x1 is always invalid).
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <string>
int _tmain(int argc, _TCHAR* argv[]){
bool flag = false;
__try {
CloseHandle((HANDLE)0x1);
}
__except (EXCEPTION_EXECUTE_HANDLER) {
flag = true;
}
if (flag == false){
printf("Not debugged\n");
}else{
printf("Debugged\n");
}
}
I compiled this code using Visual Studio 2008, creating a 32bit binary.
It works correctly on Windows XP and Windows 7 32bit, but it does not work on Windows 7 64bit, because it always returns "Not debugged".
Do you have any idea why this happens?
Thank you.
I'm currently working on an application that needs to add a menu
to each application's system menu. I can accomplish that for the existing
windows with the EnumWindows function.
For the new windows (applications starting up after mine)
I'm trying to do this with windows hooks. More specifically with CBTProc.
This is where I'm stuck.
I've stripped about everything possible in the app,
but I've got the impression the procedure in my dll just doesn't
get called at all.
Here's the code for the dll:
#include <string>
using std::string;
#include <fstream>
using std::ofstream;
#include <windows.h>
// ---------------------------------------------------
extern "C"
{
void log(const string & msg)
{
ofstream out("out.log", std::ios_base::app);
out << msg;
out.flush();
out.close();
}
// ---------------------------------------------------
LRESULT CALLBACK CBTProc(int nCode, WPARAM wParam, LPARAM lParam)
{
log("CBTProc");
return CallNextHookEx(0, nCode, wParam, lParam);
}
// ---------------------------------------------------
}
I compile this with g++ 3.4.5 on a windows xp sp3 32bit machine:
g++ -shared -otest.dll test_dll.cpp
And here's the code for the application
#include <iostream>
using std::cout;
using std::cin;
using std::cerr;
using std::endl;
#include <string>
using std::string;
#include <windows.h>
typedef void (*func)();
void run()
{
cout << "press enter to exit" << endl;
cin.get();
}
void * loadProc(HMODULE mod, const char * procname)
{
void * retval = (void *)GetProcAddress(mod, procname);
if (retval == NULL)
cerr << "GetProcAddress(" << procname << ") failed" << endl;
return retval;
}
int main(int argc, char ** argv)
{
HMODULE dll = LoadLibrary("test.dll");
if (dll == NULL)
{
cerr << "LoadLibrary failed" << endl;
return 1;
}
HOOKPROC proc = (HOOKPROC)loadProc(dll, "CBTProc#12");
if (!proc)
return 1;
HHOOK callwnd = SetWindowsHookEx(WH_CBT, proc, dll, 0);
if (callwnd == NULL)
{
cerr << "SetWindowsHookEx failed for CBTProc" << endl;
return 1;
}
run();
UnhookWindowsHookEx(callwnd);
return 0;
}
I compile this with the same setup:
g++ -otest.exe test.cpp
When I run, I get no errors, but when I start up new applications I get nothing
in my logfile.
Any ideas?
gr,
ldx
Edit: spelling errors
I'd suggest you to check the following:
ensure that your DLL has an export
(can be checked with dumpbin tool). I
don't know about g++, but in MSVC it
is necessary to either use
__declspec(dllexport) or explicitly state exports in DEF file.
ensure that your host application
uses the correct name of the
exported function (the same as
"dumpbin /EXPORTS test.dll"
displays)
keep in mind that you are are using relative file name out.log - when DLL gets loaded to other processes it would write relatively to the host process' current directory. For testing purposes it would be better to use OutputDebugString API and inspect results with DbgView tool.
Chances are that your solution works already.
PS: it's not generally a good idea to use STL in an injected DLL. Make sure you are aware of the risks.