[Bootstrap] Add a sample shared library to used with ffi api

This commit is contained in:
Sameer Rahmani 2020-12-25 21:57:13 +00:00
parent 7ee0a60f37
commit b0925a527b
7 changed files with 120 additions and 0 deletions

View File

@ -0,0 +1,16 @@
(ns examples.ffi.foo
:require '[adssa
[serene.ffi.libllvm]])
(defmacro deffi.....)
(ffi/deffi some-function
:fn-name "some_function"
:args {:x :i32
:y :char_ptr}
:return :void)
(some-function 12 "asdasd")

View File

@ -0,0 +1,5 @@
foo:
gcc -c -Wall -Werror -fpic foo.c
gcc -shared -o libfoo.so foo.o
all: foo

View File

@ -0,0 +1,7 @@
#include <stdio.h>
void bar(void)
{
puts("Hello, I am a shared library");
}

View File

@ -0,0 +1,6 @@
#ifndef foo_h__
#define foo_h__
extern void baz(void);
#endif // foo_h__

Binary file not shown.

Binary file not shown.

86
bootstrap/pkg/dl/dl.go Normal file
View File

@ -0,0 +1,86 @@
/*
Serene --- Yet an other Lisp
Copyright (c) 2020 Sameer Rahmani <lxsameer@gnu.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package dl
/*
#cgo linux LDFLAGS: -ldl
#cgo pkg-config: libffi
#include <dlfcn.h>
#include <limits.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
static uintptr_t openShareLib(const char* path, char** err) {
void* h = dlopen(path, RTLD_NOW|RTLD_GLOBAL);
if (h == NULL) {
*err = (char*)dlerror();
}
return (uintptr_t)h;
}
static void* shareLibLookup(uintptr_t h, const char* name, char** err) {
void* r = dlsym((void*)h, name);
if (r == NULL) {
*err = (char*)dlerror();
}
return r;
}
*/
import "C"
import (
"fmt"
"unsafe"
)
type SharedLib struct{}
func Open(libPath string) (*SharedLib, error) {
cPath := make([]byte, C.PATH_MAX+1)
cRelName := make([]byte, len(libPath)+1)
copy(cRelName, libPath)
// If the given libPath exists, fill the cPath with the absolute path
// to the file (it follows symlinks).
if C.realpath(
(*C.char)(unsafe.Pointer(&cRelName[0])),
(*C.char)(unsafe.Pointer(&cPath[0]))) == nil {
return nil, fmt.Errorf("can't find the shared library '%s'", libPath)
}
//filepath := C.GoString((*C.char)(unsafe.Pointer(&cPath[0])))
var cErr *C.char
h := C.openShareLib((*C.char)(unsafe.Pointer(&cPath[0])), &cErr)
if h == 0 {
// lock.Unlock()
return nil, fmt.Errorf("failed to open shared library: '%s' due to: '%s'", libPath, C.GoString(cErr))
}
// if plugins == nil {
// plugins = make(map[string]*Plugin)
// }
initTask := C.shareLibLookup(h, C.CString("bar"), &cErr)
fmt.Printf(">> %p \n", initTask)
return &SharedLib{}, nil
}