[英]String Corruption in my Number Printing Function for 16bit Real Mode DOS
我正在编写一个程序,它将在 DOS 中以 16 位实模式运行,使用 GCC 编译,并在 DOSBox 下进行测试。
这是我用来创建可执行文件的 linker 脚本(从https://github.com/skeeto/dosdefender-ld31/blob/master/com.ld 复制):
OUTPUT_FORMAT(binary)
SECTIONS
{
. = 0x0100;
.text :
{
*(.text);
}
.data :
{
*(.data);
*(.bss);
*(.rodata);
}
_heap = ALIGN(4);
}
我可以打印以“$”结尾的字符串,但不能打印包含数字和“$”的 2 个字符串; 我得到一个 memory 转储,如下所示:
这是我的 makefile,我将标志传递给 gcc 最小化大小,而不是链接到 C 运行时库。
CC = gcc
DOS = dosbox
CFLAGS = -std=gnu99 -Wall -Wextra -Os -nostdlib -m32 -march=i386 \
-Wno-unused-function \
-ffreestanding -fomit-frame-pointer -fwrapv -fno-strict-aliasing \
-fno-leading-underscore -fno-pic -fno-stack-protector \
-Wl,--nmagic,-static,-Tcom.ld,--verbose=99
.PHONY : all clean test
all:
$(CC) -o bottles.com $(CFLAGS) main.c
clean :
$(RM) *.com
test : bottles.com
$(DOS) $^
%.com : %.c
$(CC) -o $@ $(CFLAGS) $<
这是'main.c':
asm (".code16gcc\n"
"call dosmain\n"
"mov $0x4C,%ah\n"
"int $0x21\n");
static void print(char *string)
{
asm volatile ("mov $0x09, %%ah\n"
"int $0x21\n"
: /* no output */
: "d"(string)
: "ah");
}
static int _pow(int a, int b)
{
int x = a;
for (int i=1; i < b; i++) {
x = x * a;
}
return x;
}
static int getdigits(int val)
{
int d = 0;
int n = val;
while (n != 0) {
n /= 10;
d++;
}
return d;
}
static void putint(int val)
{
const int digits_num = getdigits(val);
const int base10_m = _pow(10, (digits_num - 1));
int r = val;
const char eof = '$';
char digit_s[2] = {0,eof};
for (int i = base10_m; i >= 10 ; i/=10) {
digit_s[0] = '0' + ( r - ( r % i ) ) / i ;
print(digit_s);
r -= ( r - ( r % i ));
}
digit_s[0] = '0' + r;
print(digit_s);
}
int dosmain(void)
{
print(1337);
return 0;
}
是什么导致 memory 如上所示被转储?
我通过查看此页面解决了我的问题: http://spike.scu.edu.au/~barry/interrupts.html#ah02 。
在页面上还有另一个中断 function, 0x02,它打印出一个推入堆栈的字符。
我写了这个 function 来调用这个中断 function:
static void putchar(char ch)
{
asm volatile ("mov $0x02, %%ah\n"
"int $0x21\n"
: /* no output */
: "d"(ch)
: "ah");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.