我一直在使用从过滤器驱动程序接收消息的应用程序。驱动程序运行正常,但我的内存管理有问题,可能是LPTSTR 用户&的域即可。
在调试时,我收到有关堆损坏的消息,他们通常会指向两个 free 或第二个 LookupAccountSid 调用。我在这里做错了什么?
#include "stdafx.h"
#include "myapp-service.h"
#include <Windows.h>
#include <fltUser.h>
#include <string>
#include <sddl.h>
BOOL
getUser(
_In_ WCHAR* sidstr,
_Inout_ LPTSTR* AcctName,
_Inout_ LPTSTR* DomainName
)
{
PSID sid;
DWORD dwAcctName = 1;
DWORD dwDomainName = 1;
SID_NAME_USE eUse = SidTypeUnknown;
bool success;
if (!ConvertStringSidToSidW(sidstr, &sid))
{
printf_s("ConvertStringSidToSid failed with 0x%08x\n", GetLastError);
return false;
}
// Lookup!
LookupAccountSid(
NULL,
sid,
*AcctName,
(LPDWORD)&dwAcctName,
*DomainName,
(LPDWORD)&dwDomainName,
&eUse);
*AcctName = (LPTSTR)GlobalAlloc(GMEM_FIXED, dwAcctName);
*DomainName = (LPTSTR)GlobalAlloc(GMEM_FIXED, dwDomainName);
success = LookupAccountSid(
NULL,
sid,
*AcctName,
(LPDWORD)&dwAcctName,
*DomainName,
(LPDWORD)&dwDomainName,
&eUse);
if (success) {
_tprintf(TEXT("Username %s@%s\n"), *AcctName, *DomainName);
}
else {
printf_s("LookupAccountSid failed with 0x%08x\n", GetLastError);
return false;
}
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
HRESULT status;
HANDLE port;
myapp_USER_MESSAGE msg;
//
// Open a communication channel to the filter
//
printf("myapp-service: Connecting to the filter ...\n");
status = FilterConnectCommunicationPort(myappPortName,
0,
NULL,
0,
NULL,
&port);
if (IS_ERROR(status)) {
printf("ERROR: Connecting to filter port: 0x%08x\n", status);
return 2;
}
//
// Fetch messages & handle them
//
while (TRUE) {
status = FilterGetMessage(port,
&msg.MessageHeader,
sizeof(msg),
NULL
);
if (status == S_OK) {
// Got a message successfully!
// The problem is most likely with these two
LPTSTR user = NULL;
LPTSTR domain = NULL;
if (getUser(msg.Message.Sid, &user, &domain)) {
_tprintf(TEXT("Username %s@%s accessed %ls at %ls\n"), user, domain, &msg.Message.FileName, &msg.Message.TimeStamp);
}
else {
printf("Unable to get user data!");
};
if (user) {
GlobalFree(user);
}
if (domain) {
GlobalFree(domain);
}
}
else {
printf("ERROR: GetMessage: 0x%08x\n", status);
}
printf("\n\n");
}
//
// Close the communication channel to the filter
//
printf("myapp-service: Closing connection ...\n");
CloseHandle(&port);
return 0;
}
答案 0 :(得分:2)
LookupAccountSid的参数cchName
和cchReferenceDomainName
以cch
为前缀(即字符数)。在分配内存时,您必须考虑到这一点,因为GlobalAlloc需要字节数:
*AcctName = (LPTSTR)GlobalAlloc(GMEM_FIXED, dwAcctName * sizeof(TCHAR));
*DomainName = (LPTSTR)GlobalAlloc(GMEM_FIXED, dwDomainName * sizeof(TCHAR));
您还应该在第一次通话之前对尺寸参数进行零初始化:
DWORD dwAcctName = 0x0;
DWORD dwDomainName = 0x0;
文档中概述了这一点:
如果函数因缓冲区太小而失败,或者如果cchName为零,则cchName会收到所需的缓冲区大小,包括终止空字符。
<小时/> 另外:
printf_s
两次来电都会打印GetLastError
的地址,而不是其返回值。您必须添加括号(GetLastError()
)才能调用函数调用。
答案 1 :(得分:1)
*AcctName = (LPTSTR)GlobalAlloc(GMEM_FIXED, dwAcctName*sizeof(TCHAR));
*DomainName = (LPTSTR)GlobalAlloc(GMEM_FIXED, dwDomainName*sizeof(TCHAR));
因为LookupAccountSid在TCHAR中返回大小,而不是以字节为单位