Trying to print out useful data from Memory - c

void update_memblock(MEMBLOCK *mb)
{
static unsigned char tempbuf[128 * 1024];
SIZE_T bytes_left;
SIZE_T total_read;
SIZE_T bytes_to_read;
SIZE_T bytes_read;
bytes_left = mb->size;
total_read = 0;
while (bytes_left)
{
bytes_to_read = (bytes_left > sizeof(tempbuf)) ?
sizeof(tempbuf) : bytes_left;
ReadProcessMemory(mb->hProc, mb->addr + total_read,
tempbuf, bytes_to_read, &bytes_read);
if (bytes_read != bytes_to_read) break;
memcpy(mb->buffer + total_read, tempbuf, bytes_read);
bytes_left -= bytes_read;
total_read += bytes_read;
}
mb->size = total_read;
}
This is the current code I have, I am initially reading another process' memory using ReadProcessMemory. Now I have the temporary data stored in tempbuf. I am able to output the data from tempbuf in hexadecimal form. But I was planning to display it as shown in the picture, also another complexity I'm facing here is if bytes_left > sizeof(tempbuf) I'm only reading enough data equivalent to the size of tempbuf. How do I read more data as the array I defined can only support as much data?

If I understand correctly, your main question is about how to mimic the output from hex editors.
This can be broken up into 3 parts:
Printing the address
Printing the hex value of each byte
Printing the ASCII value for each byte
Printing an address in hex is easy. We can use %p to print the address of a pointer like this:
char* mem = malloc(99);
printf("%p\n", (void*)mem);
// output: 0xc17080
Next you can print the hex value of a byte using %02x on a char (1 byte). The 02 specifies a zero padded field width of 2. In this case it's just to make 0 print as 00 to make things line up and look pretty.
printf("%02x", mem[0]);
// output: 0A
Lastly, printing ASCII is the easiest of all... almost. We can use %c to print a byte for some ASCII values, but we don't want to print things like \nor \t. To solve this we can limit the use of %c to the character/symbol region of the ASCII table and print . for everything else.
char c = mem[0];
if ( ' ' <= c && c <= '~' ) {
printf("%c", c);
}
else {
printf(".");
}
//output: .
Now we just need to combine these all together. You can decide how many bytes you want to display per line and print "[address] [n hex bytes] [n ascii bytes]" and repeat until you've gone through the entire memory region. I've given a sample function below and you can run it for yourself here.
void display_mem(void* mem, int mem_size, int line_len) {
/*
mem - pointer to beggining of memory region to be printed
mem_size - number of bytes mem points to
line_len - number of bytyes to display per line
*/
unsigned char* data = mem;
int full_lines = mem_size / line_len;
unsigned char* addr = mem;
for (int linno = 0; linno < full_lines; linno++) {
// Print Address
printf("0x%x\t", addr);
// Print Hex
for (int i = 0; i < line_len; i++) {
printf(" %02x", data[linno*line_len + i]);
}
printf("\t");
// Print Ascii
for (int i = 0; i < line_len; i++) {
char c = data[linno*line_len + i];
if ( 32 < c && c < 125) {
printf(" %c", c);
}
else {
printf(" .");
}
}
printf("\n");
// Incremement addr by number of bytes printed
addr += line_len;
}
// Print any remaining bytes that couldn't make a full line
int remaining = mem_size % line_len;
if (remaining > 0) {
// Print Address
printf("0x%x\t", addr);
// Print Hex
for (int i = 0; i < remaining; i++) {
printf(" %02x", data[line_len*full_lines + i]);
}
for (int i = 0; i < line_len - remaining; i++) {
printf(" ");
}
printf("\t");
// Print Hex
for (int i = 0; i < remaining; i++) {
char c = data[line_len*full_lines + i];
if ( 32 < c && c < 125) {
printf(" %c", c);
}
else {
printf(" .");
}
}
printf("\n");
}
}
Sample output:
0x1e79010 74 65 73 74 79 2a 6e t e s t y * n
0x1e79017 0c 3e 24 45 5e 33 27 . > $ E ^ 3 '
0x1e7901e 18 51 09 2d 76 7e 4a . Q . - v . J
0x1e79025 12 53 0f 6e 0b 1a 6d . S . n . . m
0x1e7902c 31 6e 03 2b 01 2f 2c 1 n . + . / ,
0x1e79033 72 59 1c 76 18 38 3c r Y . v . 8 <
0x1e7903a 6e 6b 5b 00 36 64 25 n k [ . 6 d %
0x1e79041 2d 5c 6f 38 30 00 27 - \ o 8 0 . '
0x1e79048 33 12 15 5c 01 18 09 3 . . \ . . .
0x1e7904f 02 40 2d 6c 1a 41 63 . # - l . A c
0x1e79056 2b 72 18 1a 5e 74 12 + r . . ^ t .
0x1e7905d 0d 51 38 33 26 28 6b . Q 8 3 & ( k
0x1e79064 56 20 0b 0b 32 20 67 V . . . 2 . g
0x1e7906b 34 30 68 2e 70 0f 1c 4 0 h . p . .
0x1e79072 04 50 . P
As for the second part of your question, if you cannot increase the size of tempbuf then you are stuck dealing with that amount of memory at any moment in time.
However, if all you want to do is display the memory as described above you can display each section of memory in chunks. You can get a chunk of memory, display it, then get a new chunk, display the new chunk, repeat.
Something along the lines of
while (bytes_left) {
ReadProcessMemory(mb->hProc, mb->addr + total_read, tempbuf, bytes_to_read, &bytes_read);
// Get new chunk
memcpy(mb->buffer + total_read, tempbuf, bytes_read);
// Display chunk
display_mem(tempbuf, bytes_read);
bytes_left -= bytes_read;
}
You will need to do a little more work to check for errors and make everything look nice but hopefully that gives you a good idea of what could be done.

There is no way to store more data than you have space allocated. If you need to store more data, you will need to allocate more space somewhere (more RAM, a disk file, etc). Compression will allow you to store a bit more data in the space allocated, but you aren't going to gain all that much. For virtually unlimited storage, you are going to need to write to disk.
Alternatively, if you just need to display once and then can forget, read in 16 bytes, display the line, and then read the next 16 bytes into the same memory.

Related

How can I read a file integer by integer and put them into a 2D array?

I am trying to read all the numbers from a txt file and put them into a 2D array. I shouldn't worry about the size and stuff because I know it will be entered in 9 rows and in each row there will be 9 numbers. But if I run this code I get the following output.
int main() {
FILE *fpointer = fopen("filename.txt", "r");
int ch;
int arr[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
ch = fgetc(fpointer);
arr[i][j] = ch;
//printf("%d", ch);
}
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
fclose(fpointer);
return 0;
}
Output:
49 51 52 53 54 55 48 57 50
10 52 50 49 57 56 51 55 52
49 10 51 49 50 52 57 56 55
49 51 10 52 50 51 53 49 51
53 49 49 10 50 51 52 54 51
53 55 50 49 10 53 50 51 54
55 56 50 52 53 10 54 52 54
53 56 57 51 50 49 10 53 52
57 50 57 56 51 53 54 10 50
But the entered numbers are:
134567092
421983741
312498713
423513511
234635721
523678245
646589321
549298356
234698721
I assume it maybe have to do something with the fgets() function, but I tried to use getw(), but then I get even worse numbers. Maybe it tries to read the file in hexadecimals or something. Any ideas?
I'm not totally sure what behavior you were hoping for here, but I recommend decoding the ASCII digits before you store the numbers in your array, like this:
arr[i][j] = ch - '0';
Also, note that fgetc will return line-ending bytes like 10, because those are characters in your file too, even if they are not exactly visible. So when you receive one of those, you need to discard it and call fgetc again. Or you could insert an extra fgetc call at the end of each line (right after your j loop) to read those.
Looks like you need to convert the char from an ascii representation of the digit, into the actual digit. See also: Convert a character digit to the corresponding integer in C
So this part:
for(int j =0; j<9;j++){
ch = fgetc(fpointer);
arr[i][j] = ch;
//printf("%d", ch);
}
Would become this:
for(int j =0; j<9;j++){
ch = fgetc(fpointer);
if(isdigit(ch)) {
ch = ch - '0';
} else {
printf("error: Non-digit found!\n");
exit(1);
}
arr[i][j] = ch;
//printf("%d", ch);
}

How to get hex values from string?

I have a function with an input parameter "text" , which consists of a string containing unknown number of 2-character Hexadecimal numbers separated by space. I need to read them and put them in separate array indexes or read them in for loop and work with them one by one. Each of these values represents an encrypted char(the hex values are ascii values of the characters). How could i do that? I think i should use sscanf(); but i can't figure out how to do it.
char* bit_decrypt(const char* text){
int size=strlen(text)/3;
unsigned int hex[size];
char*ptr;
for(int i=0; i<size+1; i++){
hex[i] = strtoul(text, &ptr, 16);
printf("%x ",hex[i]);
}
return NULL;
}
output is: "80 80 80 80 80 80 80 80 80 80 80 80"
should be: "80 9c 95 95 96 11 bc 96 b9 95 9d 10"
You scan always the first value of text, because you forgot to move the input for strtoul right after the end of the previous scan. That's what the **end-parameter of strtoul is good for: it points to the character right after the last digit of a successful scan. Note: if nothing could have been read in, the end-pointer is equal the input pointer, and this indicates a "wrongly formated number" or the end of the string. See the following program illustrating this. Hope it helps.
int main() {
const char* input = "80 9c 95 95 96 11 bc 96 b9 95 9d 10";
const char *current = input;
char *end = NULL;
while (1) {
unsigned long val = strtoul(current, &end, 16);
if (current == end) // invalid input or end of string reached
break;
printf("val: %lX\n", val);
current = end;
}
}
This is also possible solution with the use of strchr, and strtoul(tmp,NULL,16);
In your solution remember that size_t arr_len = (len/3) + 1; since the last token is only 2 bytes long.
Input text tokens are converted to bytes and stored in char array:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char text[] = "80 9c 95 95 96 11 bc 96 b9 95 9d 10";
size_t len = strlen(text);
size_t arr_len = (len/3) + 1;
printf("len= %zu arr_len= %zu\n", len, arr_len);
printf("Text:\n%s\n", text);
char array[arr_len];
const char *p1 = text;
char tmp[3];
tmp[2] = 0;
printf("Parsing:\n");
for(size_t i=0; i< arr_len; i++)
{
p1 = strchr(p1,' ');
if(p1)
{
tmp[0] = *(p1-2);
tmp[1] = *(p1-1);
array[i]= (char)strtoul(tmp,NULL,16);
printf("%2x ", (unsigned char) array[i]);
p1++;
if(strlen(p1) == 2 ) // the last char
{
i++;
tmp[0] = *(p1);
tmp[1] = *(p1+1);
array[i]= (char)strtoul(tmp,NULL,16);
printf("%2x", (unsigned char) array[i]);
}
}
}
printf("\nArray content:\n");
for(size_t i=0; i< arr_len; i++)
{
printf("%2x ", (unsigned char) array[i]);
}
return 0;
}
Test:
len= 35 arr_len= 12
Text:
80 9c 95 95 96 11 bc 96 b9 95 9d 10
Parsing:
80 9c 95 95 96 11 bc 96 b9 95 9d 10
Array content:
80 9c 95 95 96 11 bc 96 b9 95 9d 10

How to print unsigned char data?

Im learning C so i have a little problem.
How to print: unsigned char *tlv_buffer = NULL;
In main function:
unsigned char *tlv_buffer = NULL;
int size = 1;
int len = 0;
int result;
tlv_buffer = BKS_MALLOC(size);
result = append_bertlv_data(&tlv_buffer, &size, &len, 0xDF04, 2,
"\x34\x56");
result = append_bertlv_data(&tlv_buffer, &size, &len, 0xDF81, 3, "ref");
BKS_TRACE("-------- success : %d --------- \n", result);
BKS_TRACE("======== %u =======", &tlv_buffer);
(I cannot see what happens in append_bertlv_data)
It should print df 04 02 34 56 df 81 03 72 65 66 ,
but it does not show like that.
My result is 3204447612
You can use the following:
for (int i = 0 ; i < strlen(tlv_buffer); i++)
printf("%02x ",*(tlv_buffer + i));
It will print each byte in hex.
edit:
use a space to separate and if you want the specific length bytes then specify the length instead of size. best is to use strlen.

Referencing a C pointer as array index twice

I have a C program in which I am trying to do a memory dump on a string of text. I want to print a certain amount of bytes and then go down to the next line and print some more. In my second for loop I am getting an error because I am writing on memory. In my second loop I want to print the exact same characters that I printed in the first loop, but as ascii instead of hex:
void dump(void *, int);
char * strcatp(char *, char *);
void
main()
{
char *str;
str = "this is an array of bytes, of which we will read some of them into our function";
print("len=%ld\n", strlen(str) +1);
dump(str, strlen(str) + 1);
}
void
dump(void *a, int len)
{
char *p;
int i, j, pos, rcount;
p = (char *) a;
rcount = 5;
pos = 0;
for(i=0;i<len;i++){
print("%p ", p[pos]);
if(pos + rcount > len)
rcount = len - pos;
if(pos == len)
return;
for(j = pos; j < pos + rcount; j++){
print("%02x ", p[j]);
}
print(" *");
for(j = pos; j < pos + rcount; j++){
if(isalpha(p[j]))
print("%s ", p[j]);
else
print(".");
//print("%s ", p[j]);
}
print("*\n");
pos += rcount;
}
}
Why do I keep writing on memory? I am not advancing the pointer that I know of.
It's important that the program compiles without warning and we got warning from your code:
$ gcc main.c
main.c: In function ‘dump’:
main.c:28:16: warning: format ‘%p’ expects argument of type ‘void *’, but argument 2 has type ‘int’ [-Wformat=]
printf("%p ", p[pos]);
^
main.c:40:24: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
printf("%s ", p[j]);
We should make sure that the types match when we call functions. If I fix your errors, it looks like your program is fine and there is no error message.
void dump(void *, int);
char * strcatp(char *, char *);
void
main()
{
char *str;
str = "this is an array of bytes, of which we will read some of them into our function";
printf("len=%ld\n", strlen(str) +1);
dump(str, (unsigned) strlen(str) + 1);
}
void
dump(void *a, int len)
{
char *p;
int i, j, pos, rcount;
p = (char *) a;
rcount = 5;
pos = 0;
for(i=0;i<len;i++){
printf("%s ", &p[pos]);
if(pos + rcount > len)
rcount = len - pos;
if(pos == len)
return;
for(j = pos; j < pos + rcount; j++){
printf("%02x ", p[j]);
}
printf(" *");
for(j = pos; j < pos + rcount; j++){
if(isalpha(p[j]))
printf("%s ", &p[j]);
else
printf(".");
//print("%s ", p[j]);
}
printf("*\n");
pos += rcount;
}
}
Output
$ ./a.out
len=80
this is an array of bytes, of which we will read some of them into our function 74 68 69 73 20 *this is an array of bytes, of which we will read some of them into our function his is an array of bytes, of which we will read some of them into our function is is an array of bytes, of which we will read some of them into our function s is an array of bytes, of which we will read some of them into our function .*
is an array of bytes, of which we will read some of them into our function 69 73 20 61 6e *is an array of bytes, of which we will read some of them into our function s an array of bytes, of which we will read some of them into our function .an array of bytes, of which we will read some of them into our function n array of bytes, of which we will read some of them into our function *
array of bytes, of which we will read some of them into our function 20 61 72 72 61 *.array of bytes, of which we will read some of them into our function rray of bytes, of which we will read some of them into our function ray of bytes, of which we will read some of them into our function ay of bytes, of which we will read some of them into our function *
y of bytes, of which we will read some of them into our function 79 20 6f 66 20 *y of bytes, of which we will read some of them into our function .of bytes, of which we will read some of them into our function f bytes, of which we will read some of them into our function .*
bytes, of which we will read some of them into our function 62 79 74 65 73 *bytes, of which we will read some of them into our function ytes, of which we will read some of them into our function tes, of which we will read some of them into our function es, of which we will read some of them into our function s, of which we will read some of them into our function *
, of which we will read some of them into our function 2c 20 6f 66 20 *..of which we will read some of them into our function f which we will read some of them into our function .*
which we will read some of them into our function 77 68 69 63 68 *which we will read some of them into our function hich we will read some of them into our function ich we will read some of them into our function ch we will read some of them into our function h we will read some of them into our function *
we will read some of them into our function 20 77 65 20 77 *.we will read some of them into our function e will read some of them into our function .will read some of them into our function *
ill read some of them into our function 69 6c 6c 20 72 *ill read some of them into our function ll read some of them into our function l read some of them into our function .read some of them into our function *
ead some of them into our function 65 61 64 20 73 *ead some of them into our function ad some of them into our function d some of them into our function .some of them into our function *
ome of them into our function 6f 6d 65 20 6f *ome of them into our function me of them into our function e of them into our function .of them into our function *
f them into our function 66 20 74 68 65 *f them into our function .them into our function hem into our function em into our function *
m into our function 6d 20 69 6e 74 *m into our function .into our function nto our function to our function *
o our function 6f 20 6f 75 72 *o our function .our function ur function r function *
function 20 66 75 6e 63 *.function unction nction ction *
tion 74 69 6f 6e 00 *tion ion on n .*
len=%ld
Now you don't have an error anymore. I hope this can help you: Always fix all compiler warning and often that will fix your errors. If you have a segfault and you are confused about it, you can track it with analysis tool like Valgrind.

C turning char arrays into int behaving weird

I have a much longer char array that I am turning into integers, but I cannot figure out why it behaves weird in some spots.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char x[60] = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08";
printf("%lu\n\n", strlen(x));
for ( int i = 0; i < strlen(x); i+=3 ) {
char num[2];
num[0] = (char)x[i];
num[1] = (char)x[i+1];
printf("%d, ", atoi(num));
}
}
The Output:
8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 500, 773, 916, 89,
Everything is great until.....500, 773, 916, 89...what is happening?
As you can see atoi wants a C-String: a null terminated array of character.
So, this
char num[2];
num[0] = (char)x[i];
num[1] = (char)x[i+1];
Have to be
char num[3] = {0};
num[0] = (char)x[i];
num[1] = (char)x[i+1];
num[2] = '\0'; // this could be avoided in your specific case
The need for a proper string with its null character has been posted by many.
Just wanted to add another coding idea: compound literal. (char[]) { x[i], x[i + 1], '\0' } to implement that.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char x[] = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08";
size_t len = strlen(x);
printf("%zu\n\n", len);
for (size_t i = 0; i < len; i += 3) {
printf("%d, ", atoi((char[] ) { x[i], x[i + 1], '\0' }));
}
}
Output
59
8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8,
Some other fixes made too.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char num[3]; // 3rd byte is the null character
num[3]='\0';
char x[60] = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08";
printf("%lu\n\n", strlen(x));
for ( int i = 0; i < strlen(x); i+=3 ) {
strncpy ( num, x+i, 2 ); // Copies two characters starting from x+i
// You get a null terminated string num here.
printf("%d, ", atoi(num));
}
printf("\n");
}
num[0] = (char)x[i];
num[1] = (char)x[i+1];
printf("%d, ", atoi(num)
This assumes that the number of digits in your input will always be 2(for which num should be declared as char num[3]. Do a dry run of your logic with a smaller input set, for eg:"01 50"
i=0
num[0] = *(num+0) = 0
num[1] = *(num+1) = <space>
num[2] = *(num + 2) = ????? Since this memory is not allocated for num
printf("%d, ", atoi("1<space>")) = 1 (atoi stops after looking at num[1] which is a non-digit character)
i = 3
num[0] = *(num+0) = 0
num[1] = *(num + 1) = 0
num[2] = *(num + 2) = ?????
printf("%d ", atoi("00<garbage>...")) // this is UB since atoi will definitely read memory at `(num + 2)` which is beyond the bounds of what the compiler allocated for it.
Try using sscanf to parse the input rather than relying on the number of digits. That would be much more cleaner and less prone to errors.
int main ()
{
char x[60] = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08";
const char *y = x;
char outputBuffer[10];
for(;sscanf(y, "%s", outputBuffer) > 0; y+=strlen(outputBuffer)) printf("%d, ", atoi(outputBuffer));
}
The answer to your question has already been provided, i.e. that a C string is by definition a NULL terminated char array. Without room for the NULL terminator, at best the results from a string passed to a string function cannot be trusted.
I am offering this just to highlight some additional ideas on reading a char array into int array, where the NULL terminator becomes almost a non-issue.
The following method includes simple string parsing and dynamic memory usage, where the string contents get read directly into int memory, bypassing any need for an intermediate string buffer, resulting in the ability to read any legal integer length from the string, and convert directly into int:
see inline comments for suggestions:
int main(void)
{
//leave array index blank, the compiler will size it for you
char x[] = "08 0223 22 97 382345 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 1000";
// ^
int size = sizeof(x)/sizeof(x[0]);//use sizeof macro to get number of elements in array
char *tok = NULL;
int i = 0;
int count=0;
for(i=0;i<size;i++)
{
if(x[i]==' ')count++;//get count to size int array
}
int *array = malloc((count+1)*sizeof(int));
if(array)
{
i=0;//reinitialize to 0 for use here
tok = strtok(x, " \n");
while(tok)//test after each parse before processing
{
if((i>0)&&(i%6==0))printf("\n");//newlines to format
array[i++] = atoi(tok);
printf("%6d, ", array[i]);
// ^ provide spacing in output
tok = strtok(NULL, " \n");
}
free(array);
}
return 0;
}

Resources