Skip to content

Commit

Permalink
replaced _LM_OpenFileBuf with regex/getline on _LM_GetParentIdEx
Browse files Browse the repository at this point in the history
  • Loading branch information
rdbo committed Dec 23, 2022
1 parent bb91547 commit 1ec4676
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 14 deletions.
1 change: 0 additions & 1 deletion CMakeLists.txt
Expand Up @@ -39,7 +39,6 @@ set_target_properties(LIEF PROPERTIES IMPORTED_LOCATION ${LIEF_IMPORT_DIR}/libLI
set(LIBMEM_DIR "${PROJECT_SOURCE_DIR}/libmem")
set(LIBMEM_INC "${LIBMEM_DIR}/include")
file(GLOB_RECURSE LIBMEM_SRC "${LIBMEM_DIR}/src/*.c" "${LIBMEM_DIR}/src/*.cpp")
message(STATUS "Source: ${LIBMEM_SRC}")
set(LIBMEM_DEPS capstone keystone LIEF stdc++ m)

if(NOT MSVC)
Expand Down
3 changes: 3 additions & 0 deletions libmem/include/libmem.h
Expand Up @@ -142,6 +142,9 @@
#define LM_MEMCPY memcpy
#define LM_MEMSET memset
#define LM_ASSERT assert
#define LM_FOPEN fopen
#define LM_FCLOSE fclose
#define LM_GETLINE getline /* TODO: Add wchar_t variant */

#define LM_CSTR(str) str
#define LM_CSTRCMP strcmp
Expand Down
1 change: 0 additions & 1 deletion libmem/src/helpers.c
Expand Up @@ -49,4 +49,3 @@ _LM_CloseFileBuf(lm_tchar_t **pfilebuf)
}
}
#endif

37 changes: 25 additions & 12 deletions libmem/src/process.c
Expand Up @@ -2,6 +2,7 @@
#if LM_OS != LM_OS_WIN
# include <dirent.h>
# include <sys/utsname.h>
# include <regex.h>
#endif

#if LM_OS == LM_OS_WIN
Expand Down Expand Up @@ -260,26 +261,38 @@ _LM_GetParentIdEx(lm_pid_t pid)
LM_PRIVATE lm_pid_t
_LM_GetParentIdEx(lm_pid_t pid)
{
lm_pid_t ppid = LM_PID_BAD;
lm_tchar_t *status_buf;
lm_tchar_t status_path[LM_ARRLEN(LM_PROCFS) + 64] = { 0 };
lm_tchar_t *ptr;
lm_pid_t ppid = LM_PID_BAD;
lm_tchar_t status_path[LM_PATH_MAX] = { 0 };
FILE *status_file;
lm_tchar_t *status_line = NULL;
regex_t regex;
size_t len;
regmatch_t matches[2];

LM_SNPRINTF(status_path, LM_ARRLEN(status_path),
LM_STR("%s/%d/status"), LM_PROCFS, pid);

if (!_LM_OpenFileBuf(status_path, &status_buf))

status_file = LM_FOPEN(status_path, "r");
if (!status_file)
return ppid;

ptr = LM_STRSTR(status_buf, LM_STR("\nPPid:\t"));
if (regcomp(&regex, "^PPid:[[:blank:]]+([0-9]+)$", REG_ICASE | REG_EXTENDED))
goto CLOSE_EXIT;

if (ptr) {
ptr = LM_STRCHR(ptr, LM_STR('\t'));
ptr = &ptr[1];
ppid = (lm_pid_t)LM_ATOI(ptr);
while (LM_GETLINE(&status_line, &len, status_file) > 0) {
if (regexec(&regex, status_line, LM_ARRLEN(matches), matches, 0))
continue;

status_line[matches[1].rm_eo] = '\x00';
ppid = LM_ATOI(&status_line[matches[1].rm_so]);
break;
}

_LM_CloseFileBuf(&status_buf);
regfree(&regex);
LM_FREE(status_line);
CLOSE_EXIT:
LM_FCLOSE(status_file);

return ppid;
}
#endif
Expand Down

0 comments on commit 1ec4676

Please sign in to comment.