I have problem with MFC DLL. I use Visual Studio 2010.
This is my DLL
#ifdef __cplusplus // If used by C++ code,
extern "C" { // we need to export the C interface
#endif
__declspec(dllexport) void __cdecl GetRAMInfo(DWORD& totaRamlPhysical, DWORD& availablephys, DWORD& memoload)
{
// Lay RAM
MEMORYSTATUS status;
status.dwLength = sizeof(status);
GlobalMemoryStatus( &status ); // lay information of ram
totaRamlPhysical = status.dwTotalPhys; // Tong dung luong RAM vat ly
availablephys = status.dwAvailPhys; // Dung luong RAM vat ly dang duoc su dug
memoload = status.dwMemoryLoad; // phan tram RAM duoc ca he thong su dung
}
__declspec(dllexport) void __cdecl GetCPUInfo(DWORD& processorArchitect, DWORD& typeProcessor, DWORD& numberProcessor)
{
SYSTEM_INFO siSysInfo;
GetSystemInfo(&siSysInfo); // lay thong tin cua CPU
processorArchitect = siSysInfo.wProcessorArchitecture;
numberProcessor = siSysInfo.dwNumberOfProcessors;
typeProcessor = siSysInfo.dwProcessorType;
}
__declspec(dllexport) void __cdecl GetRAMuseandProcessMostUse(CString& namePMU, DWORD& ramUse)
{
//===========NAME PMU ==========//
DWORD sizeallProcess; // Kich thuoc danh sach ID Process thu duoc
DWORD processNumber; // So luong Process thu duoc
DWORD arrayProcessID[100]; // mang chua danh sach ID Process
EnumProcesses( arrayProcessID, sizeof(arrayProcessID), &sizeallProcess ); // lay danh sach process dang chay
processNumber = sizeallProcess / sizeof(DWORD); // Lay so luong Process thu duoc
namePMU = GetProcess(arrayProcessID, processNumber);
///===========RAM USE==============//
DWORD arrayWorkingSetSize[100];
unsigned int i;
ramUse =0;
for( i =0; i < processNumber;i++){
HANDLE hProcess;
PROCESS_MEMORY_COUNTERS pmc;
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, arrayProcessID[i] ); // handle toi 1 process
if (hProcess != NULL)
{
if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ){ // laays kich thuoc bo nho ma tien trinh do su dung
arrayWorkingSetSize[i] = pmc.WorkingSetSize ;
}
}
CloseHandle( hProcess );
}
for(i =2; i<(processNumber); i++){
if(arrayWorkingSetSize[i] != 3435973836){
ramUse += arrayWorkingSetSize[i];
}
}
}
__declspec(dllexport) void __cdecl GetCPUuseandProcessMostUse(CString& namePMUCPU, DOUBLE& cpuUse)
{
//DWORD processID = 2412;
FILETIME ftSysIdle, ftSysKernel, ftSysUser;
FILETIME ftProcCreation, ftProcExit, ftProcKernel, ftProcUser;
//=== HANDLE of a PROCESS ==///
DWORD sizeallProcess; // Kich thuoc danh sach ID Process thu duoc
DWORD processNumber; // So luong Process thu duoc
DWORD arrayProcessID[100]; // mang chua danh sach ID Process
EnumProcesses( arrayProcessID, sizeof(arrayProcessID), &sizeallProcess ); // lay danh sach process dang chay
processNumber = sizeallProcess / sizeof(DWORD); // Lay so luong Process thu duoc
bool flagFor = FALSE;
ULONGLONG arrayTotalSys[2][100];
ULONGLONG arrayTotalProc[2][100];
DOUBLE arrayPercent[100];
for(unsigned int a = 0; a<2; a++) {
for(unsigned int i=2; i<processNumber; i++) {
if(arrayProcessID[i] !=3435973836){
HANDLE hProcess;
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, arrayProcessID[i] );
GetSystemTimes(&ftSysIdle, &ftSysKernel, &ftSysUser);
GetProcessTimes(hProcess, &ftProcCreation, &ftProcExit, &ftProcKernel, &ftProcUser);
arrayTotalSys[a][i] = AddTimes(ftSysKernel, ftSysUser);
arrayTotalProc[a][i] = AddTimes(ftProcKernel, ftProcUser);
}
}
Sleep(500);
}
DOUBLE sumSys =0;
DOUBLE sumProc =0;
for(unsigned int i=2; i<processNumber; i++){
if(arrayProcessID[i] !=3435973836){
/*sumSys += arrayTotalSys[0][i] + arrayTotalSys[1][i];
sumProc += arrayTotalProc[0][i] + arrayTotalProc[1][i];*/
sumSys += arrayTotalSys[1][i] - arrayTotalSys[0][i] ;
sumProc += arrayTotalProc[1][i] - arrayTotalProc[0][i] ;
arrayPercent[i] = (double)((100*sumProc)/sumSys);
}
}
int maxindex = 2;
double processMaxPercent = arrayPercent[2];
double sumpercent =0;
for(unsigned int i =2; i<(processNumber); i++){
if(arrayPercent[i] != 3435973836){
if(processMaxPercent < arrayPercent[i] ){
processMaxPercent = arrayPercent[i];
maxindex = i;
}
sumpercent += arrayPercent[i];
}
}
cpuUse = sumpercent;
namePMUCPU = GetNameProcessMU(arrayProcessID[maxindex]); // tam thoi lay ten mac djnh la cai nay
}
__declspec(dllexport) ULONGLONG __cdecl AddTimes(const FILETIME& ftA,const FILETIME& ftB){
LARGE_INTEGER a, b;
a.LowPart = ftA.dwLowDateTime;
a.HighPart = ftA.dwHighDateTime;
b.LowPart = ftB.dwLowDateTime;
b.HighPart = ftB.dwHighDateTime;
return a.QuadPart + b.QuadPart;
}
__declspec(dllexport) CString __cdecl GetProcess(DWORD arrayProcess[], DWORD numberprocess)
{
// Working set cua cac process
DWORD arrayWorkingSetSize[100];
unsigned int maxindex;
DWORD processMaxSize;
CString nameProcessMaxSize;
unsigned int i;
for( i =0; i < numberprocess;i++){
HANDLE hProcess;
PROCESS_MEMORY_COUNTERS pmc;
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, arrayProcess[i] ); // handle toi 1 process
if (hProcess != NULL)
{
if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ){ // laays kich thuoc bo nho ma tien trinh do su dung
arrayWorkingSetSize[i] = pmc.WorkingSetSize ;
}
}
CloseHandle( hProcess );
}
// Sap xep, lay ra phan tu co WorkingSetSize lon nhat
maxindex = 2;
processMaxSize = arrayWorkingSetSize[2];
for(i =2; i<(numberprocess - 10); i++){
if(arrayWorkingSetSize[i] != 3435973836){
if(processMaxSize < arrayWorkingSetSize[i] ){
processMaxSize = arrayWorkingSetSize[i];
maxindex = i;
}
}
}
// lay ten process co kich thuoc max
nameProcessMaxSize = GetNameProcessMU(arrayProcess[maxindex]);
return nameProcessMaxSize;
}
__declspec(dllexport) CString __cdecl GetNameProcessMU(DWORD processID)
{
CString nameProcess;
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, processID );
// Get the process name.
if (NULL != hProcess )
{
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
&cbNeeded) )
{
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
}
}
nameProcess = (LPCTSTR)szProcessName; // chuyen kieu
CloseHandle( hProcess );
return nameProcess;
}
#ifdef __cplusplus
}
#endif
Now when i build it, it show error again and again to notice that it dont know some function.
Error 1 error C3861: 'GetProcess': identifier not found c:\users\anhnt\documents\visual studio 2010\projects\bkav_btap2_dll\bkav_btap2_dll\bkav_btap2_dll.cpp 104 1 Bkav_btap2_dll
Error 2 error C3861: 'AddTimes': identifier not found c:\users\anhnt\documents\visual studio 2010\projects\bkav_btap2_dll\bkav_btap2_dll\bkav_btap2_dll.cpp 154 1 Bkav_btap2_dll
Error 3 error C3861: 'AddTimes': identifier not found c:\users\anhnt\documents\visual studio 2010\projects\bkav_btap2_dll\bkav_btap2_dll\bkav_btap2_dll.cpp 155 1 Bkav_btap2_dll
Error 4 error C3861: 'GetNameProcessMU': identifier not found c:\users\anhnt\documents\visual studio 2010\projects\bkav_btap2_dll\bkav_btap2_dll\bkav_btap2_dll.cpp 187 1 Bkav_btap2_dll
Warning 5 warning C4190: 'GetProcess' has C-linkage specified, but returns UDT 'ATL::CStringT<BaseType,StringTraits>' which is incompatible with C c:\users\anhnt\documents\visual studio 2010\projects\bkav_btap2_dll\bkav_btap2_dll\bkav_btap2_dll.cpp 200 1 Bkav_btap2_dll
Error 6 error C3861: 'GetNameProcessMU': identifier not found c:\users\anhnt\documents\visual studio 2010\projects\bkav_btap2_dll\bkav_btap2_dll\bkav_btap2_dll.cpp 234 1 Bkav_btap2_dll
Warning 7 warning C4190: 'GetNameProcessMU' has C-linkage specified, but returns UDT 'ATL::CStringT<BaseType,StringTraits>' which is incompatible with C c:\users\anhnt\documents\visual studio 2010\projects\bkav_btap2_dll\bkav_btap2_dll\bkav_btap2_dll.cpp 239 1 Bkav_btap2_dll
Please help me :(. Thanksss
P/s: i read this topic(stackoverflow.com/questions/17332327/cannot-build-dll-with-base-class) but it not work for me.
You're missing to include the Header files for the required libaries. Add (at least) the following line to the beginning of your file:
#include <windows.h>
Edit:
If I'm creating a new Visual Studio Project and paste the above code into a new file it successfully builds if I add the following lines to the top of the source file:
#include "stdafx.h" // Contains the afx default header files (which internally reference Windows.h)
#include <Psapi.h> // for process specific stuff
__declspec(dllexport) CString __cdecl GetProcess(DWORD arrayProcess[], DWORD numberprocess);
__declspec(dllexport) ULONGLONG __cdecl AddTimes(const FILETIME& ftA, const FILETIME& ftB);
__declspec(dllexport) CString __cdecl GetNameProcessMU(DWORD processID);
Additionally, psapi.lib must be added as linker input.
I suggest you read up some documentation on building C++ projects, on header files and libraries. You seem to be missing the understanding for some basic concepts of C++.
EDIT 2
The following are now my files, they build fine. (Any missing files are left as-is when using the MFC Project wizard, they're optional)
Stackoverflow.vcproj
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{D25D3BF5-42FD-4649-BEE4-A7F142367727}</ProjectGuid>
<RootNamespace>StackOverflow</RootNamespace>
<Keyword>MFCDLLProj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>Unicode</CharacterSet>
<UseOfMfc>Dynamic</UseOfMfc>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<UseOfMfc>Dynamic</UseOfMfc>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>SYSTEMINFO_LIB;WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ModuleDefinitionFile>.\StackOverflow.def</ModuleDefinitionFile>
<AdditionalDependencies>psapi.lib</AdditionalDependencies>
</Link>
<Midl>
<MkTypLibCompatible>false</MkTypLibCompatible>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</Midl>
<ResourceCompile>
<Culture>0x0407</Culture>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>Use</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>SYSTEMINFO_LIB;WIN32;_WINDOWS;NDEBUG;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<ModuleDefinitionFile>.\StackOverflow.def</ModuleDefinitionFile>
</Link>
<Midl>
<MkTypLibCompatible>false</MkTypLibCompatible>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</Midl>
<ResourceCompile>
<Culture>0x0407</Culture>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
</ItemDefinitionGroup>
<ItemGroup>
<None Include="ReadMe.txt" />
<None Include="res\StackOverflow.rc2" />
<None Include="StackOverflow.def" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="SystemInfo.cpp" />
<ClCompile Include="StackOverflow.cpp" />
<ClCompile Include="stdafx.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="Resource.h" />
<ClInclude Include="StackOverflow.h" />
<ClInclude Include="stdafx.h" />
<ClInclude Include="SystemInfo.h" />
<ClInclude Include="targetver.h" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="StackOverflow.rc" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
Stackoverflow.vcproj.filters
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Quelldateien">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Headerdateien">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Ressourcendateien">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<None Include="ReadMe.txt" />
<None Include="StackOverflow.def">
<Filter>Quelldateien</Filter>
</None>
<None Include="res\StackOverflow.rc2">
<Filter>Ressourcendateien</Filter>
</None>
</ItemGroup>
<ItemGroup>
<ClCompile Include="StackOverflow.cpp">
<Filter>Quelldateien</Filter>
</ClCompile>
<ClCompile Include="stdafx.cpp">
<Filter>Quelldateien</Filter>
</ClCompile>
<ClCompile Include="SystemInfo.cpp">
<Filter>Quelldateien</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="StackOverflow.h">
<Filter>Headerdateien</Filter>
</ClInclude>
<ClInclude Include="stdafx.h">
<Filter>Headerdateien</Filter>
</ClInclude>
<ClInclude Include="targetver.h">
<Filter>Headerdateien</Filter>
</ClInclude>
<ClInclude Include="Resource.h">
<Filter>Headerdateien</Filter>
</ClInclude>
<ClInclude Include="SystemInfo.h">
<Filter>Headerdateien</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="StackOverflow.rc">
<Filter>Ressourcendateien</Filter>
</ResourceCompile>
</ItemGroup>
</Project>
SystemInfo.cpp
#include "stdafx.h"
#include <Psapi.h>
#include "SystemInfo.h"
SYSTEMINFO_EXPORTS void __cdecl GetRAMInfo(DWORD& totaRamlPhysical, DWORD& availablephys, DWORD& memoload)
{
// Lay RAM
MEMORYSTATUS status;
status.dwLength = sizeof(status);
GlobalMemoryStatus( &status ); // lay information of ram
totaRamlPhysical = status.dwTotalPhys; // Tong dung luong RAM vat ly
availablephys = status.dwAvailPhys; // Dung luong RAM vat ly dang duoc su dug
memoload = status.dwMemoryLoad; // phan tram RAM duoc ca he thong su dung
}
SYSTEMINFO_EXPORTS void __cdecl GetCPUInfo(DWORD& processorArchitect, DWORD& typeProcessor, DWORD& numberProcessor)
{
SYSTEM_INFO siSysInfo;
GetSystemInfo(&siSysInfo); // lay thong tin cua CPU
processorArchitect = siSysInfo.wProcessorArchitecture;
numberProcessor = siSysInfo.dwNumberOfProcessors;
typeProcessor = siSysInfo.dwProcessorType;
}
SYSTEMINFO_EXPORTS void __cdecl GetRAMuseandProcessMostUse(CString& namePMU, DWORD& ramUse)
{
//===========NAME PMU ==========//
DWORD sizeallProcess; // Kich thuoc danh sach ID Process thu duoc
DWORD processNumber; // So luong Process thu duoc
DWORD arrayProcessID[100]; // mang chua danh sach ID Process
EnumProcesses( arrayProcessID, sizeof(arrayProcessID), &sizeallProcess ); // lay danh sach process dang chay
processNumber = sizeallProcess / sizeof(DWORD); // Lay so luong Process thu duoc
namePMU = GetProcess(arrayProcessID, processNumber);
///===========RAM USE==============//
DWORD arrayWorkingSetSize[100];
unsigned int i;
ramUse =0;
for( i =0; i < processNumber;i++){
HANDLE hProcess;
PROCESS_MEMORY_COUNTERS pmc;
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, arrayProcessID[i] ); // handle toi 1 process
if (hProcess != NULL)
{
if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ){ // laays kich thuoc bo nho ma tien trinh do su dung
arrayWorkingSetSize[i] = pmc.WorkingSetSize ;
}
}
CloseHandle( hProcess );
}
for(i =2; i<(processNumber); i++){
if(arrayWorkingSetSize[i] != 3435973836){
ramUse += arrayWorkingSetSize[i];
}
}
}
SYSTEMINFO_EXPORTS void __cdecl GetCPUuseandProcessMostUse(CString& namePMUCPU, DOUBLE& cpuUse)
{
//DWORD processID = 2412;
FILETIME ftSysIdle, ftSysKernel, ftSysUser;
FILETIME ftProcCreation, ftProcExit, ftProcKernel, ftProcUser;
//=== HANDLE of a PROCESS ==///
DWORD sizeallProcess; // Kich thuoc danh sach ID Process thu duoc
DWORD processNumber; // So luong Process thu duoc
DWORD arrayProcessID[100]; // mang chua danh sach ID Process
EnumProcesses( arrayProcessID, sizeof(arrayProcessID), &sizeallProcess ); // lay danh sach process dang chay
processNumber = sizeallProcess / sizeof(DWORD); // Lay so luong Process thu duoc
bool flagFor = FALSE;
ULONGLONG arrayTotalSys[2][100];
ULONGLONG arrayTotalProc[2][100];
DOUBLE arrayPercent[100];
for(unsigned int a = 0; a<2; a++) {
for(unsigned int i=2; i<processNumber; i++) {
if(arrayProcessID[i] !=3435973836){
HANDLE hProcess;
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, arrayProcessID[i] );
GetSystemTimes(&ftSysIdle, &ftSysKernel, &ftSysUser);
GetProcessTimes(hProcess, &ftProcCreation, &ftProcExit, &ftProcKernel, &ftProcUser);
arrayTotalSys[a][i] = AddTimes(ftSysKernel, ftSysUser);
arrayTotalProc[a][i] = AddTimes(ftProcKernel, ftProcUser);
}
}
Sleep(500);
}
DOUBLE sumSys =0;
DOUBLE sumProc =0;
for(unsigned int i=2; i<processNumber; i++){
if(arrayProcessID[i] !=3435973836){
/*sumSys += arrayTotalSys[0][i] + arrayTotalSys[1][i];
sumProc += arrayTotalProc[0][i] + arrayTotalProc[1][i];*/
sumSys += arrayTotalSys[1][i] - arrayTotalSys[0][i] ;
sumProc += arrayTotalProc[1][i] - arrayTotalProc[0][i] ;
arrayPercent[i] = (double)((100*sumProc)/sumSys);
}
}
int maxindex = 2;
double processMaxPercent = arrayPercent[2];
double sumpercent =0;
for(unsigned int i =2; i<(processNumber); i++){
if(arrayPercent[i] != 3435973836){
if(processMaxPercent < arrayPercent[i] ){
processMaxPercent = arrayPercent[i];
maxindex = i;
}
sumpercent += arrayPercent[i];
}
}
cpuUse = sumpercent;
namePMUCPU = GetNameProcessMU(arrayProcessID[maxindex]); // tam thoi lay ten mac djnh la cai nay
}
SYSTEMINFO_EXPORTS ULONGLONG __cdecl AddTimes(const FILETIME& ftA,const FILETIME& ftB){
LARGE_INTEGER a, b;
a.LowPart = ftA.dwLowDateTime;
a.HighPart = ftA.dwHighDateTime;
b.LowPart = ftB.dwLowDateTime;
b.HighPart = ftB.dwHighDateTime;
return a.QuadPart + b.QuadPart;
}
SYSTEMINFO_EXPORTS CString __cdecl GetProcess(DWORD arrayProcess[], DWORD numberprocess)
{
// Working set cua cac process
DWORD arrayWorkingSetSize[100];
unsigned int maxindex;
DWORD processMaxSize;
CString nameProcessMaxSize;
unsigned int i;
for( i =0; i < numberprocess;i++){
HANDLE hProcess;
PROCESS_MEMORY_COUNTERS pmc;
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, arrayProcess[i] ); // handle toi 1 process
if (hProcess != NULL)
{
if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ){ // laays kich thuoc bo nho ma tien trinh do su dung
arrayWorkingSetSize[i] = pmc.WorkingSetSize ;
}
}
CloseHandle( hProcess );
}
// Sap xep, lay ra phan tu co WorkingSetSize lon nhat
maxindex = 2;
processMaxSize = arrayWorkingSetSize[2];
for(i =2; i<(numberprocess - 10); i++){
if(arrayWorkingSetSize[i] != 3435973836){
if(processMaxSize < arrayWorkingSetSize[i] ){
processMaxSize = arrayWorkingSetSize[i];
maxindex = i;
}
}
}
// lay ten process co kich thuoc max
nameProcessMaxSize = GetNameProcessMU(arrayProcess[maxindex]);
return nameProcessMaxSize;
}
SYSTEMINFO_EXPORTS CString __cdecl GetNameProcessMU(DWORD processID)
{
CString nameProcess;
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, processID );
// Get the process name.
if (NULL != hProcess )
{
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
&cbNeeded) )
{
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
}
}
nameProcess = (LPCTSTR)szProcessName; // chuyen kieu
CloseHandle( hProcess );
return nameProcess;
}
SystemInfo.h
#pragma once
#include <Psapi.h>
SYSTEMINFO_EXPORTS CString __cdecl GetProcess(DWORD arrayProcess[], DWORD numberprocess);
SYSTEMINFO_EXPORTS ULONGLONG __cdecl AddTimes(const FILETIME& ftA, const FILETIME& ftB);
SYSTEMINFO_EXPORTS CString __cdecl GetNameProcessMU(DWORD processID);
and these lines added to stdafx.h:
#ifdef SYSTEMINFO_LIB
#define SYSTEMINFO_EXPORTS __declspec(dllexport)
#else
#define SYSTEMINFO_EXPORTS __declspec(dllimport)
#endif
(Yiack, I hope I'm not breaking any rules by posting this much code here.)
Related
I use detours to hook win32 api CreateFile and use CaptureStackBackTrace to get callstack information. and then resolve symbol by SymFromAddr api. but the result shown in terminal is only error 126 and error 184. And I only invoke ShowTraceStack function one time while trace information is more than one. I do not know what happened, can someone help me?
#include <windows.h>
#include <stdio.h>
#include "detours.h"
#include <fstream>
#include <Shlwapi.h>
#pragma comment(lib, "shlwapi.lib") //Windows API PathFileExists
#include <io.h>
#pragma comment(lib, "detours.lib")
#include <DbgHelp.h> //SymInitialize
#pragma comment(lib,"dbghelp.lib")
#define STACK_INFO_LEN 20000
struct stackInfo {
PDWORD hashValue; // hash value to identify same stack
char* szBriefInfo; // callstack info
};
stackInfo ShowTraceStack(char* szBriefInfo)
{
static const int MAX_STACK_FRAMES = 200;
void* pStack[MAX_STACK_FRAMES];
static char szStackInfo[STACK_INFO_LEN * MAX_STACK_FRAMES];
static char szFrameInfo[STACK_INFO_LEN];
HANDLE process = GetCurrentProcess(); // The handle used must be unique to avoid sharing a session with another component,
SymInitialize(process, NULL, TRUE);
PDWORD hashValue = (PDWORD)malloc(sizeof(DWORD)); // allow memory for hashVavlue, it will be rewrited in function CaptureStackBackTrace
WORD frames = CaptureStackBackTrace(0, MAX_STACK_FRAMES, pStack, hashValue);
//printf("hash value is: %ud \n", &hashValue);
if (szBriefInfo == NULL) {
strcpy_s(szStackInfo, "stack traceback:\n");
}
else {
strcpy_s(szStackInfo, szBriefInfo);
}
for (WORD i = 0; i < frames; ++i) {
DWORD64 address = (DWORD64)(pStack[i]);
DWORD64 displacementSym = 0;
char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)];
PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer;
pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
pSymbol->MaxNameLen = MAX_SYM_NAME;
DWORD displacementLine = 0;
IMAGEHLP_LINE64 line;
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
if (SymFromAddr(process, address, &displacementSym, pSymbol) &&
SymGetLineFromAddr64(process, address, &displacementLine, &line))
{
_snprintf_s(szFrameInfo, sizeof(szFrameInfo), "\t%s() at %s:%d(0x%x)\n",
pSymbol->Name, line.FileName, line.LineNumber, pSymbol->Address);
}
else
{
_snprintf_s(szFrameInfo, sizeof(szFrameInfo), "\terror: %d\n", GetLastError());
}
strcat_s(szStackInfo, szFrameInfo);
}
stackInfo traceStackInfo;
traceStackInfo.hashValue = hashValue;
traceStackInfo.szBriefInfo = szStackInfo;
printf("%s", szStackInfo);
return traceStackInfo;
}
HANDLE(*oldCreateFile)(LPCWSTR,
DWORD,
DWORD,
LPSECURITY_ATTRIBUTES,
DWORD,
DWORD,
HANDLE) = CreateFileW;
HANDLE WINAPI newCreateFile(
_In_ LPCWSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile
) {
ShowTraceStack((char*)"trace information.");
return oldCreateFile(
L".\\newFiles.txt", // L".\\NewFile.txt", // Filename
//lpFileName,
dwDesiredAccess, // Desired access
dwShareMode, // Share mode
lpSecurityAttributes, // Security attributes
dwCreationDisposition, // Creates a new file, only if it doesn't already exist
dwFlagsAndAttributes, // Flags and attributes
NULL);
}
void hook() {
DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)oldCreateFile, newCreateFile);
DetourTransactionCommit();
}
void unhook()
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)oldCreateFile, newCreateFile);
DetourTransactionCommit();
}
void myProcess() {
HANDLE hFile = CreateFile(TEXT(".\\CreateFileDemo.txt"),
GENERIC_WRITE | GENERIC_READ,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
OutputDebugString(TEXT("CreateFile fail!\r\n"));
}
// write to file
const int BUFSIZE = 4096;
char chBuffer[BUFSIZE];
memcpy(chBuffer, "Test", 4);
DWORD dwWritenSize = 0;
BOOL bRet = WriteFile(hFile, chBuffer, 4, &dwWritenSize, NULL);
ShowTraceStack((char*)"trace information.");
if (bRet)
{
OutputDebugString(TEXT("WriteFile success!\r\n"));
}
}
int main(){
hook();
myProcess();
unhook();
}
I am trying to set over time my PC time in Windows in C++. It doesn't work.
I already run my project as administrator.
I asked some privileges to effcetion this task.
But nothing, etc...
Could you have some ideas about it ?
Here is my code :
#include <windows.h>
#include <stdio.h>
#include <strsafe.h>
using namespace std;
void main()
{
SYSTEMTIME st;
ZeroMemory(&st, sizeof(st));
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
// Enable the required privilege
OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_ALL_ACCESS, &hToken);
LookupPrivilegeValue(NULL, SE_SYSTEMTIME_NAME, &tkp.Privileges[0].Luid);
tkp.PrivilegeCount = 1; // valider deux privileges , tkp contient les parametres de chaque privilege
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; // je valide le privilege 1
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0); // pour valider ou desactiver les privileges dans un acces precis.
// LookupPrivilegeValue(NULL, SE_TIME_ZONE_NAME, &tkp.Privileges[1].Luid);
// tkp.Privileges[1].Attributes = SE_PRIVILEGE_ENABLED; // je valide le privilege 2
// Set system time
st.wHour = 15;
st.wMinute = 15;
SetSystemTime(&st);
GetSystemTime(&st);
printf("The system time is: %02d:%02d\n", st.wHour, st.wMinute);
tkp.Privileges[0].Attributes = 0;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
system("pause");
}
I have the following problem to solve (VS2012, C++)
I have to find out if a specific HTA app is running from my exe. For that, I have to find the process mshta and check if it has correct arguments (should have been started as "mshta somehta.hta"). My first attempt was to iterate over the processes/modules, which I can do now. I see mshta listed and its PID. But, I did not find the way to get the info, how it was started. Is there a way to do it?
ProcessExists(wchar_t* processName)
{
DWORD aProcesses[1024], cbNeeded, cProcesses;
unsigned int i;
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
{
return false;
}
// Calculate how many process identifiers were returned.
cProcesses = cbNeeded / sizeof(DWORD);
// Print the name and process identifier for each process.
for ( i = 0; i < cProcesses; i++ )
{
if( aProcesses[i] != 0 )
{
PrintProcessNameAndID( aProcesses[i] );
}
}
return false;
}
void PrintProcessNameAndID( DWORD processID )
{
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
// Get a handle to the process.
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, processID );
// Get the process name.
if (NULL != hProcess )
{
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
&cbNeeded) )
{
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
}
}
// Print the process name and identifier.
dprintf( TEXT("%s (PID: %u) %s %s\n"), szProcessName, processID );
// Release the handle to the process.
CloseHandle( hProcess );
}
I ended up to use the solution proposed here: http://www.codeproject.com/Articles/19685/Get-Process-Info-with-NtQueryInformationProcess
I am running com scripts from c++ on windows xp
Usually the script executes without problems, but sometimes the execution fails with hresult DISP_E_MEMBERNOTFOUND. (Invoke is the function that fails)
Does anybody have any idea why it happens?
The code is below
CLSID clsid;
MULTI_QI mqi;
HRESULT hr ;
mqi.hr = 0;
mqi.pIID = &IID_IDispatch;
mqi.pItf = NULL;
hr = CLSIDFromProgID(T2W(progId.c_str()), &clsid);
CHECK_HRESULT(hr);
hr = CoCreateInstanceEx(clsid, NULL, CLSCTX_INPROC_SERVER, NULL, 1, &mqi);
CHECK_HRESULT(hr);
tMethodArguments argTemp(arguments.size()) ;
USES_CONVERSION ;
HRESULT hr;
DISPID index ;
OLECHAR FAR* szMember = T2W(method.c_str());
unsigned int err ;
hr = m_pScriptComObj->GetIDsOfNames( IID_NULL, &szMember, 1, LOCALE_SYSTEM_DEFAULT, &index ) ;
CHECK_HRESULT(hr);
DISPPARAMS params ;
params.rgvarg = pArgs ;
params.rgdispidNamedArgs = NULL ;
params.cArgs = arguments.size() ;
params.cNamedArgs = 0 ;
EXCEPINFO excep_info;
hr = m_pScriptComObj->Invoke(index,
IID_NULL,
LOCALE_SYSTEM_DEFAULT,
DISPATCH_METHOD,
¶ms,
&res,
&excep_info,
&err);
I omitted method and arguments initialization
The vbscript that is called by INVOKE looks like this
<?xml version="1.0"?>
<component id="script_wsc_script">
<?component?>
<registration
description="script_wsc_script"
progid="wscScript.WSC"
version="1.00"
classid="{A1C14070-EBAB-41A0-BC9C-B4330A73437D}"
remotable="true"
>
</registration>
<public>
<method name="PrintMessage">
<PARAMETER name="first"/>
<PARAMETER name="second"/>
</method>
</public>
<script language="VBScript">
<![CDATA[
Function PrintMessage ( first, second)
''do something
End Function
I use win7 os and the develop environment is vs2005.
The situation is I want to create the process as current account's priviledge.(such as: in the normal account ,right click the program choice "run as admin" )
I refer to other people's way:
1.get the token of the process explorer.exe;
2.improve the priviledge;
3.use the CreateProcessAsUser to create a process.
But the CreateProcessAsUser failed,and use GetLastError() to get the error code is 1314.
Because of that, I think I'am crazy now.
Can you tell me what's wrong in my program. Thank you!!!
#include <iostream>
using namespace std;
#include "windows.h"
#include "tlhelp32.h"
BOOL GetProcessTokenByName(HANDLE &hToken, LPTSTR szProcessName)
{
// var init
STARTUPINFO st;
PROCESS_INFORMATION pi;
PROCESSENTRY32 ps;
HANDLE hSnapshot;
ZeroMemory(&st, sizeof(STARTUPINFO));
ZeroMemory(&pi, sizeof(PROCESS_INFORMATIO
N));
st.cb = sizeof(STARTUPINFO);
ZeroMemory(&ps,sizeof(PROCESSENTRY32));
ps.dwSize = sizeof(PROCESSENTRY32);
// find the explorer.exe
hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0);
if(hSnapshot == INVALID_HANDLE_VALUE)
{
return FALSE;
}
if(!Process32First(hSnapshot,&ps))
{
return FALSE;
}
do
{
wprintf(_T("%s , %u\n"), ps.szExeFile, ps.th32ProcessID);
// compare the process name
if(lstrcmpi(ps.szExeFile,szProcessName)==0)
{ // find
//*lpPID = ps.th32ProcessID;
//CloseHandle(hSnapshot);
//return TRUE;
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, ps.th32ProcessID);
BOOL bRet = FALSE;
HANDLE tmpToken;
if( OpenProcessToken(hProcess, /*TOKEN_QUERY*/TOKEN_ALL_ACCESS, &tmpToken) )
{
bRet = DuplicateTokenEx(
tmpToken, //_In_ HANDLE hExistingToken,
MAXIMUM_ALLOWED, //_In_ DWORD dwDesiredAccess,
NULL, //_In_opt_ LPSECURITY_ATTRIBUTES lpTokenAttributes,
SecurityIdentification, //_In_ SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
TokenPrimary, //_In_ TOKEN_TYPE TokenType,
&hToken //_Out_ PHANDLE phNewToken
);
//DWORD dwSessionId = WTSGetActiveConsoleSessionId();
//SetTokenInformation(hToken,TokenSessionId,(void*)dwSessionId,sizeof(DWORD));
//SetPrivilege(hToken, SE_ASSIGNPRIMARYTOKEN_NAME, TRUE);
}
else
{
printf("OpenProcessToken error: %u\n", GetLastError());
}
CloseHandle (hSnapshot);
return (bRet);
}
}while(Process32Next(hSnapshot,&ps));
// didn't find
CloseHandle(hSnapshot);
return FALSE;
}
BOOL RunasUser( )
{
HANDLE hToken;
if( GetProcessTokenByName( hToken, _T("explorer.exe") ) )
{
if( hToken != INVALID_HANDLE_VALUE )
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb= sizeof(STARTUPINFO);
si.lpDesktop = TEXT("winsta0\\default");
{
TOKEN_PRIVILEGES tp;
tp.PrivilegeCount =1;
if(!LookupPrivilegeValue(NULL,SE_ASSIGNPRIMARYTOKEN_NAME/*SE_DEBUG_NAME*/,&tp.Privileges[0].Luid))
{
printf("LookupPrivilegeValue value Error: %u\n",GetLastError());
}
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if(!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, NULL) )
{
printf("Adjust Privilege value Error: %u\n",GetLastError());
}
}
printf("Adjust Privilege\n");
{
TOKEN_PRIVILEGES tp;
tp.PrivilegeCount =1;
if(!LookupPrivilegeValue(NULL,SE_INCREASE_QUOTA_NAME/*SE_DEBUG_NAME*/,&tp.Privileges[0].Luid))
{
printf("LookupPrivilegeValue value Error: %u\n",GetLastError());
}
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if(!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, NULL) )
{
printf("Adjust Privilege value Error: %u\n",GetLastError());
}
}
BOOL bResult = CreateProcessAsUser(
hToken, //_In_opt_ HANDLE hToken,
_T("D:\\GetMac.exe"), //_In_opt_ LPCTSTR lpApplicationName,
NULL, //_Inout_opt_ LPTSTR lpCommandLine,
NULL, //_In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes,
NULL, //_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
FALSE, //_In_ BOOL bInheritHandles,
NORMAL_PRIORITY_CLASS, //_In_ DWORD dwCreationFlags,
NULL, //_In_opt_ LPVOID lpEnvironment,
NULL, //_In_opt_ LPCTSTR lpCurrentDirectory,
&si, //_In_ LPSTARTUPINFO lpStartupInfo,
&pi //_Out_ LPPROCESS_INFORMATION lpProcessInformation
);
CloseHandle(hToken);
if( bResult )
{
//succeed
return TRUE;
}
else
{ //fail
DWORD dwErr = GetLastError();
printf( "error: %u\n", dwErr );
}
}
}
else
{
printf("GetProcessTokenByName fail\n");
}
return FALSE;
}
int _tmain(int argc, _TCHAR* argv[])
{
BOOL bRet = RunasUser();
printf("result: %d\n", bRet);
system("pause");
return 0;
}