WinCE: How can I determine the module that contains a code address? - visual-c++

I wrote a solution that involved OpenProcess, EnumProcessModules, GetModuleInformation and GetModuleBaseName, but apparently EnumProcessModules and GetModuleBaseName do not exist in Windows CE! What alternative is there?

I found a way to do this with CreateToolhelp32Snapshot, Module32First, Module32Next, Process32First and Process32Next. First you have to get a list of modules, then search through the list of modules to find the desired address.
#include <Tlhelp32.h>
struct MyModuleInfo
{
BYTE* Base;
HMODULE Handle;
DWORD Size;
enum { MaxNameLen = 36 };
TCHAR Name[MaxNameLen];
};
bool GetModuleList(vector<MyModuleInfo>& moduleList)
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS | TH32CS_SNAPMODULE | TH32CS_GETALLMODS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE)
return false;
MODULEENTRY32 moduleInfo;
moduleInfo.dwSize = sizeof(moduleInfo);
if (Module32First(hSnapshot, &moduleInfo)) do {
MyModuleInfo myInfo;
myInfo.Handle = moduleInfo.hModule;
myInfo.Base = moduleInfo.modBaseAddr;
myInfo.Size = moduleInfo.modBaseSize;
memcpy(myInfo.Name, moduleInfo.szModule, min(sizeof(myInfo.Name), sizeof(moduleInfo.szModule)));
myInfo.Name[myInfo.MaxNameLen-1] = '\0';
moduleList.push_back(myInfo);
} while (Module32Next(hSnapshot, &moduleInfo));
// The module list obtained above only contains DLLs! To get the EXE files
// also, we must call Process32First and Process32Next in a loop.
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
if (Process32First(hSnapshot, &processInfo)) do {
MyModuleInfo myInfo;
myInfo.Handle = NULL; // No handle given
myInfo.Base = (BYTE*)processInfo.th32MemoryBase;
myInfo.Size = 0x800000; // No size provided! Allow max 8 MB
memcpy(myInfo.Name, processInfo.szExeFile, min(sizeof(myInfo.Name), sizeof(processInfo.szExeFile)));
myInfo.Name[myInfo.MaxNameLen-1] = '\0';
moduleList.push_back(myInfo);
} while(Process32Next(hSnapshot, &processInfo));
// Debug output
for (int i = 0; i < (int)moduleList.size(); i++) {
MyModuleInfo& m = moduleList[i];
TRACE(_T("%-30s: 0x%08x - 0x%08x\n"), m.Name, (DWORD)m.Base, (DWORD)m.Base + m.Size);
}
CloseToolhelp32Snapshot(hSnapshot);
return true;
}
const MyModuleInfo* GetModuleForAddress(vector<MyModuleInfo>& moduleList, void* address)
{
for (int m = 0; m < (int)moduleList.size(); m++) {
const MyModuleInfo& mInfo = moduleList[m];
if (address >= mInfo.Base && address < mInfo.Base + mInfo.Size)
return &mInfo;
}
return NULL;
}

Related

Populating std::map and calling find return end() even though the entry is in the map

So, I create this map on the fly so I can update the image type for all the images in the library (currently over 1 million). The map populates well, HOWEVER, despite visually seeing the extension ("jpg") added to the map, std::map::find("jpg") == std::map::end() always. What gives.
void CImageLibrary::ThreadedUpdateImageLibraryFileDuringOpen(shared_ptr<ScanData> pScanData)
{
size_t nCount = pScanData->GetImageLibrary()->m_imageEntries.count();
std::map<std::wstring, CImageType *> mapImageExtToType;
for (const auto &pImageType : pScanData->GetImageLibrary()->m_vecImageTypes)
{
std::vector<std::wstring> vecExtensions;
pImageType->GetAssociatedExtensions(vecExtensions);
for (auto ext : vecExtensions)
{
std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
mapImageExtToType[ext] = pImageType;
}
}
for (size_t idx = 0; idx < nCount; ++idx)
{
CImageEntry *pEntry = pScanData->GetImageLibrary()->m_imageEntries[idx];
if (pEntry && !pEntry->GetImageType())
{
wstring &wsPath = pEntry->GetPathName(), wsExt;
size_t nIdx = wsPath.find_last_of('.');
wsExt = wsPath.substr(nIdx + 1);
std::transform(wsExt.begin(), wsExt.end(), wsExt.begin(), ::tolower);
auto Itor = mapImageExtToType.find(wsExt);
if (Itor == mapImageExtToType.end())
pEntry->m_pImageType = nullptr;
else
pEntry->m_pImageType = Itor->second;
}
}
pScanData->GetBkgndThreadManager()->MarkOperationThreadDone(std::this_thread::get_id());
}

How to detect window state in linux?

I need to find out if a native linux application window is maximized or minimized in a java program.
I tried using X11.XGetWindowProperty() and I get some results also, but I cant make out any useful information in it.
I am using JNA 4.2.1, Java 8 update72 on Ubuntu 14.04 LTS. Any pointers will be very helpful. Thanks in advance to all.
[Edit]
I have the code below which gives me the result I need. But the result is not same for every invocation. The atoms which are returned for the window vary within invocations. Is there any other reliable way to get the window state?
private static X11 x11 = X11.INSTANCE;
private static Display dispy = x11.XOpenDisplay(null);
public static void main(String[] args) {
try {
X11.Atom[] atoms = getAtomProperties(
bytesToInt(getProperty(X11.XA_ATOM, X11.INSTANCE.XInternAtom(dispy, "_NET_WM_STATE", false))));
boolean hidden = false;
boolean vmax = false;
boolean hmax = false;
for (int i = 0; i < atoms.length; i++) {
X11.Atom atom = atoms[i];
if (atom == null)
continue;
String atomName = X11.INSTANCE.XGetAtomName(dispy, atom);
if ("_NET_WM_STATE_HIDDEN".equals(atomName)) {
hidden = true;
} else if ("_NET_WM_STATE_MAXIMIZED_VERT".equals(atomName)) {
vmax = true;
} else if ("_NET_WM_STATE_MAXIMIZED_HORZ".equals(atomName)) {
hmax = true;
}
}
if (hidden)
System.out.println("Window minimized");
else if (vmax && hmax && !hidden)
System.out.println("Window maximized");
else
System.out.println("Window normal");
} catch (X11Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static X11.Atom[] getAtomProperties(int[] ids) {
X11.Atom[] atoms = new X11.Atom[ids.length];
for (int i = 0; i < ids.length; i++) {
if (ids[i] == 0)
continue;
atoms[i] = new X11.Atom(ids[i]);
}
return atoms;
}
private static int[] bytesToInt(byte[] prop) {
if (prop == null)
return null;
int[] res = new int[prop.length / 4];
for (int i = 0; i < res.length; i++) {
res[i] = ((prop[i * 4 + 3] & 0xff) << 24) | ((prop[i * 4 + 2] & 0xff) << 16) | ((prop[i * 4 + 1] & 0xff) << 8)
| ((prop[i * 4 + 0] & 0xff));
if (res[i] != 0)
continue;
}
return res;
}
private static byte[] getProperty(X11.Atom xa_prop_type, X11.Atom xa_prop_name) throws X11Exception {
X11.Window window = new X11.Window(73400355);
X11.AtomByReference xa_ret_type_ref = new X11.AtomByReference();
IntByReference ret_format_ref = new IntByReference();
NativeLongByReference ret_nitems_ref = new NativeLongByReference();
NativeLongByReference ret_bytes_after_ref = new NativeLongByReference();
PointerByReference ret_prop_ref = new PointerByReference();
NativeLong long_offset = new NativeLong(0);
NativeLong long_length = new NativeLong(4096 / 4);
/*
* MAX_PROPERTY_VALUE_LEN / 4 explanation (XGetWindowProperty manpage):
*
* long_length = Specifies the length in 32-bit multiples of the data to be retrieved.
*/
if (x11.XGetWindowProperty(dispy, window, xa_prop_name, long_offset, long_length, false, xa_prop_type, xa_ret_type_ref,
ret_format_ref, ret_nitems_ref, ret_bytes_after_ref, ret_prop_ref) != X11.Success) {
String prop_name = x11.XGetAtomName(dispy, xa_prop_name);
throw new X11Exception("Cannot get " + prop_name + " property.");
}
X11.Atom xa_ret_type = xa_ret_type_ref.getValue();
Pointer ret_prop = ret_prop_ref.getValue();
if (xa_ret_type == null) {
// the specified property does not exist for the specified window
return null;
}
if (xa_ret_type == null || xa_prop_type == null || !xa_ret_type.toNative().equals(xa_prop_type.toNative())) {
x11.XFree(ret_prop);
String prop_name = x11.XGetAtomName(dispy, xa_prop_name);
throw new X11Exception("Invalid type of " + prop_name + " property");
}
int ret_format = ret_format_ref.getValue();
long ret_nitems = ret_nitems_ref.getValue().longValue();
// null terminate the result to make string handling easier
int nbytes;
if (ret_format == 32)
nbytes = Native.LONG_SIZE;
else if (ret_format == 16)
nbytes = Native.LONG_SIZE / 2;
else if (ret_format == 8)
nbytes = 1;
else if (ret_format == 0)
nbytes = 0;
else
throw new X11Exception("Invalid return format");
int length = Math.min((int) ret_nitems * nbytes, 4096);
byte[] ret = ret_prop.getByteArray(0, length);
x11.XFree(ret_prop);
return ret;
}

How can i download only new records from Anviz EP300?

All,
Currently i'm using Anviz EP300 time attendance machine. I need to download only new records from device.
I'm using following sdk. Click here
There is some method already have in sdk. Which is i used like...
int i = 0;
int Ret = 0;
int RecordCount = 0;
int RetCount = 0;
int pClockings = 0;
int pLongRun = 0;
CKT_DLL.CLOCKINGRECORD clocking = new CKT_DLL.CLOCKINGRECORD();
clocking.Time = new byte[20];
int ptemp = 0;
ProgressBar1.Value = 0;
//If CKT_GetClockingNewRecordEx(IDNumber, pLongRun) Then 'IF GET NewRecord
if (CKT_DLL.CKT_GetClockingNewRecordEx(IDNumber, ref pLongRun) != 0) //IF GET Record
{
while (true)
{
Ret = CKT_DLL.CKT_GetClockingRecordProgress(pLongRun, ref RecordCount, ref RetCount, ref pClockings);
if (RecordCount > 0)
{
ProgressBar1.Maximum = RecordCount;
}
if (Ret == 0)
{
return;
}
if (Ret != 0)
{
ptemp = pClockings;
for (i = 1; i <= RetCount; i++)
{
PCopyMemory(ref clocking, pClockings, CKT_DLL.CLOCKINGRECORDSIZE);
pClockings = pClockings + CKT_DLL.CLOCKINGRECORDSIZE;
insertTimeAttendance(clocking.PersonID, clocking.Stat, Encoding.Default.GetString(clocking.Time), clocking.ID);
ProgressBar1.Value += 1;
}
if (ptemp != 0)
{
CKT_DLL.CKT_FreeMemory(ptemp);
}
}
if (Ret == 1)
{
return;
}
}
}
CKT_GetClockingNewRecordEx that method should be return new records. But it returns all records.
I guess, there is should be one method or config should be mark as downloaded.
Anyone some idea or solution?
Thanks,
Eba
I created the SDK you downloaded (basically written in Vb, and I just convert it to C#)
Actually for the Anviz EP300 device, there is no way you can just retrieve new records,neither retrieve user lists (for example), at list with that SDK.. It has a lot of methods, but unfortunately few of them works fine. You will have to Use CKT_GetClockingRecordEx, instead of CKT_DLL.CKT_GetClockingNewRecordEx

How to create sourcemaps for concatenated files

I want to concatenate a bunch of different files of a single type into one large file. For example, many javascript files into one large file, many css files down to one etc. I want to create a sourcemap of the files pre concatenation, but I do not know where to start. I am working in Node, but I am also open to solutions in other environments.
I know there are tools that can do this, but they seem to be on a language by language basis (uglifyjs, cssmin or whatever its called these days), but I want a tool that is not language specific.
Also, I would like to define how the files are bound. For example, in javascript I want to give each file its own closure with an IIFE. Such as:
(function () {
// File
}());
I can also think of other wrappers I would like to implement for different files.
Here are my options as I see it right now. However, I don't know which is best or how to start any of them.
Find a module that does this (I'm working in a Node.js environment)
Create an algorithm with Mozilla's source-map module. For that I also see a couple options.
Only map each line to the new line location
Map every single character to the new location
Map every word to its new location (this options seems way out of scope)
Don't even worry about source maps
What do you guys think about these options. I've already tried options 2.1 and 2.2, but the solution seemed way too complicated for a concatenation algorithm and it did not perform perfectly in the Google Chrome browser tools.
I implemented code without any dependencies like this:
export interface SourceMap {
version: number; // always 3
file?: string;
sourceRoot?: string;
sources: string[];
sourcesContent?: string[];
names?: string[];
mappings: string | Buffer;
}
const emptySourceMap: SourceMap = { version: 3, sources: [], mappings: new Buffer(0) }
var charToInteger = new Buffer(256);
var integerToChar = new Buffer(64);
charToInteger.fill(255);
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('').forEach((char, i) => {
charToInteger[char.charCodeAt(0)] = i;
integerToChar[i] = char.charCodeAt(0);
});
class DynamicBuffer {
buffer: Buffer;
size: number;
constructor() {
this.buffer = new Buffer(512);
this.size = 0;
}
ensureCapacity(capacity: number) {
if (this.buffer.length >= capacity)
return;
let oldBuffer = this.buffer;
this.buffer = new Buffer(Math.max(oldBuffer.length * 2, capacity));
oldBuffer.copy(this.buffer);
}
addByte(b: number) {
this.ensureCapacity(this.size + 1);
this.buffer[this.size++] = b;
}
addVLQ(num: number) {
var clamped: number;
if (num < 0) {
num = (-num << 1) | 1;
} else {
num <<= 1;
}
do {
clamped = num & 31;
num >>= 5;
if (num > 0) {
clamped |= 32;
}
this.addByte(integerToChar[clamped]);
} while (num > 0);
}
addString(s: string) {
let l = Buffer.byteLength(s);
this.ensureCapacity(this.size + l);
this.buffer.write(s, this.size);
this.size += l;
}
addBuffer(b: Buffer) {
this.ensureCapacity(this.size + b.length);
b.copy(this.buffer, this.size);
this.size += b.length;
}
toBuffer(): Buffer {
return this.buffer.slice(0, this.size);
}
}
function countNL(b: Buffer): number {
let res = 0;
for (let i = 0; i < b.length; i++) {
if (b[i] === 10) res++;
}
return res;
}
export class SourceMapBuilder {
outputBuffer: DynamicBuffer;
sources: string[];
mappings: DynamicBuffer;
lastSourceIndex = 0;
lastSourceLine = 0;
lastSourceCol = 0;
constructor() {
this.outputBuffer = new DynamicBuffer();
this.mappings = new DynamicBuffer();
this.sources = [];
}
addLine(text: string) {
this.outputBuffer.addString(text);
this.outputBuffer.addByte(10);
this.mappings.addByte(59); // ;
}
addSource(content: Buffer, sourceMap?: SourceMap) {
if (sourceMap == null) sourceMap = emptySourceMap;
this.outputBuffer.addBuffer(content);
let sourceLines = countNL(content);
if (content.length > 0 && content[content.length - 1] !== 10) {
sourceLines++;
this.outputBuffer.addByte(10);
}
let sourceRemap = [];
sourceMap.sources.forEach((v) => {
let pos = this.sources.indexOf(v);
if (pos < 0) {
pos = this.sources.length;
this.sources.push(v);
}
sourceRemap.push(pos);
});
let lastOutputCol = 0;
let inputMappings = (typeof sourceMap.mappings === "string") ? new Buffer(<string>sourceMap.mappings) : <Buffer>sourceMap.mappings;
let outputLine = 0;
let ip = 0;
let inOutputCol = 0;
let inSourceIndex = 0;
let inSourceLine = 0;
let inSourceCol = 0;
let shift = 0;
let value = 0;
let valpos = 0;
const commit = () => {
if (valpos === 0) return;
this.mappings.addVLQ(inOutputCol - lastOutputCol);
lastOutputCol = inOutputCol;
if (valpos === 1) {
valpos = 0;
return;
}
let outSourceIndex = sourceRemap[inSourceIndex];
this.mappings.addVLQ(outSourceIndex - this.lastSourceIndex);
this.lastSourceIndex = outSourceIndex;
this.mappings.addVLQ(inSourceLine - this.lastSourceLine);
this.lastSourceLine = inSourceLine;
this.mappings.addVLQ(inSourceCol - this.lastSourceCol);
this.lastSourceCol = inSourceCol;
valpos = 0;
}
while (ip < inputMappings.length) {
let b = inputMappings[ip++];
if (b === 59) { // ;
commit();
this.mappings.addByte(59);
inOutputCol = 0;
lastOutputCol = 0;
outputLine++;
} else if (b === 44) { // ,
commit();
this.mappings.addByte(44);
} else {
b = charToInteger[b];
if (b === 255) throw new Error("Invalid sourceMap");
value += (b & 31) << shift;
if (b & 32) {
shift += 5;
} else {
let shouldNegate = value & 1;
value >>= 1;
if (shouldNegate) value = -value;
switch (valpos) {
case 0: inOutputCol += value; break;
case 1: inSourceIndex += value; break;
case 2: inSourceLine += value; break;
case 3: inSourceCol += value; break;
}
valpos++;
value = shift = 0;
}
}
}
commit();
while (outputLine < sourceLines) {
this.mappings.addByte(59);
outputLine++;
}
}
toContent(): Buffer {
return this.outputBuffer.toBuffer();
}
toSourceMap(sourceRoot?: string): Buffer {
return new Buffer(JSON.stringify({ version: 3, sourceRoot, sources: this.sources, mappings: this.mappings.toBuffer().toString() }));
}
}
I, at first, implemented "index map" from that spec, only to find out that it is not supported by any browser.
Another project that could be useful to look at is magic string.

How to Drag and Drop multiple files between Namespace extensions

I am working on a namespace extension project, I need to implement multiple files drag and drop between Namespace Extensions. I have used DragQueryFile API to find the the number of files. But Always this Function give a crash.
Could anyone help me by explaining how we can implement this multiple files Drag and drop.
Thanks,
Robin
Here is how I use it
void yourclass::OnDropFiles(HDROP hDropInfo)
{
TCHAR lpszFile[MAX_PATH] = { 0 };
UINT uFile = 0;
uFile = DragQueryFile(hDropInfo, 0xFFFFFFFF, NULL, NULL);
if (uFile != 0)
{
for (int i = 0; i < uFile; i++)
{
lpszFile[0] = '\0';
if (DragQueryFile(hDropInfo, i, lpszFile, MAX_PATH))
{
std::wstring directory;
std::wstring filename;
LVITEM lvi = { 0 };
lvi.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;
SplitPath(lpszFile, directory, filename);
lvi.iSubItem = 0;
lvi.pszText = LPSTR_TEXTCALLBACK;
lvi.cchTextMax = MAX_PATH;
int n = m_wndFileList.InsertItem(&lvi);
m_wndFileList.SetItemText(n, 0, filename.c_str());
m_wndFileList.SetItemText(n, 1, directory.c_str());
}
}
}
DragFinish(hDropInfo);
return;
CDialogEx::OnDropFiles(hDropInfo);
}

Resources