begin working on file mapping parsing

This commit is contained in:
mykola2312 2024-08-28 14:50:57 +03:00
parent db6a7cdde8
commit 774a555175
3 changed files with 78 additions and 0 deletions

View file

@ -25,6 +25,13 @@ void print_status(procstat_status_t* proc)
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
// test test
{
procstat_parse_maps(1, NULL, NULL);
return 0;
}
procstat_status_t* list = NULL; procstat_status_t* list = NULL;
size_t count = 0; size_t count = 0;

View file

@ -212,3 +212,53 @@ int procstat_find_active(procstat_status_t* list, size_t count, procstat_status_
} }
return 1; return 1;
} }
int procstat_parse_maps(pid_t pid, procstat_map_t** maps, size_t* count)
{
// open proc maps
char mapsPath[256] = {0};
snprintf(mapsPath, sizeof(mapsPath), "/proc/%d/maps", pid);
int fd = open(mapsPath, O_RDONLY);
if (fd < 0) return -1;
// now, block by block read contents
const unsigned blockSize = 512;
char* buffer = (char*)malloc(blockSize);
unsigned bufferOffset = 0;
while (1)
{
ssize_t rd = read(fd, buffer + bufferOffset, blockSize);
TRACE("rd %lu\n", rd);
if (rd == -1)
{
// error
free(buffer);
close(fd);
return -1;
}
else if (rd < blockSize)
{
// we've encountered last block, so set bufferOffset
// and terminate last line with zero byte
bufferOffset += rd;
buffer[bufferOffset] = '\0';
// finish reading
break;
}
else
{
// so rd is blockSize precisely, that means
// we need go further and read next block
bufferOffset += blockSize;
buffer = (char*)realloc(buffer, bufferOffset + blockSize);
}
}
// we got our maps buffer, now we can close file
close(fd);
TRACE("buffer: %s", buffer);
return 0;
}

View file

@ -1,6 +1,7 @@
#ifndef __PROCSTAT_H #ifndef __PROCSTAT_H
#define __PROCSTAT_H #define __PROCSTAT_H
#include <stdint.h>
#include <sys/types.h> #include <sys/types.h>
typedef enum { typedef enum {
@ -52,4 +53,24 @@ int procstat_is_considered_active(procstat_state_t state);
// find any active (running) thread and returns 0 and success, otherwise non zero // find any active (running) thread and returns 0 and success, otherwise non zero
int procstat_find_active(procstat_status_t* list, size_t count, procstat_status_t** thread); int procstat_find_active(procstat_status_t* list, size_t count, procstat_status_t** thread);
typedef struct {
uint64_t v_start;
uint64_t v_end;
int prot;
int flags;
uint64_t f_offset;
unsigned dev_major;
unsigned dev_minor;
uint64_t inode;
const char* path;
} procstat_map_t;
// parse process file mappings. return 0 on success and -1 on error
int procstat_parse_maps(pid_t pid, procstat_map_t** maps, size_t* count);
#endif #endif