Skip to content

modify armv7_tick prototype to return uint64_t instead of uint32_t - #17555

Closed
marler8997 wants to merge 1 commit into
openssl:masterfrom
marler8997:armTickR1Clobber
Closed

marler8997 wants to merge 1 commit into
openssl:masterfrom
marler8997:armTickR1Clobber

Conversation

@marler8997

@marler8997 marler8997 commented Jan 20, 2022 •

Copy link
Copy Markdown

Addresses an ABI issue on 32-bit arm. The implementation of armv7_tick calls the mrrc instruction to retrieve a counter from the p15 coprocessor. This is a 64-bit counter and it is stored into the 2 32-bit registers r0 and r1. The problem is that the C prototype only declares the function as returning a 32-bit value, so the compiler is not aware that the r1 register is being clobbered. This results in undefined behavior and I confirmed that I would get unpredictable results with a small test app that duplicates this problem. Modifying the return type to uint64_t fixed the unpredictable results that I observed. I confirmed in the 32-bit arm ABI documentation that a 64-bit result from a function is stored in r0 and r1, which would inform the compiler that r1 is being overwritten by the armv7_tick function properly.

This could be related to:

#14838
#17009
#17465

Addresses an ABI issue on 32-bit arm.  The implementation of armv7_tick
calls the mrrc instruction to retrieve a counter from the p15 coprocessor.
This is a 64-bit counter and it is stored into the 2 32-bit registers
r0 and r1.  The problem is that the C prototype only declares the function
as returning a 32-bit value, so the compiler is not aware that the r1
register is being clobbered.  This results in undefined behavior and I
confirmed that I would get unpredictable results with a small test app
that duplicates this problem.  Modifying the return type to uint64_t
fixed the unpredictable results that I observed. I confirmed in the 32-bit
arm ABI documentation that a 64-bit result from a function is stored in
r0 and r1, which would inform the compiler that r1 is being overwritten
by the armv7_tick function properly.

This could be related to:

openssl#14838
openssl#17009
openssl#17465

CLA: trivial
@bernd-edlinger

Copy link
Copy Markdown
Member

I'm a bit surprised, since r1-r3 are scratch registers.
How does your test case look like?

@marler8997

marler8997 commented Jan 20, 2022 •

Copy link
Copy Markdown
Author

To build the example you'll need the zig compiler: https://ziglang.org/download/
Linux-x86_64 is here: https://ziglang.org/builds/zig-linux-x86_64-0.10.0-dev.339+0e682e71b.tar.xz

Source code is here:

cntvct.zig:

const std = @import("std");

// Use T = u32 to reproduce ABI issue, T = u64 will fix it
const T = u32;
fn armv7_tick() callconv(.C) T {
    return asm (
    \\ mrrc    p15,1,%[ret],r1,c14
    : [ret] "={r0}" (-> T)
    :
    //: "r1" (NOTE: telling compiler that r1 is clobbered will also fix ABI issue)
    );
}

var val: T = 0;
const val_ptr: *volatile T = &val;

pub export fn _start() noreturn {
    var i: usize = 0;
    log("starting armv7_tick call loop...", .{});
    // NOTE: using while(true) won't reproduce the segfault from using incorrect u32 ABI
    while (i < 10) : (i += 1) {
        val_ptr.* = armv7_tick();
        if ((i % 100000000) == 0) {
            log("{}: last value was 0x{x}", .{i, val_ptr.*});
        }
    }
    log("done, last value was {}", .{val_ptr.*});
    std.os.exit(0);
}

pub fn panic(msg: []const u8, trace: ?*std.builtin.StackTrace) noreturn {
    _ = trace;
    std.log.err("panic: {s}", .{msg});
    std.os.exit(1);
}
fn log(comptime msg: []const u8, args: anytype) void {
    std.io.getStdOut().writer().print(msg ++ "\n", args) catch @panic("write to stdout failed");
}

Build with:

zig build-exe -O ReleaseSmall -target arm-linux-musl cntvct.zig --single-threaded

This will cross-compile the code for arm32, the executable will be named cntvct. I ran this on a cortex a72. When using type u32 I get this segfault:

$ ./cntvct
starting armv7_tick call loop...
Segmentation fault (core dumped)

SELinux also prints this:

[590130.886733] audit: type=1701 audit(1642688368.656:12): auid=4294967295 uid=0 gid=0 ses=4294967295 subj=kernel pid=4068 comm="cntvct" exe="/tmp/foo/cntvct" sig=11

The error goes away if I turn the while(i < 10) into while (true). This shows how clobbering registers without the compiler knowing causes undefined behavior which can cause any number of issues. The issue also goes away if I declare the ABI properly by using u64 instead of u32, or if I tell the compiler that r1 is clobbered in the asm volatile configuration.

@bernd-edlinger

Copy link
Copy Markdown
Member

But with your patch the OPENSSL_rdtsc function changes just from this:

00178b3c <OPENSSL_rdtsc>:
  178b3c:       e59f3018        ldr     r3, [pc, #24]   ; 178b5c <OPENSSL_rdtsc+0x20>
  178b40:       e59f2018        ldr     r2, [pc, #24]   ; 178b60 <OPENSSL_rdtsc+0x24>
  178b44:       e08f3003        add     r3, pc, r3
  178b48:       e7933002        ldr     r3, [r3, r2]
  178b4c:       e5930000        ldr     r0, [r3]
  178b50:       e2100002        ands    r0, r0, #2
  178b54:       012fff1e        bxeq    lr
  178b58:       ea00003a        b       178c48 <_armv7_tick>
  178b5c:       001bc4b4        .word   0x001bc4b4
  178b60:       00000280        .word   0x00000280

to this:

00178b3c <OPENSSL_rdtsc>:
  178b3c:       e59f3020        ldr     r3, [pc, #32]   ; 178b64 <OPENSSL_rdtsc+0x28>
  178b40:       e59f2020        ldr     r2, [pc, #32]   ; 178b68 <OPENSSL_rdtsc+0x2c>
  178b44:       e08f3003        add     r3, pc, r3
  178b48:       e7933002        ldr     r3, [r3, r2]
  178b4c:       e5930000        ldr     r0, [r3]
  178b50:       e2100002        ands    r0, r0, #2
  178b54:       012fff1e        bxeq    lr
  178b58:       e92d4010        push    {r4, lr}
  178b5c:       eb000039        bl      178c48 <_armv7_tick>
  178b60:       e8bd8010        pop     {r4, pc}
  178b64:       001bc4b4        .word   0x001bc4b4
  178b68:       00000280        .word   0x00000280

so it still clobbers r1, but is less performance, since it has two additional instructions.

@marler8997

Copy link
Copy Markdown
Author

Remember that this is "undefined behavior" which means that it could work or may not work. I gave you an example where it produces a segfault, but I don't know what your example with your toolchain and your optimization/sanitazation/whatever flags do. In the example I gave you where it produces a segfault because of the clobber, the diff between that and telling the compiler that the clobber occurs is this (original on left, fixed on right):

image

So the original is this:

        mrrc    p15, #1, r0, r1, c14
        ldr     r1, .LCPI1_1
        str     r0, [r7]

And the fixed is this:

        mrrc    p15, #1, r0, r1, c14
        str     r0, [r7]
        ldr     r1, .LCPI1_1

If I modify the ABI to use u64 then the code changes quite a bit more, which is what I've done in this PR. Allowing undefined behavior in the name of performance doesn't seem like the right choice to me.

@marler8997

marler8997 commented Jan 20, 2022 •

Copy link
Copy Markdown
Author

I should also clarify I'm not familiar enough with arm asm to critique the assembly you provided. But you said that r1 is still clobbered. The problem isn't that r1 is overwritten, it's that it's overwritten in the armv7_tick assembly and the compiler doesn't know about it. By "clobbered" I'm saying it's overwritten "unknowingly". If in your new assembly it's still overwritten then that's fine because the compiler knows about it, so if it needed that register then it would know to save it beforehand. And the original compiled assembly (without this PR) you provided may not have any issue because you don't have a particular set of compiler options or toolchain to expose the undefined behavior in a poor way such as creating a segfault.

@bernd-edlinger

Copy link
Copy Markdown
Member

But your compiler does inline this function, the ABI is not about inline, it is about call conventions for external functions.
Clobbering r1 in an inline assembler statement, that is declared only to clobber r0 is of course a completely different
thing.

@marler8997

marler8997 commented Jan 20, 2022 •

Copy link
Copy Markdown
Author

Whether it's inlined doesn't matter, the compiler still doesn't know that the armv7_tick assembly is clobbering the r1 register. The ABI tells the compiler what registers that assembly code uses, which in this case is either r0 (for uint32_t) or r0 and r1 (for uint64_t).

And a correction on my assembly diff. What I gave you was from GodBolt but it's slightly different from what my local compilation did. Here is the diff with objdump before and after I let the compiler know the assembly clobbers the r1 register:

80,81c80,81
<    2020c:	e59f10f8 	ldr	r1, [pc, #248]	; 0x2030c
<    20210:	ec510f1e 	mrrc	15, 1, r0, r1, cr14
---
>    2020c:	ec510f1e 	mrrc	15, 1, r0, r1, cr14
>    20210:	e59f10f4 	ldr	r1, [pc, #244]	; 0x2030c

Also note that the next line is:

   20214:	e5810000 	str	r0, [r1]

In the bad version, the compiler loads the r1 register, then calls mrrc but thinks the r1 register still has what it did, then loads r0 with whatever r1 is pointing to. That's what causes the segfault. When I tell the compiler that mrrc clobbers r1, then it just reorders those 2 instructions and no more segfault.

@paulidale

paulidale commented Jan 21, 2022 •

Copy link
Copy Markdown
Contributor

According to gcc and Microsoft, R1 is not saved by functions. Overwriting it should not cause problems for the caller.

As @bernd-edlinger noted, your inline assembler will cause problems because it isn't a function call and it says that it doesn't clobber R1.

I'd still like to see our rdtsc function return a 64 bit value but I don't think this is the underlying issue.

@marler8997

Copy link
Copy Markdown
Author

Oh ok, so it looks like C compilers assume r0 through r3 are never guaranteed. It looks in Zig's inline assembly it doesn't assume this and requires the clobbers to be explicit. Thanks for the pointers

@marler8997 marler8997 closed this Jan 21, 2022
@paulidale

paulidale commented Jan 21, 2022 •

Copy link
Copy Markdown
Contributor

Exactly. The same thing would happen with inline assembly for any compiler.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants