Last active
December 16, 2015 13:19
-
-
Save ichaos/5441114 to your computer and use it in GitHub Desktop.
C: code snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdarg.h> | |
#include <string.h> | |
#include <errno.h> | |
/* eprintf: print error message and exit */ | |
void eprintf(char *fmt, ...) { | |
va_list args; | |
fflush(stdout); | |
if (progname() != NULL) | |
fprintf(stderr, "%s: ", progname()); | |
va_start(args, fmt); | |
vfprintf(stderr, fmt, args); | |
va_end(args); | |
if (fmt[0] != '\0' && fmt[strlen(fmt) - 1] == ':') | |
fprintf(stderr, " %s", stderror(errno)); | |
fprintf(stderr, "\n"); | |
exit(2); /* conventional value for failed execution */ | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* gcc inline assembly example | |
*/ | |
#include <stdio.h> | |
int main() { | |
unsigned long esp; | |
unsigned long ebp; | |
//get esp and ebp | |
__asm__ (//".att_syntax\n\t" | |
"movq %%rsp, %0\n\t" | |
"movq %%rbp, %1\n\t" | |
: "=r"(esp), "=r"(ebp) | |
: | |
: "memory"); | |
printf("current stack pointer is 0x%lx, stack frame pointer 0x%lx\n", | |
esp, ebp); | |
//get return value | |
unsigned long ret_pc; | |
__asm__ ("movq 8(%%rbp), %0\n\t" | |
: "=r"(ret_pc) | |
:); | |
printf("return address is 0x%lx\n", ret_pc); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* vmcall at domU(HVM) using gcc inline assembly | |
* this example works on Intel machine | |
*/ | |
#define VMCALL ".byte 0x0f,0x01,0xc1" | |
// push vmcall number and return value into eax, no argument | |
static inline long hypercall0(unsigned int nr) | |
{ | |
long ret; | |
asm volatile(KVM_HYPERCALL | |
: "=a"(ret) | |
: "a"(nr) | |
: "memory"); | |
return ret; | |
} | |
// add one argument, storing in rdi | |
static inline long kvm_hypercall1(unsigned int nr, unsigned long p1) | |
{ | |
long ret; | |
asm volatile(KVM_HYPERCALL | |
: "=a"(ret) | |
: "a"(nr), "b"(p1) | |
: "memory"); | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment