Skip to content

Instantly share code, notes, and snippets.

@TJesionowski
Created December 14, 2018 00:06
Show Gist options
  • Save TJesionowski/ab6a3faddd5cb04a8533aad5a2539dd4 to your computer and use it in GitHub Desktop.
Save TJesionowski/ab6a3faddd5cb04a8533aad5a2539dd4 to your computer and use it in GitHub Desktop.
a quick demonstration of C inline assembly
// re-writing strlen, while certainly doable, isn't the point
#include <string.h>
void print(char* message);
void readLine(int maxBytes, char *dest);
int main(void) {
char message[] = "Hello world!\n";
print(message);
print("What's your name: ");
char name[128] = {};
readLine(127, name);
print("Your name is ");
print(name);
print("!\n");
}
// Directly calls sys_write
void print(char *message) {
int len = strlen(message);
asm("movq $1, %%rax\n\t"
"movq $1, %%rdi\n\t"
"syscall"
:
: "S"(message), "d"(len)
: "rax", "rdi");
return;
}
// Directly calls sys_read
void readLine(int maxBytes, char *dest) {
asm("movq $0, %%rax\n\t"
"movq $0, %%rdi\n\t"
"syscall"
: "=m"(*dest)
: "S"(dest), "d"(maxBytes)
: );
// strip the trailing newline
int i = maxBytes - 1;
while (dest[i] != '\n' && dest[i] >= 0)
i--;
if (i != 0)
dest[i] = 0;
return;
}
@TJesionowski
Copy link
Author

Interestingly if I press the up arrow key during the input prompt I get weird terminal bugs.
Must clobber an escape sequence somewhere in the plumbing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment