Why is the deleted file commit by default when using the commit command in libgit2? - libgit2

I delete the file: user git_remove_bypath and git_index_write
I use the index to commit, and don't commit the file by removed file,but the file by my removed also commit success.
int commit(void *repository, const char *file_name[], const unsigned int file, const char *message, void *payload)
{
int error = -1;
git_signature *signature = NULL;
/*git git; identify of any object*/
/*git commit_id; identify of any object*/
void* index = NULL;
void* tree = NULL;
do /* try catch */
{
const char *path = git_repository_path((git_repository*)repository);
/*get signature*/
error = git_signature_default(&signature, (git_repository*)repository);
/*get repository head*/
error = git_repository_head(&ref_head,(git_repository*)repository);
if (error == GIT_OK)
{
error = git_commit_lookup(&parent_commit, (git_repository*)repository, git_reference_target(ref_head));
}
else if (error != -9)
{
break;
}
/*get repository index*/
error = git_repository_index((git_index**)&index, (git_repository*)repository);
for(int i = 0; i < Count; ++i)
{
/*get statue*/
error = git_status_file(&flags, (git_repository *)repository, file_name[i]);
if(-3 == error || -5 == error)
{
continue;
}
if( GIT_STATUS_INDEX_DELETED & flags || GIT_STATUS_WT_DELETED & flags )
{
/*remove file*/
error = git_index_remove_bypath((git_index *)index, file_name[i]);
}
else
{
/*add file*/
error = git_index_add_bypath((git_index *)index, file_name[i]);
}
/*write disk*/
error = git_index_write((git_index*)index);
}
/* Get the index and write it to a tree */
error = git_index_write_tree(&git, (git_index*)index);
/* lookup tree */
error = git_tree_lookup((git_tree**)&tree, (git_repository *)repository, &git);
/* Do the commit*/
error = git_commit_create(&commit_id, (git_repository*)repository, "HEAD", signature, signature, NULL,
message, (git_tree *)tree, 1, parents);
}while(0);
}

Related

How to Get Remote Proc address of injected DLL into another process

This application is created
1) Console Application
2) InjectedDLL - DLL Project for inject into the process
1) the console application i have taken notepad.exe process id and inject my DLL into the notepad.
2) I have Created one exported method in the injected dll.
3) Now after injecting dll into notepad , i require the proc address of that exported method.
I have writted code here to get it but it's is not calling that methods and crash it.
I am attaching sample code this here. for run it only need to give full path of the dll.
const WCHAR INJECTED_DLL_FULL_PATH[] = L"FULL PATH OF DLL";
Only change this path, everything else will work.
I am unable to get the proc address of the injected dll.
anyone can help me on that.
/
Console Application code
/ DLLInjection.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Windows.h>
#include <stdlib.h>
#include "RemoteOperation.h"
#include <stdio.h>
#include <tchar.h>
#include <tlhelp32.h>
BOOL InjectDLL();
void EjectDLL();
HANDLE m_hRemoteThread;
HANDLE m_hProcess;
void* m_pLibRemoteAddress;
DWORD m_dwhLibModule;
BOOL m_bIsDLLInjected;
DWORD m_dwProcessID;
HWND m_hCaptureWnd;
const WCHAR INJECTED_DLL[] = L"InjectedDLL.dll";
const WCHAR INJECTED_DLL_FULL_PATH[] = L"FULL PATH OF DLL";
DWORD GetProcessIdEx(LPCWSTR szExeName);
typedef void (WINAPI *test)();
test _test = NULL;
int main()
{
InjectDLL();
HMODULE hDLLModule = GetRemoteModuleHandle(m_hProcess, INJECTED_DLL);
_test = (test)GetRemoteProcAddress(m_hProcess, hDLLModule, "test");
_test();
EjectDLL();
return 0;
}
DWORD GetProcessIdEx(LPCWSTR szExeName)
{
DWORD dwRet = 0;
DWORD dwCount = 0;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 pe = { 0 };
pe.dwSize = sizeof(PROCESSENTRY32);
BOOL bRet = Process32First(hSnapshot, &pe);
while (bRet)
{
OutputDebugString(pe.szExeFile);
OutputDebugString(L"\n");
if (!wcscmp(szExeName, pe.szExeFile))
{
dwCount++;
dwRet = pe.th32ProcessID;
break;
}
bRet = Process32Next(hSnapshot, &pe);
}
if (dwCount > 1)
dwRet = 0xFFFFFFFF;
CloseHandle(hSnapshot);
}
return dwRet;
}
BOOL InjectDLL()
{
m_hRemoteThread = NULL;
m_hProcess = NULL;
m_pLibRemoteAddress = NULL;
m_dwhLibModule = 0;
char chardllPath[MAX_PATH] = "\0";
wcstombs(chardllPath, INJECTED_DLL_FULL_PATH, MAX_PATH);
int Length = strlen(chardllPath);
HMODULE hKernel32 = ::GetModuleHandle(L"Kernel32");
LPVOID LoadLibraryPoniter = (LPVOID)GetProcAddress(hKernel32, "LoadLibraryA");
m_dwProcessID = GetProcessIdEx(L"notepad.exe");
m_hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION, FALSE, m_dwProcessID);
// 1. Allocate memory in the remote process for szLibPath
// 2. Write szLibPath to the allocated memory
m_pLibRemoteAddress = 0;
m_pLibRemoteAddress = ::VirtualAllocEx(m_hProcess, NULL, Length, MEM_COMMIT, PAGE_READWRITE);
if (m_pLibRemoteAddress == NULL)
{
CloseHandle(m_hProcess);
m_hProcess = NULL;
return false;
}
::WriteProcessMemory(m_hProcess, m_pLibRemoteAddress, (void*)chardllPath, Length, NULL);
// Load "dll" into the remote process
// (via CreateRemoteThread & LoadLibrary)
m_hRemoteThread = ::CreateRemoteThread(m_hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibraryPoniter, (LPVOID)m_pLibRemoteAddress, 0, NULL);
m_bIsDLLInjected = true;
::WaitForSingleObject(m_hRemoteThread, INFINITE);
// Get handle of loaded module
m_dwhLibModule = 0;
::GetExitCodeThread(m_hRemoteThread, &m_dwhLibModule);
::CloseHandle(m_hRemoteThread);
m_hRemoteThread = NULL;
::VirtualFreeEx(m_hProcess, m_pLibRemoteAddress, Length, MEM_RELEASE);
m_pLibRemoteAddress = NULL;
return true;
}
void EjectDLL()
{
if (m_hProcess && m_bIsDLLInjected)
{
HMODULE hKernel32 = ::GetModuleHandle(L"Kernel32");
LPVOID LoadFreeLibraryPoniter = (LPVOID)GetProcAddress(hKernel32, "FreeLibrary");
HMODULE hDLLModule = GetRemoteModuleHandle(m_hProcess, INJECTED_DLL);
if (hDLLModule)
{
HANDLE hThread = ::CreateRemoteThread(m_hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadFreeLibraryPoniter, (void*)hDLLModule, 0, NULL);
::WaitForSingleObject(hThread, INFINITE);
// Clean up
::CloseHandle(hThread);
}
}
if (m_hProcess)
{
CloseHandle(m_hProcess);
}
m_hProcess = NULL;
}
Remoteoperation.h
#pragma once
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#include <commctrl.h>
// C RunTime Header Files
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
#ifndef REM_OPS_H
#define REM_OPS_H
HMODULE WINAPI GetRemoteModuleHandle(HANDLE hProcess, LPCWSTR lpModuleName);
FARPROC WINAPI GetRemoteProcAddress(HANDLE hProcess, HMODULE hModule, LPCSTR lpProcName, UINT Ordinal = 0, BOOL UseOrdinal = FALSE);
BOOL RemoteLibraryFunction(HANDLE hProcess, LPCSTR lpModuleName, LPCSTR lpProcName, LPVOID lpParameters, SIZE_T dwParamSize, PVOID *ppReturn);
#endif //REM_OPS_H
// RemoteOperation.cpp
#include "stdafx.h"
/* RempteOps.cpp */
#include "stdafx.h" // SDKDDKVer.h, windows.h, stdlib.h, malloc.h, memory.h, tchar.h
#include "RemoteOperation.h" // Function prototypes
#include <string>
#include <windows.h>
#include <psapi.h>
using std::string;
//-----------------------------------------------------------------------------
HMODULE WINAPI GetRemoteModuleHandle(HANDLE hProcess, LPCWSTR lpModuleName)
{
HMODULE* ModuleArray = NULL;
DWORD ModuleArraySize = 200;
DWORD NumModules = 0;
WCHAR lpModuleNameCopy[MAX_PATH] = { 0 };
WCHAR ModuleNameBuffer[MAX_PATH] = { 0 };
/* Make sure we didn't get a NULL pointer for the module name */
if (lpModuleName == NULL)
goto GRMH_FAIL_JMP;
/* Convert lpModuleName to all lowercase so the comparison isn't case sensitive */
for (size_t i = 0; lpModuleName[i] != '\0'; ++i)
{
if (lpModuleName[i] >= 'A' && lpModuleName[i] <= 'Z')
lpModuleNameCopy[i] = lpModuleName[i] + 0x20; // 0x20 is the difference between uppercase and lowercase
else
lpModuleNameCopy[i] = lpModuleName[i];
lpModuleNameCopy[i + 1] = '\0';
}
/* Allocate memory to hold the module handles */
ModuleArray = new HMODULE[ModuleArraySize];
/* Check if the allocation failed */
if (ModuleArray == NULL)
goto GRMH_FAIL_JMP;
/* Get handles to all the modules in the target process */
if (!::EnumProcessModulesEx(hProcess, ModuleArray,
ModuleArraySize * sizeof(HMODULE), &NumModules, LIST_MODULES_ALL))
goto GRMH_FAIL_JMP;
/* We want the number of modules not the number of bytes */
NumModules /= sizeof(HMODULE);
/* Did we allocate enough memory for all the module handles? */
if (NumModules > ModuleArraySize)
{
delete[] ModuleArray; // Deallocate so we can try again
ModuleArray = NULL; // Set it to NULL se we can be sure if the next try fails
ModuleArray = new HMODULE[NumModules]; // Allocate the right amount of memory
/* Check if the allocation failed */
if (ModuleArray == NULL)
goto GRMH_FAIL_JMP;
ModuleArraySize = NumModules; // Update the size of the array
/* Get handles to all the modules in the target process */
if (!::EnumProcessModulesEx(hProcess, ModuleArray,
ModuleArraySize * sizeof(HMODULE), &NumModules, LIST_MODULES_ALL))
goto GRMH_FAIL_JMP;
/* We want the number of modules not the number of bytes */
NumModules /= sizeof(HMODULE);
}
/* Iterate through all the modules and see if the names match the one we are looking for */
for (DWORD i = 0; i <= NumModules; ++i)
{
/* Get the module's name */
::GetModuleBaseName(hProcess, ModuleArray[i],
ModuleNameBuffer, sizeof(ModuleNameBuffer));
/* Convert ModuleNameBuffer to all lowercase so the comparison isn't case sensitive */
for (size_t j = 0; ModuleNameBuffer[j] != '\0'; ++j)
{
if (ModuleNameBuffer[j] >= 'A' && ModuleNameBuffer[j] <= 'Z')
ModuleNameBuffer[j] += 0x20; // 0x20 is the difference between uppercase and lowercase
}
/* Does the name match? */
if (wcsstr(ModuleNameBuffer, lpModuleNameCopy) != NULL)
{
/* Make a temporary variable to hold return value*/
HMODULE TempReturn = ModuleArray[i];
/* Give back that memory */
delete[] ModuleArray;
/* Success */
return TempReturn;
}
/* Wrong module let's try the next... */
}
/* Uh Oh... */
GRMH_FAIL_JMP:
/* If we got to the point where we allocated memory we need to give it back */
if (ModuleArray != NULL)
delete[] ModuleArray;
/* Failure... */
return NULL;
}
//-----------------------------------------------------------------------------
FARPROC WINAPI GetRemoteProcAddress(HANDLE hProcess, HMODULE hModule, LPCSTR lpProcName, UINT Ordinal, BOOL UseOrdinal)
{
BOOL Is64Bit = FALSE;
MODULEINFO RemoteModuleInfo = { 0 };
UINT_PTR RemoteModuleBaseVA = 0;
IMAGE_DOS_HEADER DosHeader = { 0 };
DWORD Signature = 0;
IMAGE_FILE_HEADER FileHeader = { 0 };
IMAGE_OPTIONAL_HEADER64 OptHeader64 = { 0 };
IMAGE_OPTIONAL_HEADER32 OptHeader32 = { 0 };
IMAGE_DATA_DIRECTORY ExportDirectory = { 0 };
IMAGE_EXPORT_DIRECTORY ExportTable = { 0 };
UINT_PTR ExportFunctionTableVA = 0;
UINT_PTR ExportNameTableVA = 0;
UINT_PTR ExportOrdinalTableVA = 0;
DWORD* ExportFunctionTable = NULL;
DWORD* ExportNameTable = NULL;
WORD* ExportOrdinalTable = NULL;
/* Temporary variables not used until much later but easier
/* to define here than in all the the places they are used */
CHAR TempChar;
BOOL Done = FALSE;
/* Check to make sure we didn't get a NULL pointer for the name unless we are searching by ordinal */
if (lpProcName == NULL && !UseOrdinal)
goto GRPA_FAIL_JMP;
/* Get the base address of the remote module along with some other info we don't need */
if (!::GetModuleInformation(hProcess, hModule, &RemoteModuleInfo, sizeof(RemoteModuleInfo)))
goto GRPA_FAIL_JMP;
RemoteModuleBaseVA = (UINT_PTR)RemoteModuleInfo.lpBaseOfDll;
/* Read the DOS header and check it's magic number */
if (!::ReadProcessMemory(hProcess, (LPCVOID)RemoteModuleBaseVA, &DosHeader,
sizeof(DosHeader), NULL) || DosHeader.e_magic != IMAGE_DOS_SIGNATURE)
goto GRPA_FAIL_JMP;
/* Read and check the NT signature */
if (!::ReadProcessMemory(hProcess, (LPCVOID)(RemoteModuleBaseVA + DosHeader.e_lfanew),
&Signature, sizeof(Signature), NULL) || Signature != IMAGE_NT_SIGNATURE)
goto GRPA_FAIL_JMP;
/* Read the main header */
if (!::ReadProcessMemory(hProcess,
(LPCVOID)(RemoteModuleBaseVA + DosHeader.e_lfanew + sizeof(Signature)),
&FileHeader, sizeof(FileHeader), NULL))
goto GRPA_FAIL_JMP;
/* Which type of optional header is the right size? */
if (FileHeader.SizeOfOptionalHeader == sizeof(OptHeader64))
Is64Bit = TRUE;
else if (FileHeader.SizeOfOptionalHeader == sizeof(OptHeader32))
Is64Bit = FALSE;
else
goto GRPA_FAIL_JMP;
if (Is64Bit)
{
/* Read the optional header and check it's magic number */
if (!::ReadProcessMemory(hProcess,
(LPCVOID)(RemoteModuleBaseVA + DosHeader.e_lfanew + sizeof(Signature) + sizeof(FileHeader)),
&OptHeader64, FileHeader.SizeOfOptionalHeader, NULL)
|| OptHeader64.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC)
goto GRPA_FAIL_JMP;
}
else
{
/* Read the optional header and check it's magic number */
if (!::ReadProcessMemory(hProcess,
(LPCVOID)(RemoteModuleBaseVA + DosHeader.e_lfanew + sizeof(Signature) + sizeof(FileHeader)),
&OptHeader32, FileHeader.SizeOfOptionalHeader, NULL)
|| OptHeader32.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC)
goto GRPA_FAIL_JMP;
}
/* Make sure the remote module has an export directory and if it does save it's relative address and size */
if (Is64Bit && OptHeader64.NumberOfRvaAndSizes >= IMAGE_DIRECTORY_ENTRY_EXPORT + 1)
{
ExportDirectory.VirtualAddress = (OptHeader64.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]).VirtualAddress;
ExportDirectory.Size = (OptHeader64.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]).Size;
}
else if (OptHeader32.NumberOfRvaAndSizes >= IMAGE_DIRECTORY_ENTRY_EXPORT + 1)
{
ExportDirectory.VirtualAddress = (OptHeader32.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]).VirtualAddress;
ExportDirectory.Size = (OptHeader32.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]).Size;
}
else
goto GRPA_FAIL_JMP;
/* Read the main export table */
if (!::ReadProcessMemory(hProcess, (LPCVOID)(RemoteModuleBaseVA + ExportDirectory.VirtualAddress),
&ExportTable, sizeof(ExportTable), NULL))
goto GRPA_FAIL_JMP;
/* Save the absolute address of the tables so we don't need to keep adding the base address */
ExportFunctionTableVA = RemoteModuleBaseVA + ExportTable.AddressOfFunctions;
ExportNameTableVA = RemoteModuleBaseVA + ExportTable.AddressOfNames;
ExportOrdinalTableVA = RemoteModuleBaseVA + ExportTable.AddressOfNameOrdinals;
/* Allocate memory for our copy of the tables */
ExportFunctionTable = new DWORD[ExportTable.NumberOfFunctions];
ExportNameTable = new DWORD[ExportTable.NumberOfNames];
ExportOrdinalTable = new WORD[ExportTable.NumberOfNames];
/* Check if the allocation failed */
if (ExportFunctionTable == NULL || ExportNameTable == NULL || ExportOrdinalTable == NULL)
goto GRPA_FAIL_JMP;
/* Get a copy of the function table */
if (!::ReadProcessMemory(hProcess, (LPCVOID)ExportFunctionTableVA,
ExportFunctionTable, ExportTable.NumberOfFunctions * sizeof(DWORD), NULL))
goto GRPA_FAIL_JMP;
/* Get a copy of the name table */
if (!::ReadProcessMemory(hProcess, (LPCVOID)ExportNameTableVA,
ExportNameTable, ExportTable.NumberOfNames * sizeof(DWORD), NULL))
goto GRPA_FAIL_JMP;
/* Get a copy of the ordinal table */
if (!::ReadProcessMemory(hProcess, (LPCVOID)ExportOrdinalTableVA,
ExportOrdinalTable, ExportTable.NumberOfNames * sizeof(WORD), NULL))
goto GRPA_FAIL_JMP;
/* If we are searching for an ordinal we do that now */
if (UseOrdinal)
{
/* NOTE:
/* Microsoft's PE/COFF specification does NOT say we need to subtract the ordinal base
/* from our ordinal but it seems to always give the wrong function if we don't */
/* Make sure the ordinal is valid */
if (Ordinal < ExportTable.Base || (Ordinal - ExportTable.Base) >= ExportTable.NumberOfFunctions)
goto GRPA_FAIL_JMP;
UINT FunctionTableIndex = Ordinal - ExportTable.Base;
/* Check if the function is forwarded and if so get the real address*/
if (ExportFunctionTable[FunctionTableIndex] >= ExportDirectory.VirtualAddress &&
ExportFunctionTable[FunctionTableIndex] <= ExportDirectory.VirtualAddress + ExportDirectory.Size)
{
Done = FALSE;
string TempForwardString;
TempForwardString.clear(); // Empty the string so we can fill it with a new name
/* Get the forwarder string one character at a time because we don't know how long it is */
for (UINT_PTR i = 0; !Done; ++i)
{
/* Get next character */
if (!::ReadProcessMemory(hProcess,
(LPCVOID)(RemoteModuleBaseVA + ExportFunctionTable[FunctionTableIndex] + i),
&TempChar, sizeof(TempChar), NULL))
goto GRPA_FAIL_JMP;
TempForwardString.push_back(TempChar); // Add it to the string
/* If it's NUL we are done */
if (TempChar == (CHAR)'\0')
Done = TRUE;
}
/* Find the dot that seperates the module name and the function name/ordinal */
size_t Dot = TempForwardString.find('.');
if (Dot == string::npos)
goto GRPA_FAIL_JMP;
/* Temporary variables that hold parts of the forwarder string */
string RealModuleName, RealFunctionId;
RealModuleName = TempForwardString.substr(0, Dot - 1);
RealFunctionId = TempForwardString.substr(Dot + 1, string::npos);
WCHAR newModuleName[MAX_PATH] = L"\0";
swprintf_s(newModuleName, L"%s", RealModuleName.c_str());
HMODULE RealModule = GetRemoteModuleHandle(hProcess, newModuleName);
FARPROC TempReturn;// Make a temporary variable to hold return value
/* Figure out if the function was exported by name or by ordinal */
if (RealFunctionId.at(0) == '#') // Exported by ordinal
{
UINT RealOrdinal = 0;
RealFunctionId.erase(0, 1); // Remove '#' from string
/* My version of atoi() because I was too lazy to use the real one... */
for (size_t i = 0; i < RealFunctionId.size(); ++i)
{
if (RealFunctionId[i] >= '0' && RealFunctionId[i] <= '9')
{
RealOrdinal *= 10;
RealOrdinal += RealFunctionId[i] - '0';
}
else
break;
}
/* Recursively call this function to get return value */
TempReturn = GetRemoteProcAddress(hProcess, RealModule, NULL, RealOrdinal, TRUE);
}
else // Exported by name
{
/* Recursively call this function to get return value */
TempReturn = GetRemoteProcAddress(hProcess, RealModule, RealFunctionId.c_str(), 0, FALSE);
}
/* Give back that memory */
delete[] ExportFunctionTable;
delete[] ExportNameTable;
delete[] ExportOrdinalTable;
/* Success!!! */
return TempReturn;
}
else // Not Forwarded
{
/* Make a temporary variable to hold return value*/
FARPROC TempReturn = (FARPROC)(RemoteModuleBaseVA + ExportFunctionTable[FunctionTableIndex]);
/* Give back that memory */
delete[] ExportFunctionTable;
delete[] ExportNameTable;
delete[] ExportOrdinalTable;
/* Success!!! */
return TempReturn;
}
}
/* Iterate through all the names and see if they match the one we are looking for */
for (DWORD i = 0; i < ExportTable.NumberOfNames; ++i) {
string TempFunctionName;
Done = FALSE;// Reset for next name
TempFunctionName.clear(); // Empty the string so we can fill it with a new name
/* Get the function name one character at a time because we don't know how long it is */
for (UINT_PTR j = 0; !Done; ++j)
{
/* Get next character */
if (!::ReadProcessMemory(hProcess, (LPCVOID)(RemoteModuleBaseVA + ExportNameTable[i] + j),
&TempChar, sizeof(TempChar), NULL))
goto GRPA_FAIL_JMP;
TempFunctionName.push_back(TempChar); // Add it to the string
/* If it's NUL we are done */
if (TempChar == (CHAR)'\0')
Done = TRUE;
}
/* Does the name match? */
if (TempFunctionName.find(lpProcName) != string::npos)
{
/* NOTE:
/* Microsoft's PE/COFF specification says we need to subtract the ordinal base
/*from the value in the ordinal table but that seems to always give the wrong function */
/* Check if the function is forwarded and if so get the real address*/
if (ExportFunctionTable[ExportOrdinalTable[i]] >= ExportDirectory.VirtualAddress &&
ExportFunctionTable[ExportOrdinalTable[i]] <= ExportDirectory.VirtualAddress + ExportDirectory.Size)
{
Done = FALSE;
string TempForwardString;
TempForwardString.clear(); // Empty the string so we can fill it with a new name
/* Get the forwarder string one character at a time because we don't know how long it is */
for (UINT_PTR j = 0; !Done; ++j)
{
/* Get next character */
if (!::ReadProcessMemory(hProcess,
(LPCVOID)(RemoteModuleBaseVA + ExportFunctionTable[i] + j),
&TempChar, sizeof(TempChar), NULL))
goto GRPA_FAIL_JMP;
TempForwardString.push_back(TempChar); // Add it to the string
/* If it's NUL we are done */
if (TempChar == (CHAR)'\0')
Done = TRUE;
}
/* Find the dot that seperates the module name and the function name/ordinal */
size_t Dot = TempForwardString.find('.');
if (Dot == string::npos)
goto GRPA_FAIL_JMP;
/* Temporary variables that hold parts of the forwarder string */
string RealModuleName, RealFunctionId;
RealModuleName = TempForwardString.substr(0, Dot);
RealFunctionId = TempForwardString.substr(Dot + 1, string::npos);
WCHAR newModuleName[MAX_PATH] = L"\0";
swprintf_s(newModuleName, L"%s", RealModuleName.c_str());
HMODULE RealModule = GetRemoteModuleHandle(hProcess, newModuleName);
FARPROC TempReturn;// Make a temporary variable to hold return value
/* Figure out if the function was exported by name or by ordinal */
if (RealFunctionId.at(0) == '#') // Exported by ordinal
{
UINT RealOrdinal = 0;
RealFunctionId.erase(0, 1); // Remove '#' from string
/* My version of atoi() because I was to lazy to use the real one... */
for (size_t i = 0; i < RealFunctionId.size(); ++i)
{
if (RealFunctionId[i] >= '0' && RealFunctionId[i] <= '9')
{
RealOrdinal *= 10;
RealOrdinal += RealFunctionId[i] - '0';
}
else
break;
}
/* Recursively call this function to get return value */
TempReturn = GetRemoteProcAddress(hProcess, RealModule, NULL, RealOrdinal, TRUE);
}
else // Exported by name
{
/* Recursively call this function to get return value */
TempReturn = GetRemoteProcAddress(hProcess, RealModule, RealFunctionId.c_str(), 0, FALSE);
}
/* Give back that memory */
delete[] ExportFunctionTable;
delete[] ExportNameTable;
delete[] ExportOrdinalTable;
/* Success!!! */
return TempReturn;
}
else // Not Forwarded
{
/* Make a temporary variable to hold return value*/
FARPROC TempReturn;
/* NOTE:
/* Microsoft's PE/COFF specification says we need to subtract the ordinal base
/*from the value in the ordinal table but that seems to always give the wrong function */
//TempReturn = (FARPROC)(RemoteModuleBaseVA + ExportFunctionTable[ExportOrdinalTable[i] - ExportTable.Base]);
/* So we do it this way instead */
TempReturn = (FARPROC)(RemoteModuleBaseVA + ExportFunctionTable[ExportOrdinalTable[i]]);
/* Give back that memory */
delete[] ExportFunctionTable;
delete[] ExportNameTable;
delete[] ExportOrdinalTable;
/* Success!!! */
return TempReturn;
}
}
/* Wrong function let's try the next... */
}
/* Uh Oh... */
GRPA_FAIL_JMP:
/* If we got to the point where we allocated memory we need to give it back */
if (ExportFunctionTable != NULL)
delete[] ExportFunctionTable;
if (ExportNameTable != NULL)
delete[] ExportNameTable;
if (ExportOrdinalTable != NULL)
delete[] ExportOrdinalTable;
/* Falure... */
return NULL;
}
BOOL RemoteLibraryFunction(HANDLE hProcess, LPCSTR lpModuleName, LPCSTR lpProcName, LPVOID lpParameters, SIZE_T dwParamSize, PVOID *ppReturn)
{
LPVOID lpRemoteParams = NULL;
LPVOID lpFunctionAddress = GetProcAddress(GetModuleHandleA(lpModuleName), lpProcName);
if (!lpFunctionAddress) lpFunctionAddress = GetProcAddress(LoadLibraryA(lpModuleName), lpProcName);
if (!lpFunctionAddress) goto ErrorHandler;
if (lpParameters)
{
lpRemoteParams = VirtualAllocEx(hProcess, NULL, dwParamSize, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (!lpRemoteParams) goto ErrorHandler;
SIZE_T dwBytesWritten = 0;
BOOL result = WriteProcessMemory(hProcess, lpRemoteParams, lpParameters, dwParamSize, &dwBytesWritten);
if (!result || dwBytesWritten < 1) goto ErrorHandler;
}
HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)lpFunctionAddress, lpRemoteParams, NULL, NULL);
if (!hThread) goto ErrorHandler;
DWORD dwOut = 0;
while (GetExitCodeThread(hThread, &dwOut)) {
if (dwOut != STILL_ACTIVE) {
*ppReturn = (PVOID)dwOut;
break;
}
}
return TRUE;
ErrorHandler:
if (lpRemoteParams)
VirtualFreeEx(hProcess, lpRemoteParams, dwParamSize, MEM_RELEASE);
return FALSE;
}
Injectdl DLL Expoerted methods
#define EXPORT __declspec (dllexport)
EXPORT void test();
EXPORT void test()
{
::MessageBox(NULL, L"test", L"", MB_OK);
}
DLL Main cpp
// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
::MessageBox(NULL, L"DLL Injected", L"", MB_OK);
}
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
def file
LIBRARY InjectedDLL
EXPORTS
test #1
That is a lot of code to debug. What you're having a problem with is writing an external version of GetProcAddress which walks the export table. Instead of taking the time to debug your code I will supply a code which I know works. It is not my own code but I have used it before, the original author is iPower.
#define ReCa reinterpret_cast
uintptr_t GetProcAddressEx(HANDLE hProcess, DWORD pid, const char* module, const char* function)
{
if (!module || !function || !pid || !hProcess)
return 0;
uintptr_t moduleBase = GetModuleBaseEx(module, pid); //toolhelp32snapshot method
if (!moduleBase)
return 0;
IMAGE_DOS_HEADER Image_Dos_Header = { 0 };
if (!ReadProcessMemory(hProcess, ReCa<LPCVOID>(moduleBase), &Image_Dos_Header, sizeof(IMAGE_DOS_HEADER), nullptr))
return 0;
if (Image_Dos_Header.e_magic != IMAGE_DOS_SIGNATURE)
return 0;
IMAGE_NT_HEADERS Image_Nt_Headers = { 0 };
if (!ReadProcessMemory(hProcess, ReCa<LPCVOID>(moduleBase + Image_Dos_Header.e_lfanew), &Image_Nt_Headers, sizeof(IMAGE_NT_HEADERS), nullptr))
return 0;
if (Image_Nt_Headers.Signature != IMAGE_NT_SIGNATURE)
return 0;
IMAGE_EXPORT_DIRECTORY Image_Export_Directory = { 0 };
uintptr_t img_exp_dir_rva = 0;
if (!(img_exp_dir_rva = Image_Nt_Headers.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress))
return 0;
if (!ReadProcessMemory(hProcess, ReCa<LPCVOID>(moduleBase + img_exp_dir_rva), &Image_Export_Directory, sizeof(IMAGE_EXPORT_DIRECTORY), nullptr))
return 0;
uintptr_t EAT = moduleBase + Image_Export_Directory.AddressOfFunctions;
uintptr_t ENT = moduleBase + Image_Export_Directory.AddressOfNames;
uintptr_t EOT = moduleBase + Image_Export_Directory.AddressOfNameOrdinals;
WORD ordinal = 0;
SIZE_T len_buf = strlen(function) + 1;
char* temp_buf = new char[len_buf];
for (size_t i = 0; i < Image_Export_Directory.NumberOfNames; i++)
{
uintptr_t tempRvaString = 0;
if (!ReadProcessMemory(hProcess, ReCa<LPCVOID>(ENT + (i * sizeof(uintptr_t))), &tempRvaString, sizeof(uintptr_t), nullptr))
return 0;
if (!ReadProcessMemory(hProcess, ReCa<LPCVOID>(moduleBase + tempRvaString), temp_buf, len_buf, nullptr))
return 0;
if (!lstrcmpi(function, temp_buf))
{
if (!ReadProcessMemory(hProcess, ReCa<LPCVOID>(EOT + (i * sizeof(WORD))), &ordinal, sizeof(WORD), nullptr))
return 0;
uintptr_t temp_rva_func = 0;
if (!ReadProcessMemory(hProcess, ReCa<LPCVOID>(EAT + (ordinal * sizeof(uintptr_t))), &temp_rva_func, sizeof(uintptr_t), nullptr))
return 0;
delete[] temp_buf;
return moduleBase + temp_rva_func;
}
}
delete[] temp_buf;
return 0;
}

Error: Failed to read audio(pocketsphinx + espeak)

I am trying to recognize voices from microphone by pocketsphinx and pass it through espeak to say what it recognized in real-time/continuous speech(I mean user says a word/sentence, pocketsphinx will recognize it and collects it inside char* hyp, then passes the hyp to speech() function that uses espeak to say what is inside the hyp. But I don't know why do I get
Failed to read audio
In this part of the code:
if ((k = ad_read(ad, adbuf, 2048)) < 0)
E_FATAL("Failed to read audio\n");
This is the complete code:
static ps_decoder_t *ps;
static cmd_ln_t *config;
static FILE *rawfd;
ad_rec_t *ad;
char *hyp;
espeak_POSITION_TYPE position_type;
espeak_AUDIO_OUTPUT output;
char *path=NULL;
int Buflength = 2048, Options=0;
void* user_data;
char Voice[] = {"English"};
unsigned int Size,position=0, end_position=0, flags=espeakCHARS_AUTO, *unique_identifier;
t_espeak_callback *SynthCallback;
espeak_PARAMETER Parm;
static void after_speech()
{
espeak_Synth( hyp, Size, position, position_type, end_position, flags,unique_identifier, user_data );
espeak_Synchronize( );
ad_start_rec(ad);
}
int receive_espeak_events(short *wav, int numsamples, espeak_EVENT *event)
{
while (event->type != espeakEVENT_LIST_TERMINATED)
{
if (event->type == espeakEVENT_MSG_TERMINATED)
{
after_speech();
}
++event;
}
return 0;
}
static void initFuncs()
{
espeak_Initialize(output, Buflength, path, AUDIO_OUTPUT_PLAYBACK ); //AUDIO_OUTPUT_SYNCHRONOUS ); //Options );
espeak_SetVoiceByName(Voice);
}
static void sleep_msec(int32 ms)
{
struct timeval tmo;
tmo.tv_sec = 0;
tmo.tv_usec = ms * 1000;
select(0, NULL, NULL, NULL, &tmo);
}
static void speech(char* hyp)
{
Size = strlen(hyp)+1;
espeak_SetSynthCallback(receive_espeak_events);
}
static void recognize_from_microphone()
{
int16 adbuf[2048];
uint8 utt_started, in_speech;
int32 k;
if ((ad = ad_open_dev(cmd_ln_str_r(config, "-adcdev"),(int) cmd_ln_float32_r(config,"-samprate"))) == NULL)
E_FATAL("Failed to open audio device\n");
if (ad_start_rec(ad) < 0)
E_FATAL("Failed to start recording\n");
if (ps_start_utt(ps) < 0)
E_FATAL("Failed to start utterance\n");
utt_started = FALSE;
E_INFO("Ready....\n");
for (;;)
{
if ((k = ad_read(ad, adbuf, 2048)) < 0)
E_FATAL("Failed to read audio\n");
ps_process_raw(ps, adbuf, k, FALSE, FALSE);
in_speech = ps_get_in_speech(ps);
if (in_speech && !utt_started)
{
utt_started = TRUE;
E_INFO("Listening...\n");
}
if (!in_speech && utt_started)
{
ps_end_utt(ps);
hyp = (char*)ps_get_hyp(ps, NULL );
if (hyp != NULL)
{
ad_stop_rec(ad);
speech(hyp);
printf("%s\n",hyp);
fflush(stdout);
// sleep_msec(3000);
}
if (ps_start_utt(ps) < 0)
E_FATAL("Failed to start utterance\n");
utt_started = FALSE;
E_INFO("Ready....\n");
}
}//for loop
ad_close(ad);
}
int main(int argc, char *argv[])
{
initFuncs();
config = cmd_ln_init(NULL, ps_args(), TRUE,
"-hmm", "/home/m/myrobot3/robot/model_parameters/robot.cd_cont_1000",
"-lm","/home/m/myrobot3/robot/etc/robot.lm.bin",
"-dict", "/home/m/myrobot3/robot/etc/robot.dic",
NULL);
ps = ps_init(config);
recognize_from_microphone();
ps_free(ps);
cmd_ln_free_r(config);
return 0;
}
NOTE: I used espeak_SetSynthCallback(receive_espeak_events); because I must pause the pocketsphinx's listening to new voices, until the espeak ends speaking of the previous recognized voice. So I tried to ad_stop_rec(ad); after finding a new hyp() inside the for(;;) loop, then tried to ad_start_rec(ad); when espeakEVENT_MSG_TERMINATED happened inside the receive_espeak_events callback.

Why does my structure assignment fail in C language?

Why does my structure assignment fail in C language?
I have a class A: define a structure
typedef struct{
int sockfd;
on_av_frame_cb av_frame_cb;
on_av_frame_cb rtp_cb;
on_error_cb error_cb;
uint8_t *p_buf;
uint8_t *v_buf;
uint8_t *a_buf;
int rtp_flag;
}udp_client_t;
Then I call in class B:
static udp_client_t client;
int jldv_create_client(int src_port,int port ,const char *dst_ip){
udp_client_t *udpClient = &client;
assert(udpClient != NULL);
const char *c_ip = dst_ip;
memset(udpClient, 0, sizeof(udp_client_t));
int ret = create_client(src_port, port, c_ip, &udpClient);
if (ret != 0) {
goto err_output;
}
udpClient->av_frame_cb = (on_av_frame_cb )onVideoFrame;
udpClient->error_cb = on_error;
if (rtp_create(&udpClient) < 0) { ///above problem
goto err_output;
}
printf("rtp_client:%d \n",udpClient->rtp_flag);
return 0;
err_output:
destroy_client(udpClient);
return -1;
}
In the above problem, I used the C class method:
int rtp_create(udp_client_t **data)
{
logi("%s", __func__);
udp_client_t *udpClient = *data;
if(udpClient)
{
udpClient->rtp_flag = 1;
memset(&rtp_cxt, 0, sizeof(rtp_context_t));
int ret = init_server();
if (ret < 0)
{
return -1;
}
rtp_cxt.nalu = alloc_nalu(MAX_FRAME_SIZE);//
if (!rtp_cxt.nalu)
{
loge("alloc nalu failed");
return -2;
}
}
else
{
loge("%s: data is null", __func__);
return -3;
}
printf("udpClient after==>%d \n",udpClient->rtp_flag);
return 0;
}
However, the result of printing is:
udpClient after==>1
rtp_client:0
supplement:
int create_client(int src_port, int dst_port, const char *dst_ip, udp_client_t **client)
{
udp_client_t *udpClient = *client;
assert(udpClient != NULL);
memset(udpClient, 0, sizeof(udp_client_t));
printf("create_client:%p\n",udpClient);
udpClient->port = src_port;
if (pthread_create(&udpClient->recv_tid, NULL, udp_receiver_runnable, (void *) udpClient) != 0)
{
loge("Failed to start new thread");
goto err_output;
}
return 0;
err_output:
memset(udpClient, 0, sizeof(udp_client_t));
return -10;
}
Why is that? Did i use something wrong?

my __init is called but not getting call for probe

I am enabling the pinctrl driver in the raspberry linux and I tried something and enabled it.
But what happened is, the __init is calling but the probe is not calling by the linux.
My code is
this is the probe
static int bcm2835_pinctrl_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct device_node *np = dev->of_node;
struct bcm2835_pinctrl *pc;
struct resource iomem;
int err, i;
BUILD_BUG_ON(ARRAY_SIZE(bcm2835_gpio_pins) != BCM2835_NUM_GPIOS);
BUILD_BUG_ON(ARRAY_SIZE(bcm2835_gpio_groups) != BCM2835_NUM_GPIOS);
pc = devm_kzalloc(dev, sizeof(*pc), GFP_KERNEL);
if (!pc)
return -ENOMEM;
platform_set_drvdata(pdev, pc);
pc->dev = dev;
err = of_address_to_resource(np, 0, &iomem);
if (err) {
dev_err(dev, "could not get IO memory\n");
return err;
}
pc->base = devm_ioremap_resource(dev, &iomem);
if (IS_ERR(pc->base))
return PTR_ERR(pc->base);
pc->gpio_chip = bcm2835_gpio_chip;
pc->gpio_chip.dev = dev;
pc->irq_domain = irq_domain_add_linear(np, BCM2835_NUM_GPIOS,
&irq_domain_simple_ops, NULL);
if (!pc->irq_domain) {
dev_err(dev, "could not create IRQ domain\n");
return -ENOMEM;
}
for (i = 0; i < BCM2835_NUM_GPIOS; i++) {
int irq = irq_create_mapping(pc->irq_domain, i);
irq_set_lockdep_class(irq, &gpio_lock_class);
irq_set_chip_and_handler(irq, &bcm2835_gpio_irq_chip,
handle_simple_irq);
irq_set_chip_data(irq, pc);
set_irq_flags(irq, IRQF_VALID);
}
for (i = 0; i < BCM2835_NUM_BANKS; i++) {
unsigned long events;
unsigned offset;
int len;
char *name;
/* clear event detection flags */
bcm2835_gpio_wr(pc, GPREN0 + i * 4, 0);
bcm2835_gpio_wr(pc, GPFEN0 + i * 4, 0);
bcm2835_gpio_wr(pc, GPHEN0 + i * 4, 0);
bcm2835_gpio_wr(pc, GPLEN0 + i * 4, 0);
bcm2835_gpio_wr(pc, GPAREN0 + i * 4, 0);
bcm2835_gpio_wr(pc, GPAFEN0 + i * 4, 0);
/* clear all the events */
events = bcm2835_gpio_rd(pc, GPEDS0 + i * 4);
for_each_set_bit(offset, &events, 32)
bcm2835_gpio_wr(pc, GPEDS0 + i * 4, BIT(offset));
pc->irq[i] = irq_of_parse_and_map(np, i);
pc->irq_data[i].pc = pc;
pc->irq_data[i].bank = i;
spin_lock_init(&pc->irq_lock[i]);
len = strlen(dev_name(pc->dev)) + 16;
name = devm_kzalloc(pc->dev, len, GFP_KERNEL);
if (!name)
return -ENOMEM;
snprintf(name, len, "%s:bank%d", dev_name(pc->dev), i);
err = devm_request_irq(dev, pc->irq[i],
bcm2835_gpio_irq_handler, IRQF_SHARED,
name, &pc->irq_data[i]);
if (err) {
dev_err(dev, "unable to request IRQ %d\n", pc->irq[i]);
return err;
}
}
err = gpiochip_add(&pc->gpio_chip);
if (err) {
dev_err(dev, "could not add GPIO chip\n");
return err;
}
pc->pctl_dev = pinctrl_register(&bcm2835_pinctrl_desc, dev, pc);
if (!pc->pctl_dev) {
err = gpiochip_remove(&pc->gpio_chip);
return err;
}
pc->gpio_range = bcm2835_pinctrl_gpio_range;
pc->gpio_range.base = pc->gpio_chip.base;
pc->gpio_range.gc = &pc->gpio_chip;
pinctrl_add_gpio_range(pc->pctl_dev, &pc->gpio_range);
return 0;
}
static struct of_device_id bcm2835_pinctrl_match[] = {
{ .compatible = "brcm,bcm2835-gpio" },
{}
};
MODULE_DEVICE_TABLE(of, bcm2835_pinctrl_match);
static struct platform_driver bcm2835_pinctrl_driver = {
.probe = bcm2835_pinctrl_probe,
.remove = bcm2835_pinctrl_remove,
.driver = {
.name = MODULE_NAME,
.owner = THIS_MODULE,
.of_match_table = bcm2835_pinctrl_match,
},
};
static int __init bcm2835_pinctrl_init(void)
{
return platform_driver_register(&bcm2835_pinctrl_driver);
}
static void __exit bcm2835_pinctrl_exit(void)
{
platform_driver_unregister(&bcm2835_pinctrl_driver);
}
module_init(bcm2835_pinctrl_init);
module_exit(bcm2835_pinctrl_exit);
MODULE_AUTHOR("Chris Boot, Simon Arlott, Stephen Warren");
MODULE_DESCRIPTION("BCM2835 Pin control driver");
MODULE_LICENSE("GPL");
Can anyone help me out this?
I am not getting where i did wrong and why the probe is not calling?
The solution for this problem is that i forgot to add the driver structure in the board file.
After adding that i am getting call to the probe

WMV Converter Fails FFMpeg

I just cann't seem to get the FFMpeg working with using the library. Everytime I try to convert asf file to wmv. I get the following issue on run time:
[wmv1 # 0x81ee000]error, slice code was 2
[wmv1 # 0x81ee000]header damaged
This my code:
static void audio_decode_example(const char *outfilename, const char *filename)
{
AVCodec *codec;
AVCodecContext *c= NULL;
int out_size, len, in_size;
FILE *f, *outfile;
uint8_t *outbuf;
uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
AVPacket avpkt;
av_init_packet(&avpkt);
printf("Audio decoding\n");
/* find the mpeg audio decoder */
codec = avcodec_find_decoder(CODEC_ID_WMV1);
if (!codec) {
fprintf(stderr, "codec not found\n");
return;
}
c= avcodec_alloc_context2(CODEC_TYPE_AUDIO);
/* open it */
if (avcodec_open(c, codec) < 0) {
fprintf(stderr, "could not open codec\n");
return;
}
outbuf = malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "could not open %s\n", filename);
return;
}
outfile = fopen(outfilename, "wb");
if (!outfile) {
av_free(c);
return;
}
/* decode until eof */
avpkt.data = inbuf;
len = avpkt.size = fread(inbuf, 1, INBUF_SIZE, f);
NSLog(#"%d", avpkt.size);
while (avpkt.size > 0) {
out_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
len = avcodec_decode_audio2(c, (short *)outbuf, &out_size, inbuf,len);// avpkt.size);
NSLog(#"%d", len);
if (len < 0) {
fprintf(stderr, "Error while decoding\n");
fclose(outfile);
return;
}
if (out_size > 0) {
/* if a frame has been decoded, output it */
fwrite(outbuf, 1, out_size, outfile);
}
avpkt.size -= len;
avpkt.data += len;
if (avpkt.size < AUDIO_REFILL_THRESH) {
/* Refill the input buffer, to avoid trying to decode
* incomplete frames. Instead of this, one could also use
* a parser, or use a proper container format through
* libavformat. */
memmove(inbuf, avpkt.data, avpkt.size);
avpkt.data = inbuf;
len = fread(avpkt.data + avpkt.size, 1,
INBUF_SIZE - avpkt.size, f);
if (len > 0)
avpkt.size += len;
}
}
fclose(outfile);
fclose(f);
free(outbuf);
avcodec_close(c);
av_free(c);
}
I have try the command line utilities and it successfully convert the file. Any help would be helpfully. thanks
Make the mistake of opening the wrong file