racket / ChezScheme

Chez Scheme
Apache License 2.0
110 stars 8 forks source link

[FFI][ARM64] Calling C function with certain signatures gives strange result on Apple M1 machine (MacOS 13) #50

Closed shih-liang closed 2 years ago

shih-liang commented 2 years ago

C Side:

#include <stdio.h>

void Cfunc(int o, int p, int q, int a, int b, int c, float d, float *e, int f, float *g, int h, float i, float *j, int k) {
  printf("o:%d,p:%d,q:%d,a:%d,b:%d,c:%d,d:%f,e:%p,f:%d,g:%p,h:%d,i:%f,j:%p,k:%d\n", o,p,q,a,b,c,d,e,f,g,h,i,j,k);
}

Compile to so:

gcc -c -fPIC -o test.o test.c
gcc -shared -fPIC -Wl -o test.so test.o -lc

Scheme Side:

(load-shared-object "test.so")
(define Cfunc (foreign-procedure "Cfunc" (int int int int int int float (* float) int (* float) int float (* float) int) void))
(define v (list -1 -2 -3 1 2 3 4.0 (make-ftype-pointer float 5) 6 (make-ftype-pointer float 7) 8 9.0 (make-ftype-pointer float 4) 11))
(display v) (newline)
(apply Cfunc v)

The outputs should be the same, but what actually get is:

Scheme output: (-1 -2 -3 1 2 3 4.0 #<ftype-pointer float 5> 6 #<ftype-pointer float 7> 8 9.0 #<ftype-pointer float 4> 11)
C output: o:-1,p:-2,q:-3,a:1,b:2,c:3,d:4.000000,e:0x5,f:6,g:0x7,h:8,i:9.000000,j:0xb00000000,k:0

The last two variables get wrong values.

This is tested on an Apple M1 machine with MacOS beta and clang 14.0 installed.

❯ uname -a
Darwin ShideMBP.lan 22.0.0 Darwin Kernel Version 22.0.0: Tue Jun 28 20:46:36 PDT 2022; root:xnu-8792.0.134.131.2~1/RELEASE_ARM64_T6000 arm64
❯ gcc -v
Apple clang version 14.0.0 (clang-1400.0.28.1)
Target: arm64-apple-darwin22.0.0
Thread model: posix
InstalledDir: /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
mflatt commented 2 years ago

Thanks for the report!