What happens if the wrong address is preselected?

Simple MWE:

int* ptr = (int*)malloc(64 * sizeof(int)); _mm_prefetch((const char*)(ptr + 64), _MM_HINT_0); 
  • Is this a specific or undefined behavior?
  • Can this raise a signal and interrupt the start of a program?

I ask, since I see such a prefetch in the code generated by the compiler, where inside the prefetch the loop is executed without checking the address (stored in rbx ):

 400e73: 49 83 c5 40 add r13,0x40 400e77: 62 f1 f9 08 28 03 vmovapd zmm0,ZMMWORD PTR [rbx] 400e7d: 4d 3b ec cmp r13,r12 400e80: 62 d1 f9 08 eb 4d ff vporq zmm1,zmm0,ZMMWORD PTR [r13-0x40] 400e87: 90 nop 400e88: 62 d1 78 08 29 4d ff vmovaps ZMMWORD PTR [r13-0x40],zmm1 400e8f: 72 03 jb 400e94 <main+0x244> 400e91: 49 89 c5 mov r13,rax 400e94: 62 f1 78 08 18 53 1d vprefetch1 [rbx+0x740] 400e9b: ff c1 inc ecx 400e9d: 62 f1 78 08 18 4b 02 vprefetch0 [rbx+0x80] 400ea4: 48 83 c3 40 add rbx,0x40 400ea8: 81 f9 00 00 10 00 cmp ecx,0x100000 400eae: 72 c3 jb 400e73 <main+0x223> 
+5
source share
1 answer

First of all, the compiler doing this, or you are doing this, is in theory completely different things. Just because it looks equivalent, it doesnโ€™t, the compiler is allowed to use any dirty hacks that work regardless of whether they are expressible or defined in fully standard C.

Of course, prefetching does not generate signals *, it would be almost useless if this happened. This can be very slow for some invalid pointers, although, depending on whether they trigger TLB skips. Thus, the compiler can use it safely, but it should not indiscriminately use it for everything.

Now, using pointer arithmetic to create bounds pointers (except for the end) is theoretically UB, but when applied to a pointer, it is a type of UB that will work anyway (with flat memory it's just an addition, the only way it can to fail is that the compiler does this to detect it, which means that it will have to reason about dynamic sizes). Obviously, the above case should be supported by compilers claiming to support SSE, otherwise you could not reasonably use prefetching as demonstrated in this answer (and there are more additional guarantees that they must fulfill over the standard).

* from the manual:

The PREFETCHh instruction is just a hint and does not affect the behavior of the program.

The signal will affect the behavior of the program, so they cannot be generated.

+4
source

Source: https://habr.com/ru/post/1258459/


All Articles