问题
Whenever isstatic32 is called, it will return STATIC even though the program is dynamically compiled. I have no idea what to do. I've tried everytime it detects .dynamic from sh_name, it adds 1 to a variable and if the variable is > 1 it will return dynamic, but that didn't work. (won't let me post code here)
#include <stdio.h>
#include <elf.h>
#define DYNAMIC 1
#define STATIC 2
static int isstatic32(FILE* fd, Elf32_Ehdr eh, Elf32_Shdr sh_table[])
{
static int i;
static int kek = 0;
static char* sh_str;
static char* buff;
buff = malloc(sh_table[eh.e_shstrndx].sh_size);
if(buff != NULL)
{
fseek(fd, sh_table[eh.e_shstrndx].sh_offset, SEEK_SET);
fread(buff, 1, sh_table[eh.e_shstrndx].sh_size, fd);
}
sh_str = buff;
for(i=0; i<eh.e_shnum; i++)
{
printf("%d", i);
if(!strcmp(".dynamic", (sh_str + sh_table[i].sh_name)))
{
return DYNAMIC;
}
}
return STATIC;
}
int main()
{
FILE *fp = NULL;
char* f;
f = "/proc/self/exe";
Elf32_Ehdr elf_header;
Elf32_Shdr* sh_table;
fp = fopen(f, "r");
fseek(fp, 0, SEEK_SET);
fread(&elf_header, 1, sizeof(Elf32_Ehdr), fp);
sh_table = malloc(elf_header.e_shentsize*elf_header.e_shnum);
fseek(fp, elf_header.e_shoff, SEEK_SET);
fread(sh_table, 1, elf_header.e_shentsize*elf_header.e_shnum, fp);
if(isstatic32(fp, elf_header, sh_table) == STATIC)
{
printf("statically linked");
}
else
{
printf("dynamic");
}
fp = NULL;
f = NULL;
}
回答1:
the program is dynamically compiled
The program can't be dynamically compiled (or rather, "dynamically compiled" means something totally different). What you mean is that the program is dynamically linked.
Wild guess: you compiled your code in 64-bit mode (because you are on a 64-bit system which defaults to 64-bit mode).
This:
Elf32_Ehdr elf_header;
is the wrong type to use if you are trying to determine whether 64-bit executable is statically linked or not.
P.S. There are many other bugs in your program as well.
P.P.S. Presence or absence of .dynamic
is not correct way to determine whether the binary was statically or dynamically linked (sections aren't required, and can be completely stripped). You should look for PT_DYNAMIC
program header instead.
P.P.P.S. You should learn how to debug small programs.
来源:https://stackoverflow.com/questions/54432841/reading-sh-name-from-header-will-return-one-value-everytime