Compare commits

...

23 Commits

Author SHA1 Message Date
xushiwei
210c483635 Merge pull request #687 from xushiwei/q
library syscall: linux fix
2024-08-09 00:33:09 +08:00
xushiwei
8ca4212650 library syscall: linux fix 2024-08-09 00:22:29 +08:00
xushiwei
c91dba5ed6 Merge pull request #686 from xushiwei/q
rollback golang.org/x/tools v0.22.0 => v0.19.0
2024-08-08 23:58:31 +08:00
xushiwei
c8de05f101 rollback golang.org/x/tools v0.22.0 => v0.19.0 2024-08-08 23:52:29 +08:00
xushiwei
0ac7cde498 Merge pull request #684 from visualfc/initafter
cl: build initAfter
2024-08-08 23:05:02 +08:00
visualfc
108829ad9c cl: build initAfter 2024-08-08 21:36:18 +08:00
xushiwei
c5b96f4e9c Merge pull request #681 from luoliwoshang/llcppsymg/refine
llcppsymg:improve parse symbol
2024-08-08 16:26:24 +08:00
luoliwoshang
4c2099d33e llcppg:remove unuse types 2024-08-08 15:18:16 +08:00
luoliwoshang
fe5de95008 llcppsymg:improve parsing process 2024-08-08 15:17:10 +08:00
xushiwei
4b0cfc0751 Merge pull request #677 from tsingbx/bigInt
llgo support big.Int
2024-08-08 14:23:32 +08:00
tsingbx
c2bf05942e add openssl BIGNUM support 2024-08-08 13:34:04 +08:00
tsingbx
df37f80c8e add big.Int Lsh and Rsh and test it 2024-08-08 13:33:14 +08:00
xushiwei
2c19d7218d Merge pull request #680 from xushiwei/q
llcppg design
2024-08-08 11:57:20 +08:00
xushiwei
34899e8d36 llcppg design 2024-08-08 11:49:55 +08:00
xushiwei
bf8c10ed25 Merge pull request #678 from spongehah/refactor/c-libuv-remove-go-wrapper
fix(c/libuv): Adjust comment errors and demo code
2024-08-08 11:33:10 +08:00
xushiwei
93c33e08c2 Merge pull request #679 from xushiwei/hmac
llcppg/ast: ppdNode
2024-08-08 11:31:01 +08:00
xushiwei
3992dd1dd0 Merge pull request #675 from hackerchai/feature/c-net-add-missing-funcs
feat(c/net): Add SockaddrStorage func, Ntohs func & SetSockOpt func
2024-08-08 11:30:48 +08:00
xushiwei
cab29c2be7 llcppg/ast: ppdNode 2024-08-08 11:21:56 +08:00
hackerchai
f582657ffd fix(c/net): Remove unused implicit import
Signed-off-by: hackerchai <i@hackerchai.com>
2024-08-08 10:12:47 +08:00
赵英杰
2823ac1aee fix(c/libuv): Adjust comment errors and demo code 2024-08-08 10:04:20 +08:00
tsingbx
289caa7cc2 add BN_CTX Start, Get, End and Add big.Int Mul and test it 2024-08-08 09:10:31 +08:00
tsingbx
0a8bad46b5 add big.Int Set, Abs, Neg and add test it 2024-08-08 08:31:03 +08:00
hackerchai
bf09e3c3ae feat(c/net): Add SockaddrStorage func, Ntohs func & SetSockOpt func 2024-08-07 18:04:04 +08:00
15 changed files with 407 additions and 503 deletions

View File

@@ -5,7 +5,7 @@ import (
"math/big" "math/big"
) )
func main() { func fib() {
// Initialize two big ints with the first two numbers in the sequence. // Initialize two big ints with the first two numbers in the sequence.
a := big.NewInt(0) a := big.NewInt(0)
b := big.NewInt(1) b := big.NewInt(1)
@@ -23,3 +23,41 @@ func main() {
} }
fmt.Println(a) // 100-digit Fibonacci number fmt.Println(a) // 100-digit Fibonacci number
} }
func abs() {
a := big.NewInt(64)
b := big.NewInt(-52)
a.Set(b)
a.Abs(a)
a.Set(big.NewInt(-164))
a.Abs(a)
fmt.Println("value: ", a.String())
}
func neg() {
fmt.Println("value: ", big.NewInt(-64).Neg(big.NewInt(-64)))
fmt.Println("value: ", big.NewInt(64).Neg(big.NewInt(64)))
fmt.Println("value: ", big.NewInt(0).Neg(big.NewInt(0)))
}
func calc() {
a := big.NewInt(64)
b := big.NewInt(-52)
c := big.NewInt(54)
fmt.Println("value:", a.Add(a, b))
fmt.Println("value:", a.Sub(b, c))
d := big.NewInt(10)
e := big.NewInt(4)
fmt.Println("value:", d.Mul(d, e))
}
func bitop() {
a := big.NewInt(4)
fmt.Println("value:", a.Lsh(a, 1))
b := big.NewInt(16)
fmt.Println("value:", b.Rsh(b, 2))
}
func main() {
bitop()
}

View File

@@ -1,8 +1,6 @@
package main package main
import ( import (
"unsafe"
"github.com/goplus/llgo/c" "github.com/goplus/llgo/c"
"github.com/goplus/llgo/c/libuv" "github.com/goplus/llgo/c/libuv"
"github.com/goplus/llgo/c/net" "github.com/goplus/llgo/c/net"
@@ -11,18 +9,18 @@ import (
var DEFAULT_PORT c.Int = 8080 var DEFAULT_PORT c.Int = 8080
var DEFAULT_BACKLOG c.Int = 128 var DEFAULT_BACKLOG c.Int = 128
type WriteReq struct { var (
Req libuv.Write Req *libuv.Write
Buf libuv.Buf Buf libuv.Buf
} )
func main() { func main() {
// Initialize the default event loop // Initialize the default event loop
var loop = libuv.DefaultLoop() var loop = libuv.DefaultLoop()
// Initialize a TCP server // Initialize a TCP server
var server libuv.Tcp server := &libuv.Tcp{}
libuv.InitTcp(loop, &server) libuv.InitTcp(loop, server)
// Set up the address to bind the server to // Set up the address to bind the server to
var addr net.SockaddrIn var addr net.SockaddrIn
@@ -30,8 +28,8 @@ func main() {
c.Printf(c.Str("Listening on %s:%d\n"), c.Str("0.0.0.0"), DEFAULT_PORT) c.Printf(c.Str("Listening on %s:%d\n"), c.Str("0.0.0.0"), DEFAULT_PORT)
// Bind the server to the specified address and port // Bind the server to the specified address and port
(&server).Bind((*net.SockAddr)(c.Pointer(&addr)), 0) server.Bind((*net.SockAddr)(c.Pointer(&addr)), 0)
res := (*libuv.Stream)(unsafe.Pointer(&server)).Listen(DEFAULT_BACKLOG, OnNewConnection) res := (*libuv.Stream)(server).Listen(DEFAULT_BACKLOG, OnNewConnection)
if res != 0 { if res != 0 {
c.Fprintf(c.Stderr, c.Str("Listen error: %s\n"), libuv.Strerror(libuv.Errno(res))) c.Fprintf(c.Stderr, c.Str("Listen error: %s\n"), libuv.Strerror(libuv.Errno(res)))
return return
@@ -41,11 +39,9 @@ func main() {
loop.Run(libuv.RUN_DEFAULT) loop.Run(libuv.RUN_DEFAULT)
} }
func FreeWriteReq(req *libuv.Write) { func FreeWriteReq() {
wr := (*WriteReq)(c.Pointer(req)) // Free the buffer base.
// Free the buffer base and the WriteReq itself. c.Free(c.Pointer(Buf.Base))
c.Free(c.Pointer(wr.Buf.Base))
c.Free(c.Pointer(wr))
} }
func AllocBuffer(handle *libuv.Handle, suggestedSize uintptr, buf *libuv.Buf) { func AllocBuffer(handle *libuv.Handle, suggestedSize uintptr, buf *libuv.Buf) {
@@ -58,26 +54,21 @@ func EchoWrite(req *libuv.Write, status c.Int) {
if status != 0 { if status != 0 {
c.Fprintf(c.Stderr, c.Str("Write error: %s\n"), libuv.Strerror(libuv.Errno(status))) c.Fprintf(c.Stderr, c.Str("Write error: %s\n"), libuv.Strerror(libuv.Errno(status)))
} }
FreeWriteReq(req) FreeWriteReq()
} }
func EchoRead(client *libuv.Stream, nread c.Long, buf *libuv.Buf) { func EchoRead(client *libuv.Stream, nread c.Long, buf *libuv.Buf) {
if nread > 0 { if nread > 0 {
req := (*WriteReq)(c.Malloc(unsafe.Sizeof(WriteReq{})))
if req == nil {
c.Fprintf(c.Stderr, c.Str("Failed to allocate memory for write request\n"))
c.Free(c.Pointer(buf.Base))
return
}
// Initialize the buffer with the data read. // Initialize the buffer with the data read.
req.Buf = libuv.InitBuf(buf.Base, c.Uint(nread)) Buf = libuv.InitBuf(buf.Base, c.Uint(nread))
// Write the data back to the client. // Write the data back to the client.
(&req.Req).Write(client, &req.Buf, 1, EchoWrite) Req = &libuv.Write{}
Req.Write(client, &Buf, 1, EchoWrite)
return return
} }
if nread < 0 { if nread < 0 {
// Handle read errors and EOF. // Handle read errors and EOF.
if libuv.Errno(nread) != libuv.EOF { if (libuv.Errno)(nread) != libuv.EOF {
c.Fprintf(c.Stderr, c.Str("Read error: %s\n"), libuv.Strerror(libuv.Errno(nread))) c.Fprintf(c.Stderr, c.Str("Read error: %s\n"), libuv.Strerror(libuv.Errno(nread)))
} }
(*libuv.Handle)(c.Pointer(client)).Close(nil) (*libuv.Handle)(c.Pointer(client)).Close(nil)
@@ -95,7 +86,7 @@ func OnNewConnection(server *libuv.Stream, status c.Int) {
} }
// Allocate memory for a new client. // Allocate memory for a new client.
client := (*libuv.Tcp)(c.Malloc(unsafe.Sizeof(libuv.Tcp{}))) client := &libuv.Tcp{}
if client == nil { if client == nil {
c.Fprintf(c.Stderr, c.Str("Failed to allocate memory for client\n")) c.Fprintf(c.Stderr, c.Str("Failed to allocate memory for client\n"))
@@ -110,9 +101,9 @@ func OnNewConnection(server *libuv.Stream, status c.Int) {
} }
// Accept the new connection and start reading data. // Accept the new connection and start reading data.
if server.Accept((*libuv.Stream)(unsafe.Pointer(client))) == 0 { if server.Accept((*libuv.Stream)(client)) == 0 {
(*libuv.Stream)(unsafe.Pointer(client)).StartRead(AllocBuffer, EchoRead) (*libuv.Stream)(client).StartRead(AllocBuffer, EchoRead)
} else { } else {
(*libuv.Handle)(unsafe.Pointer(client)).Close(nil) (*libuv.Handle)(c.Pointer(client)).Close(nil)
} }
} }

View File

@@ -251,7 +251,7 @@ func (req *Req) GetData() c.Pointer {
return nil return nil
} }
// llgo:link (*Req).SetData C.uv_handle_set_data // llgo:link (*Req).SetData C.uv_req_set_data
func (req *Req) SetData(data c.Pointer) {} func (req *Req) SetData(data c.Pointer) {}
// llgo:link (*Req).GetType C.uv_req_get_type // llgo:link (*Req).GetType C.uv_req_get_type

View File

@@ -17,7 +17,7 @@
package net package net
import ( import (
_ "unsafe" "unsafe"
"github.com/goplus/llgo/c" "github.com/goplus/llgo/c"
) )
@@ -97,6 +97,13 @@ const (
EAI_OVERFLOW /* argument buffer overflow */ EAI_OVERFLOW /* argument buffer overflow */
) )
const (
ALIGNSIZE = unsafe.Sizeof(c.LongLong(0))
MAXSIZE = 128
PAD1_SIZE = ALIGNSIZE - unsafe.Sizeof(byte(0)) - unsafe.Sizeof(byte(0))
PAD2_SIZE = MAXSIZE - unsafe.Sizeof(byte(0)) - unsafe.Sizeof(byte(0)) - PAD1_SIZE - ALIGNSIZE
)
// (TODO) merge to inet // (TODO) merge to inet
const INET_ADDRSTRLEN = 16 const INET_ADDRSTRLEN = 16
@@ -117,6 +124,14 @@ type SockaddrIn6 struct {
ScopeId c.Uint ScopeId c.Uint
} }
type SockaddrStorage struct {
Len uint8
Family uint8
pad1 [PAD1_SIZE]c.Char
align c.LongLong
pad2 [PAD2_SIZE]c.Char
}
type InAddr struct { type InAddr struct {
Addr c.Uint Addr c.Uint
} }
@@ -171,6 +186,9 @@ func Send(c.Int, c.Pointer, uintptr, c.Int) c.Long
//go:linkname Recv C.recv //go:linkname Recv C.recv
func Recv(c.Int, c.Pointer, uintptr, c.Int) c.Long func Recv(c.Int, c.Pointer, uintptr, c.Int) c.Long
//go:linkname SetSockOpt C.setsockopt
func SetSockOpt(socket c.Int, level c.Int, optionName c.Int, optionValue c.Pointer, sockLen c.Uint) c.Int
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
type AddrInfo struct { type AddrInfo struct {
@@ -196,8 +214,27 @@ func swapInt16(data uint16) uint16 {
return (data << 8) | (data >> 8) return (data << 8) | (data >> 8)
} }
func swapInt32(data c.Uint) c.Uint {
return ((data & 0xff) << 24) |
((data & 0xff00) << 8) |
((data & 0xff0000) >> 8) |
((data & 0xff000000) >> 24)
}
func Htons(x uint16) uint16 { func Htons(x uint16) uint16 {
return swapInt16(x) return swapInt16(x)
} }
func Ntohs(x uint16) uint16 {
return swapInt16(x)
}
func Htonl(x c.Uint) c.Uint {
return swapInt32(x)
}
func Ntohl(x c.Uint) c.Uint {
return swapInt32(x)
}
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------

View File

@@ -49,8 +49,19 @@ func BN_CTXSecureNew() *BN_CTX
func (*BN_CTX) Free() {} func (*BN_CTX) Free() {}
// void BN_CTX_start(BN_CTX *ctx); // void BN_CTX_start(BN_CTX *ctx);
//
// llgo:link (*BN_CTX).Start C.BN_CTX_start
func (*BN_CTX) Start() {}
// BIGNUM *BN_CTX_get(BN_CTX *ctx); // BIGNUM *BN_CTX_get(BN_CTX *ctx);
//
// llgo:link (*BN_CTX).Get C.BN_CTX_get
func (*BN_CTX) Get() *BIGNUM { return nil }
// void BN_CTX_end(BN_CTX *ctx); // void BN_CTX_end(BN_CTX *ctx);
//
// llgo:link (*BN_CTX).End C.BN_CTX_end
func (*BN_CTX) End() {}
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -191,23 +202,80 @@ func BNDec2bn(a **BIGNUM, str *c.Char) c.Int
//go:linkname BNAsc2bn C.BN_asc2bn //go:linkname BNAsc2bn C.BN_asc2bn
func BNAsc2bn(a **BIGNUM, str *c.Char) c.Int func BNAsc2bn(a **BIGNUM, str *c.Char) c.Int
/* // BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret);
BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret); //
BIGNUM *BN_signed_bin2bn(const unsigned char *s, int len, BIGNUM *ret); //go:linkname BNBin2bn C.BN_bin2bn
int BN_bn2bin(const BIGNUM *a, unsigned char *to); func BNBin2bn(s *byte, len c.Int, ret *BIGNUM) *BIGNUM
int BN_bn2binpad(const BIGNUM *a, unsigned char *to, int tolen);
int BN_signed_bn2bin(const BIGNUM *a, unsigned char *to, int tolen); // BIGNUM *BN_signed_bin2bn(const unsigned char *s, int len, BIGNUM *ret);
BIGNUM *BN_lebin2bn(const unsigned char *s, int len, BIGNUM *ret); //
BIGNUM *BN_signed_lebin2bn(const unsigned char *s, int len, BIGNUM *ret); //go:linkname BNSignedBin2bn C.BN_signed_bin2bn
int BN_bn2lebinpad(const BIGNUM *a, unsigned char *to, int tolen); func BNSignedBin2bn(s *byte, len c.Int, ret *BIGNUM) *BIGNUM
int BN_signed_bn2lebin(const BIGNUM *a, unsigned char *to, int tolen);
BIGNUM *BN_native2bn(const unsigned char *s, int len, BIGNUM *ret); // int BN_bn2bin(const BIGNUM *a, unsigned char *to);
BIGNUM *BN_signed_native2bn(const unsigned char *s, int len, BIGNUM *ret); //
int BN_bn2nativepad(const BIGNUM *a, unsigned char *to, int tolen); // llgo:link (*BIGNUM).Bn2bin C.BN_bn2bin
int BN_signed_bn2native(const BIGNUM *a, unsigned char *to, int tolen); func (bn *BIGNUM) Bn2bin(to *byte) c.Int { return 0 }
BIGNUM *BN_mpi2bn(const unsigned char *s, int len, BIGNUM *ret);
int BN_bn2mpi(const BIGNUM *a, unsigned char *to); // int BN_bn2binpad(const BIGNUM *a, unsigned char *to, int tolen);
*/ //
// llgo:link (*BIGNUM).Bn2binpad C.BN_bn2binpad
func (bn *BIGNUM) Bn2binpad(to *byte, tolen c.Int) c.Int { return 0 }
// int BN_signed_bn2bin(const BIGNUM *a, unsigned char *to, int tolen);
//
// llgo:link (*BIGNUM).SignedBn2bin C.BN_signed_bn2bin
func (bn *BIGNUM) SignedBn2bin(to *byte, tolen c.Int) c.Int { return 0 }
// BIGNUM *BN_lebin2bn(const unsigned char *s, int len, BIGNUM *ret);
//
//go:linkname BNLebin2bn C.BN_lebin2bn
func BNLebin2bn(s *byte, len c.Int, ret *BIGNUM) *BIGNUM
// BIGNUM *BN_signed_lebin2bn(const unsigned char *s, int len, BIGNUM *ret);
//
//go:linkname BNSignedLebin2bn C.BN_signed_lebin2bn
func BNSignedLebin2bn(s *byte, len c.Int, ret *BIGNUM) *BIGNUM
// int BN_bn2lebinpad(const BIGNUM *a, unsigned char *to, int tolen);
//
// llgo:link (*BIGNUM).Bn2lebinpad C.BN_bn2lebinpad
func (bn *BIGNUM) Bn2lebinpad(to *byte, tolen c.Int) c.Int { return 0 }
// int BN_signed_bn2lebin(const BIGNUM *a, unsigned char *to, int tolen);
//
// llgo:link (*BIGNUM).SignedBn2lebin C.BN_signed_bn2lebin
func (bn *BIGNUM) SignedBn2lebin(to *byte, tolen c.Int) c.Int { return 0 }
// BIGNUM *BN_native2bn(const unsigned char *s, int len, BIGNUM *ret);
//
//go:linkname BNNative2bn C.BN_native2bn
func BNNative2bn(s *byte, len c.Int, ret *BIGNUM) *BIGNUM
// BIGNUM *BN_signed_native2bn(const unsigned char *s, int len, BIGNUM *ret);
//
//go:linkname BNSignedNative2bn C.BN_signed_native2bn
func BNSignedNative2bn(s *byte, len c.Int, ret *BIGNUM) *BIGNUM
// int BN_bn2nativepad(const BIGNUM *a, unsigned char *to, int tolen);
//
// llgo:link (*BIGNUM).Bn2nativepad C.BN_bn2nativepad
func (bn *BIGNUM) Bn2nativepad(to *byte, tolen c.Int) c.Int { return 0 }
// int BN_signed_bn2native(const BIGNUM *a, unsigned char *to, int tolen);
//
// llgo:link (*BIGNUM).SignedBn2native C.BN_signed_bn2native
func (bn *BIGNUM) SignedBn2native(to *byte, tolen c.Int) c.Int { return 0 }
// BIGNUM *BN_mpi2bn(const unsigned char *s, int len, BIGNUM *ret);
//
//go:linkname BNMpi2bn C.BN_mpi2bn
func BNMpi2bn(s *byte, len c.Int, ret *BIGNUM) *BIGNUM
// int BN_bn2mpi(const BIGNUM *a, unsigned char *to);
//
// llgo:link (*BIGNUM).Bn2mpi C.BN_bn2mpi
func (bn *BIGNUM) Bn2mpi(to *byte) c.Int { return 0 }
// int BN_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b); // int BN_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
// //

View File

@@ -22,7 +22,6 @@ import (
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
"strconv"
"strings" "strings"
"unsafe" "unsafe"
@@ -61,11 +60,11 @@ func main() {
check(err) check(err)
filepaths := generateHeaderFilePath(conf.CFlags, conf.Include) filepaths := genHeaderFilePath(conf.CFlags, conf.Include)
astInfos, err := parse.ParseHeaderFile(filepaths) headerInfos, err := parse.ParseHeaderFile(filepaths, conf.TrimPrefixes)
check(err) check(err)
symbolInfo := getCommonSymbols(symbols, astInfos, conf.TrimPrefixes) symbolInfo := getCommonSymbols(symbols, headerInfos, conf.TrimPrefixes)
err = genSymbolTableFile(symbolInfo) err = genSymbolTableFile(symbolInfo)
check(err) check(err)
@@ -77,8 +76,8 @@ func check(err error) {
} }
} }
func parseDylibSymbols(lib string) ([]types.CPPSymbol, error) { func parseDylibSymbols(lib string) ([]*nm.Symbol, error) {
dylibPath, err := generateDylibPath(lib) dylibPath, err := genDylibPath(lib)
if err != nil { if err != nil {
return nil, errors.New("failed to generate dylib path") return nil, errors.New("failed to generate dylib path")
} }
@@ -88,22 +87,15 @@ func parseDylibSymbols(lib string) ([]types.CPPSymbol, error) {
return nil, errors.New("failed to list symbols in dylib") return nil, errors.New("failed to list symbols in dylib")
} }
var symbols []types.CPPSymbol var symbols []*nm.Symbol
for _, file := range files { for _, file := range files {
for _, sym := range file.Symbols { symbols = append(symbols, file.Symbols...)
demangleName := decodeSymbolName(sym.Name)
symbols = append(symbols, types.CPPSymbol{
Symbol: sym,
DemangleName: demangleName,
})
}
} }
return symbols, nil return symbols, nil
} }
func generateDylibPath(lib string) (string, error) { func genDylibPath(lib string) (string, error) {
output := lib output := lib
libPath := "" libPath := ""
libName := "" libName := ""
@@ -123,31 +115,20 @@ func generateDylibPath(lib string) (string, error) {
return dylibPath, nil return dylibPath, nil
} }
func decodeSymbolName(symbolName string) string { func decodeSymbol(symbolName string) string {
if symbolName == "" { if symbolName == "" {
return "" return ""
} }
demangled := llvm.ItaniumDemangle(symbolName, true) demangled := llvm.ItaniumDemangle(symbolName, true)
if demangled == nil { if demangled == nil {
return symbolName return symbolName
} }
defer c.Free(unsafe.Pointer(demangled)) defer c.Free(unsafe.Pointer(demangled))
demangleName := c.GoString(demangled) demangleName := c.GoString(demangled)
if demangleName == "" { return strings.TrimSpace(demangleName)
return symbolName
}
decodedName := strings.TrimSpace(demangleName)
decodedName = strings.ReplaceAll(decodedName,
"std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const",
"std::string")
return decodedName
} }
func generateHeaderFilePath(cflags string, files []string) []string { func genHeaderFilePath(cflags string, files []string) []string {
prefixPath := cflags prefixPath := cflags
prefixPath = strings.TrimPrefix(prefixPath, "-I") prefixPath = strings.TrimPrefix(prefixPath, "-I")
var includePaths []string var includePaths []string
@@ -157,77 +138,23 @@ func generateHeaderFilePath(cflags string, files []string) []string {
return includePaths return includePaths
} }
func getCommonSymbols(dylibSymbols []types.CPPSymbol, astInfoList []types.ASTInformation, prefix []string) []types.SymbolInfo { func getCommonSymbols(dylibSymbols []*nm.Symbol, symbolMap map[string]string, prefix []string) []*types.SymbolInfo {
var commonSymbols []types.SymbolInfo var commonSymbols []*types.SymbolInfo
functionNameMap := make(map[string]int) for _, dylibSym := range dylibSymbols {
symName := strings.TrimPrefix(dylibSym.Name, "_")
for _, astInfo := range astInfoList { if goName, ok := symbolMap[symName]; ok {
for _, dylibSym := range dylibSymbols { symbolInfo := &types.SymbolInfo{
if strings.TrimPrefix(dylibSym.Name, "_") == astInfo.Symbol { Mangle: symName,
cppName := generateCPPName(astInfo) CPP: decodeSymbol(dylibSym.Name),
functionNameMap[cppName]++ Go: goName,
symbolInfo := types.SymbolInfo{
Mangle: strings.TrimPrefix(dylibSym.Name, "_"),
CPP: cppName,
Go: generateMangle(astInfo, functionNameMap[cppName], prefix),
}
commonSymbols = append(commonSymbols, symbolInfo)
break
} }
commonSymbols = append(commonSymbols, symbolInfo)
} }
} }
return commonSymbols return commonSymbols
} }
func generateCPPName(astInfo types.ASTInformation) string { func genSymbolTableFile(symbolInfos []*types.SymbolInfo) error {
cppName := astInfo.Name
if astInfo.Class != "" {
cppName = astInfo.Class + "::" + astInfo.Name
}
return cppName
}
func generateMangle(astInfo types.ASTInformation, count int, prefixes []string) string {
astInfo.Class = removePrefix(astInfo.Class, prefixes)
astInfo.Name = removePrefix(astInfo.Name, prefixes)
res := ""
if astInfo.Class != "" {
if astInfo.Class == astInfo.Name {
res = "(*" + astInfo.Class + ")." + "Init"
if count > 1 {
res += "__" + strconv.Itoa(count-1)
}
} else if astInfo.Name == "~"+astInfo.Class {
res = "(*" + astInfo.Class + ")." + "Dispose"
if count > 1 {
res += "__" + strconv.Itoa(count-1)
}
} else {
res = "(*" + astInfo.Class + ")." + astInfo.Name
if count > 1 {
res += "__" + strconv.Itoa(count-1)
}
}
} else {
res = astInfo.Name
if count > 1 {
res += "__" + strconv.Itoa(count-1)
}
}
return res
}
func removePrefix(str string, prefixes []string) string {
for _, prefix := range prefixes {
if strings.HasPrefix(str, prefix) {
return strings.TrimPrefix(str, prefix)
}
}
return str
}
func genSymbolTableFile(symbolInfos []types.SymbolInfo) error {
// keep open follow code block can run successfully // keep open follow code block can run successfully
for i := range symbolInfos { for i := range symbolInfos {
println("symbol", symbolInfos[i].Go) println("symbol", symbolInfos[i].Go)
@@ -269,6 +196,7 @@ func genSymbolTableFile(symbolInfos []types.SymbolInfo) error {
} }
return nil return nil
} }
func readExistingSymbolTable(fileName string) (map[string]types.SymbolInfo, error) { func readExistingSymbolTable(fileName string) (map[string]types.SymbolInfo, error) {
existingSymbols := make(map[string]types.SymbolInfo) existingSymbols := make(map[string]types.SymbolInfo)

View File

@@ -3,23 +3,27 @@ package parse
import ( import (
"errors" "errors"
"strconv" "strconv"
"strings"
"unsafe" "unsafe"
"github.com/goplus/llgo/c" "github.com/goplus/llgo/c"
"github.com/goplus/llgo/c/clang" "github.com/goplus/llgo/c/clang"
"github.com/goplus/llgo/chore/llcppg/types"
) )
type Context struct { type Context struct {
namespaceName string namespaceName string
className string className string
astInfo []types.ASTInformation prefixes []string
symbolMap map[string]string
currentFile string currentFile string
nameCounts map[string]int
} }
func newContext() *Context { func newContext(prefixes []string) *Context {
return &Context{ return &Context{
astInfo: make([]types.ASTInformation, 0), prefixes: prefixes,
symbolMap: make(map[string]string),
nameCounts: make(map[string]int),
} }
} }
@@ -35,70 +39,83 @@ func (c *Context) setCurrentFile(filename string) {
c.currentFile = filename c.currentFile = filename
} }
var context = newContext() func (c *Context) removePrefix(str string) string {
for _, prefix := range c.prefixes {
if strings.HasPrefix(str, prefix) {
return strings.TrimPrefix(str, prefix)
}
}
return str
}
func collectFuncInfo(cursor clang.Cursor) types.ASTInformation { func (c *Context) genGoName(name string) string {
class := c.removePrefix(c.className)
name = c.removePrefix(name)
info := types.ASTInformation{ var baseName string
Namespace: context.namespaceName, if class == "" {
Class: context.className, baseName = name
} else {
baseName = c.genMethodName(class, name)
} }
return c.addSuffix(baseName)
}
func (c *Context) genMethodName(class, name string) string {
prefix := "(*" + class + ")."
if class == name {
return prefix + "Init"
}
if name == "~"+class {
return prefix + "Dispose"
}
return prefix + name
}
func (c *Context) addSuffix(name string) string {
c.nameCounts[name]++
count := c.nameCounts[name]
if count > 1 {
return name + "__" + strconv.Itoa(count-1)
}
return name
}
var context = newContext([]string{})
func collectFuncInfo(cursor clang.Cursor) {
cursorStr := cursor.String() cursorStr := cursor.String()
symbol := cursor.Mangling() symbol := cursor.Mangling()
info.Name = c.GoString(cursorStr.CStr()) name := c.GoString(cursorStr.CStr())
symbolName := c.GoString(symbol.CStr())
info.Symbol = c.GoString(symbol.CStr()) if len(symbolName) >= 1 && symbolName[0] == '_' {
if len(info.Symbol) >= 1 { symbolName = symbolName[1:]
if info.Symbol[0] == '_' {
info.Symbol = info.Symbol[1:]
}
} }
defer symbol.Dispose() defer symbol.Dispose()
defer cursorStr.Dispose() defer cursorStr.Dispose()
if context.namespaceName != "" { goName := context.genGoName(name)
info.Namespace = context.namespaceName context.symbolMap[symbolName] = goName
}
if context.className != "" {
info.Class = context.className
}
typeStr := cursor.ResultType().String()
defer typeStr.Dispose()
info.ReturnType = c.GoString(typeStr.CStr())
info.Parameters = make([]types.Parameter, cursor.NumArguments())
for i := 0; i < int(cursor.NumArguments()); i++ {
argCurSor := cursor.Argument(c.Uint(i))
argType := argCurSor.Type().String()
argName := argCurSor.String()
info.Parameters[i] = types.Parameter{
Name: c.GoString(argName.CStr()),
Type: c.GoString(argType.CStr()),
}
argType.Dispose()
argName.Dispose()
}
return info
} }
func visit(cursor, parent clang.Cursor, clientData c.Pointer) clang.ChildVisitResult { func visit(cursor, parent clang.Cursor, clientData c.Pointer) clang.ChildVisitResult {
if cursor.Kind == clang.Namespace { if cursor.Kind == clang.CursorNamespace {
nameStr := cursor.String() nameStr := cursor.String()
defer nameStr.Dispose()
context.setNamespaceName(c.GoString(nameStr.CStr())) context.setNamespaceName(c.GoString(nameStr.CStr()))
clang.VisitChildren(cursor, visit, nil) clang.VisitChildren(cursor, visit, nil)
context.setNamespaceName("") context.setNamespaceName("")
} else if cursor.Kind == clang.ClassDecl { } else if cursor.Kind == clang.CursorClassDecl {
nameStr := cursor.String() nameStr := cursor.String()
defer nameStr.Dispose()
context.setClassName(c.GoString(nameStr.CStr())) context.setClassName(c.GoString(nameStr.CStr()))
clang.VisitChildren(cursor, visit, nil) clang.VisitChildren(cursor, visit, nil)
context.setClassName("") context.setClassName("")
} else if cursor.Kind == clang.CXXMethod || cursor.Kind == clang.FunctionDecl || cursor.Kind == clang.Constructor || cursor.Kind == clang.Destructor { } else if cursor.Kind == clang.CursorCXXMethod || cursor.Kind == clang.CursorFunctionDecl || cursor.Kind == clang.CursorConstructor || cursor.Kind == clang.CursorDestructor {
loc := cursor.Location() loc := cursor.Location()
var file clang.File var file clang.File
var line, column c.Uint var line, column c.Uint
@@ -107,9 +124,7 @@ func visit(cursor, parent clang.Cursor, clientData c.Pointer) clang.ChildVisitRe
filename := file.FileName() filename := file.FileName()
if c.Strcmp(filename.CStr(), c.AllocaCStr(context.currentFile)) == 0 { if c.Strcmp(filename.CStr(), c.AllocaCStr(context.currentFile)) == 0 {
info := collectFuncInfo(cursor) collectFuncInfo(cursor)
info.Location = c.GoString(filename.CStr()) + ":" + strconv.Itoa(int(line)) + ":" + strconv.Itoa(int(column))
context.astInfo = append(context.astInfo, info)
} }
defer filename.Dispose() defer filename.Dispose()
@@ -118,14 +133,13 @@ func visit(cursor, parent clang.Cursor, clientData c.Pointer) clang.ChildVisitRe
return clang.ChildVisit_Continue return clang.ChildVisit_Continue
} }
func ParseHeaderFile(filepaths []string) ([]types.ASTInformation, error) { func ParseHeaderFile(filepaths []string, prefixes []string) (map[string]string, error) {
index := clang.CreateIndex(0, 0) index := clang.CreateIndex(0, 0)
args := make([]*c.Char, 3) args := make([]*c.Char, 3)
args[0] = c.Str("-x") args[0] = c.Str("-x")
args[1] = c.Str("c++") args[1] = c.Str("c++")
args[2] = c.Str("-std=c++11") args[2] = c.Str("-std=c++11")
context = newContext() context = newContext(prefixes)
for _, filename := range filepaths { for _, filename := range filepaths {
unit := index.ParseTranslationUnit( unit := index.ParseTranslationUnit(
@@ -149,5 +163,5 @@ func ParseHeaderFile(filepaths []string) ([]types.ASTInformation, error) {
index.Dispose() index.Dispose()
return context.astInfo, nil return context.symbolMap, nil
} }

View File

@@ -36,6 +36,11 @@ type Stmt interface {
stmtNode() stmtNode()
} }
type PPD interface { // preprocessing directive
Node
ppdNode()
}
// ============================================================================= // =============================================================================
// Expressions (Types are also expressions) // Expressions (Types are also expressions)
@@ -226,6 +231,8 @@ type EnumItem struct {
Value Expr // optional Value Expr // optional
} }
func (*EnumItem) exprNode() {}
// enum Name { Item1, Item2, ... }; // enum Name { Item1, Item2, ... };
type EnumTypeDecl struct { type EnumTypeDecl struct {
DeclBase DeclBase
@@ -261,8 +268,25 @@ func (*TypeDecl) declNode() {}
// ============================================================================= // =============================================================================
// AST File // AST File
type Include struct {
Path string `json:"path"`
}
func (*Include) ppdNode() {}
// ------------------------------------------------
type Macro struct {
}
func (*Macro) ppdNode() {}
// ------------------------------------------------
type File struct { type File struct {
Decls []Decl Decls []Decl `json:"decls"`
Includes []*Include `json:"includes,omitempty"`
Macros []*Macro `json:"macros,omitempty"`
} }
// ============================================================================= // =============================================================================

View File

@@ -59,8 +59,21 @@ llcppsigfetch - # read config from stdin
It fetches information of C/C++ symbols and print to stdout. Its format is as follows: It fetches information of C/C++ symbols and print to stdout. Its format is as follows:
``` ```json
TODO: see llgo/xtool/clang/ast [
{
"path": "/path/to/file.h",
"doc": {
"decls": [],
"macros": [],
"includes": [
{
"path": "incfile.h"
}
]
}
}
]
``` ```
### gogensig ### gogensig
@@ -69,252 +82,3 @@ TODO: see llgo/xtool/clang/ast
gogensig ast-file gogensig ast-file
gogensig - # read AST from stdin gogensig - # read AST from stdin
``` ```
## Overall
### Process
1. The Parsing Module reads `llcppg.cfg` to obtain dynamic libraries, header files, and the package name. After parsing, it writes the generated `llcppg.symb.json` path into `llcppg.cfg`.
2. The Function Declaration Generation Module reads `llcppg.cfg` to get the package name, header files, and the previously generated `llcppg.symb.json`. After parsing, it generates the function prototype `llcppg.function.json`.
3. Reads the previously generated `llcppg.information.json`, stores it as a structure, and uses gogen to generate code based on the structure.
## Parsing Module
### Input
Obtains the paths to header files and dynamic library files by reading the JSON file `llcppg.cfg`.
```json
{
"name": "inih",
"cflags": "$(pkg-config --cflags INIReader)",
"include": [
"INIReader.h",
"AnotherHeaderFile.h"
],
"libs": "$(pkg-config --libs INIReader)",
"trimPrefixes": ["Ini", "INI"]
}
```
```bash
llcppsymg config-file
```
### Implementation Steps
1. Parse dylib and store:
```go
// types.go
type CPPSymbol struct {
Symbol string `json:"symbol"`
Type string `json:"type"`
Name string `json:"name"`
}
// parser_dylib.go
func parseDylibSymbols(lib string) ([]common.CPPSymbol, error)
```
2. Parse header files and store:
```go
// common.go
type ASTInformation struct {
Namespace string `json:"namespace"`
Class string `json:"class"`
Name string `json:"name"`
BaseClasses []string `json:"baseClasses"`
ReturnType string `json:"returnType"`
Location string `json:"location"`
Parameters []Parameter `json:"parameters"`
Symbol string `json:"symbol"`
}
type Parameter struct {
Name string `json:"name"`
Type string `json:"type"`
}
// parser_ast.go
func parseHeaderFile(config types.Config) ([]common.ASTInformation, error)
```
3. Cross-reference data from the first two steps to get the final output
```go
// common.go
type SymbolInfo struct {
Mangle string `json:"mangle"` // C++ Symbol
CPP string `json:"c++"` // C++ function name
Go string `json:"go"` // Go function name
}
// common_symbols.go
func getCommonSymbols(dylibSymbols []common.CPPSymbol, astInfoList []common.ASTInformation) []common.SymbolInfo {
```
4. Generate `llcppg.symb.json` file and store the JSON file path into `llcppg.cfg`
```go
func generateJSON([]CommonSymbolInfo)
```
5. Example `llcppg.symb.json` file
```json
{
"FunctionName": "A::B::C",
"Symbol": "_ZN9INIReaderC1ERKNSt3__112basic_stringIcNS0_11char_traitsIcEENS0_9allocatorIcEEEE",
"Location": "a.h",
"UserFunctionName": "CFromA"
}
```
## Function Declaration Generation Module
### Input
No input required, directly reads the `llcppg.cfg` file
### Implementation Steps
1. Execute the executable
```bash
llcppsigfetch config-file
```
2. Parse header files
```go
// common.go
type ASTInformation struct {
Namespace string `json:"namespace"`
Class string `json:"class"`
Name string `json:"name"`
BaseClasses []string `json:"baseClasses"`
ReturnType string `json:"returnType"`
Location string `json:"location"`
Parameters []Parameter `json:"parameters"`
Symbol string `json:"symbol"`
}
type Parameter struct {
Name string `json:"name"`
Type string `json:"type"`
}
// parser_ast.go
func ParseHeaderFile(filePath string) ([]common.ASTInformation, error)
```
3. Generate the final JSON mapping file `llcppg.information.json`
```go
func GenerateJSONFile(info []common.ASTInformation)
```
```json
{
"functionName": "A::B::C",
"symbol": "_ZN9INIReaderC1ERKNSt3__112basic_stringIcNS0_11char_traitsIcEENS0_9allocatorIcEEEE",
"location": "a.h",
"returnType": "int",
"userFunctionName": "CFromA",
"parameters": [
{
"arg1": "int"
},
{
"arg2": "*char"
}
]
}
```
## Code Generation Module
### Input
No input required, directly reads `llcppg.information.json` file
### Implementation Steps
1. Execute the executable
```bash
gogensig ast-file
```
2. Parse JSON file
```go
// common.go
type HeaderFileInfo struct {
FunctionName string `json:"functionName"`
Symbol string `json:"symbol"`
Location string `json:"location"`
UserFunctionName string `json:"userFunctionName"`
Parameters map[string]string `json:"parameters"`
}
// parse_json.go
func ParseJSON(jsonFilePath string) ([]common.HeaderFileInfo, error)
```
3. Generate code using the parsed structure with gogen
```go
// generator.go
func GenerateCode(info []common.HeaderFileInfo) {
pkg := gogen.NewPackage("", PackageName, nil)
cm := comment(fmt.Sprintf("llgo:link %s %s", funcName1, symbol1))
pkg.NewFunc(recv, funcName, params, results, variadic).SetComments(pkg, cm).BodyStart(pkg).End()
}
```
### Output
1. Directory structure
```bash
package_name/
├── _demo
├── demo1.go
└── llgo_link.go
└── a.go
└── b.go
└── c.go
```
Note that `demo1.go` file needs to be written by the user
2. `llgo_link.go` is responsible for linking configuration
```go
package inih
const (
LLGoFiles = "$(pkg-config --cflags INIReader): _wrap/reader.cpp"
LLGoPackage = "link: $(pkg-config --libs inih INIReader); -linih -lINIReader"
)
```
3. Example content for `a.go`
```go
package inih
import (
_ "unsafe"
"github.com/goplus/llgo/c"
)
//go:linkname Parse C.ini_parse
func Parse(filename *c.Char, handler func(user c.Pointer, section *c.Char, name *c.Char, value *c.Char) c.Int, user c.Pointer) c.Int
//go:linkname ParseFile C.ini_parse_file
func ParseFile(file c.FilePtr, handler func(user c.Pointer, section *c.Char, name *c.Char, value *c.Char) c.Int, user c.Pointer) c.Int
//go:linkname ParseString C.ini_parse_string
func ParseString(str *c.Char, handler func(user c.Pointer, section *c.Char, name *c.Char, value *c.Char) c.Int, user c.Pointer) c.Int
```

View File

@@ -16,10 +16,6 @@
package types package types
import (
"github.com/goplus/llgo/xtool/nm"
)
// Config represents a configuration for the llcppg tool. // Config represents a configuration for the llcppg tool.
type Config struct { type Config struct {
Name string `json:"name"` Name string `json:"name"`
@@ -29,27 +25,6 @@ type Config struct {
TrimPrefixes []string `json:"trimPrefixes"` TrimPrefixes []string `json:"trimPrefixes"`
} }
type CPPSymbol struct {
DemangleName string
*nm.Symbol
}
type ASTInformation struct {
Namespace string `json:"namespace"`
Class string `json:"class"`
Name string `json:"name"`
BaseClasses []string `json:"baseClasses"`
ReturnType string `json:"returnType"`
Location string `json:"location"`
Parameters []Parameter `json:"parameters"`
Symbol string `json:"symbol"`
}
type Parameter struct {
Name string `json:"name"`
Type string `json:"type"`
}
type SymbolInfo struct { type SymbolInfo struct {
Mangle string `json:"mangle"` // C++ Symbol Mangle string `json:"mangle"` // C++ Symbol
CPP string `json:"c++"` // C++ function name CPP string `json:"c++"` // C++ function name

View File

@@ -98,8 +98,9 @@ type context struct {
patches Patches patches Patches
blkInfos []blocks.Info blkInfos []blocks.Info
inits []func() inits []func()
phis []func() phis []func()
initAfter func()
state pkgState state pkgState
inCFunc bool inCFunc bool
@@ -292,9 +293,9 @@ func (p *context) compileBlock(b llssa.Builder, block *ssa.BasicBlock, n int, do
instrs = instrs[:last] instrs = instrs[:last]
} else if p.state != pkgHasPatch { } else if p.state != pkgHasPatch {
// TODO(xsw): confirm pyMod don't need to call AfterInit // TODO(xsw): confirm pyMod don't need to call AfterInit
p.inits = append(p.inits, func() { p.initAfter = func() {
pkg.AfterInit(b, ret) pkg.AfterInit(b, ret)
}) }
} }
} else if doMainInit { } else if doMainInit {
argc := pkg.NewVar("__llgo_argc", types.NewPointer(types.Typ[types.Int32]), llssa.InC) argc := pkg.NewVar("__llgo_argc", types.NewPointer(types.Typ[types.Int32]), llssa.InC)
@@ -837,6 +838,10 @@ func NewPackageEx(prog llssa.Program, patches Patches, pkg *ssa.Package, files [
ini() ini()
} }
} }
if fn := ctx.initAfter; fn != nil {
ctx.initAfter = nil
fn()
}
return return
} }

2
go.mod
View File

@@ -7,7 +7,7 @@ require (
github.com/goplus/llvm v0.8.0 github.com/goplus/llvm v0.8.0
github.com/goplus/mod v0.13.12 github.com/goplus/mod v0.13.12
github.com/qiniu/x v1.13.10 github.com/qiniu/x v1.13.10
golang.org/x/tools v0.22.0 golang.org/x/tools v0.19.0
) )
require ( require (

4
go.sum
View File

@@ -10,5 +10,5 @@ golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8=
golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/tools v0.22.0 h1:gqSGLZqv+AI9lIQzniJ0nZDRG5GBPsSi+DRNHWNz6yA= golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
golang.org/x/tools v0.22.0/go.mod h1:aCwcsjqvq7Yqt6TNyX7QMU2enbQ/Gt0bo6krSeEri+c= golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=

View File

@@ -18,6 +18,9 @@ package big
// llgo:skipall // llgo:skipall
import ( import (
"math/rand"
"github.com/goplus/llgo/c"
"github.com/goplus/llgo/c/openssl" "github.com/goplus/llgo/c/openssl"
) )
@@ -81,9 +84,34 @@ func NewInt(x int64) *Int {
return z.SetInt64(x) return z.SetInt64(x)
} }
/*
// Set sets z to x and returns z. // Set sets z to x and returns z.
func (z *Int) Set(x *Int) *Int { func (z *Int) Set(x *Int) *Int {
if z != x {
a := (*openssl.BIGNUM)(z)
b := (*openssl.BIGNUM)(x)
a.Copy(b)
}
return z
}
// Abs sets z to |x| (the absolute value of x) and returns z.
func (z *Int) Abs(x *Int) *Int {
z.Set(x)
a := (*openssl.BIGNUM)(z)
a.SetNegative(0)
return z
}
// Neg sets z to -x and returns z.
func (z *Int) Neg(x *Int) *Int {
z.Set(x)
a := (*openssl.BIGNUM)(z)
if a.IsNegative() != 0 {
a.SetNegative(0)
} else {
a.SetNegative(1)
}
return z
} }
// Bits provides raw (unchecked but fast) access to x by returning its // Bits provides raw (unchecked but fast) access to x by returning its
@@ -92,6 +120,7 @@ func (z *Int) Set(x *Int) *Int {
// Bits is intended to support implementation of missing low-level Int // Bits is intended to support implementation of missing low-level Int
// functionality outside this package; it should be avoided otherwise. // functionality outside this package; it should be avoided otherwise.
func (x *Int) Bits() []Word { func (x *Int) Bits() []Word {
panic("todo big.Bits")
} }
// SetBits provides raw (unchecked but fast) access to z by setting its // SetBits provides raw (unchecked but fast) access to z by setting its
@@ -100,17 +129,9 @@ func (x *Int) Bits() []Word {
// SetBits is intended to support implementation of missing low-level Int // SetBits is intended to support implementation of missing low-level Int
// functionality outside this package; it should be avoided otherwise. // functionality outside this package; it should be avoided otherwise.
func (z *Int) SetBits(abs []Word) *Int { func (z *Int) SetBits(abs []Word) *Int {
panic("todo big.SetBits")
} }
// Abs sets z to |x| (the absolute value of x) and returns z.
func (z *Int) Abs(x *Int) *Int {
}
// Neg sets z to -x and returns z.
func (z *Int) Neg(x *Int) *Int {
}
*/
// Add sets z to the sum x+y and returns z. // Add sets z to the sum x+y and returns z.
func (z *Int) Add(x, y *Int) *Int { func (z *Int) Add(x, y *Int) *Int {
(*openssl.BIGNUM)(z).Add((*openssl.BIGNUM)(x), (*openssl.BIGNUM)(y)) (*openssl.BIGNUM)(z).Add((*openssl.BIGNUM)(x), (*openssl.BIGNUM)(y))
@@ -123,31 +144,35 @@ func (z *Int) Sub(x, y *Int) *Int {
return z return z
} }
/*
// Mul sets z to the product x*y and returns z. // Mul sets z to the product x*y and returns z.
func (z *Int) Mul(x, y *Int) *Int { func (z *Int) Mul(x, y *Int) *Int {
panic("todo big.Mul")
} }
// MulRange sets z to the product of all integers // MulRange sets z to the product of all integers
// in the range [a, b] inclusively and returns z. // in the range [a, b] inclusively and returns z.
// If a > b (empty range), the result is 1. // If a > b (empty range), the result is 1.
func (z *Int) MulRange(a, b int64) *Int { func (z *Int) MulRange(a, b int64) *Int {
panic("todo big.MulRange")
} }
// Binomial sets z to the binomial coefficient C(n, k) and returns z. // Binomial sets z to the binomial coefficient C(n, k) and returns z.
func (z *Int) Binomial(n, k int64) *Int { func (z *Int) Binomial(n, k int64) *Int {
panic("todo big.Binomial")
} }
// Quo sets z to the quotient x/y for y != 0 and returns z. // Quo sets z to the quotient x/y for y != 0 and returns z.
// If y == 0, a division-by-zero run-time panic occurs. // If y == 0, a division-by-zero run-time panic occurs.
// Quo implements truncated division (like Go); see QuoRem for more details. // Quo implements truncated division (like Go); see QuoRem for more details.
func (z *Int) Quo(x, y *Int) *Int { func (z *Int) Quo(x, y *Int) *Int {
panic("todo big.Quo")
} }
// Rem sets z to the remainder x%y for y != 0 and returns z. // Rem sets z to the remainder x%y for y != 0 and returns z.
// If y == 0, a division-by-zero run-time panic occurs. // If y == 0, a division-by-zero run-time panic occurs.
// Rem implements truncated modulus (like Go); see QuoRem for more details. // Rem implements truncated modulus (like Go); see QuoRem for more details.
func (z *Int) Rem(x, y *Int) *Int { func (z *Int) Rem(x, y *Int) *Int {
panic("todo big.Rem")
} }
// QuoRem sets z to the quotient x/y and r to the remainder x%y // QuoRem sets z to the quotient x/y and r to the remainder x%y
@@ -162,18 +187,21 @@ func (z *Int) Rem(x, y *Int) *Int {
// (See Daan Leijen, “Division and Modulus for Computer Scientists”.) // (See Daan Leijen, “Division and Modulus for Computer Scientists”.)
// See DivMod for Euclidean division and modulus (unlike Go). // See DivMod for Euclidean division and modulus (unlike Go).
func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int) { func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int) {
panic("todo big.QuoRem")
} }
// Div sets z to the quotient x/y for y != 0 and returns z. // Div sets z to the quotient x/y for y != 0 and returns z.
// If y == 0, a division-by-zero run-time panic occurs. // If y == 0, a division-by-zero run-time panic occurs.
// Div implements Euclidean division (unlike Go); see DivMod for more details. // Div implements Euclidean division (unlike Go); see DivMod for more details.
func (z *Int) Div(x, y *Int) *Int { func (z *Int) Div(x, y *Int) *Int {
panic("todo big.Div")
} }
// Mod sets z to the modulus x%y for y != 0 and returns z. // Mod sets z to the modulus x%y for y != 0 and returns z.
// If y == 0, a division-by-zero run-time panic occurs. // If y == 0, a division-by-zero run-time panic occurs.
// Mod implements Euclidean modulus (unlike Go); see DivMod for more details. // Mod implements Euclidean modulus (unlike Go); see DivMod for more details.
func (z *Int) Mod(x, y *Int) *Int { func (z *Int) Mod(x, y *Int) *Int {
panic("todo big.Mod")
} }
// DivMod sets z to the quotient x div y and m to the modulus x mod y // DivMod sets z to the quotient x div y and m to the modulus x mod y
@@ -191,8 +219,8 @@ func (z *Int) Mod(x, y *Int) *Int {
// ACM press.) // ACM press.)
// See QuoRem for T-division and modulus (like Go). // See QuoRem for T-division and modulus (like Go).
func (z *Int) DivMod(x, y, m *Int) (*Int, *Int) { func (z *Int) DivMod(x, y, m *Int) (*Int, *Int) {
panic("big.DivMod")
} }
*/
// Cmp compares x and y and returns: // Cmp compares x and y and returns:
// //
@@ -212,29 +240,35 @@ func (x *Int) CmpAbs(y *Int) int {
return int((*openssl.BIGNUM)(x).Ucmp((*openssl.BIGNUM)(y))) return int((*openssl.BIGNUM)(x).Ucmp((*openssl.BIGNUM)(y)))
} }
/*
// Int64 returns the int64 representation of x. // Int64 returns the int64 representation of x.
// If x cannot be represented in an int64, the result is undefined. // If x cannot be represented in an int64, the result is undefined.
func (x *Int) Int64() int64 { func (x *Int) Int64() int64 {
panic("todo big.Int64")
} }
// Uint64 returns the uint64 representation of x. // Uint64 returns the uint64 representation of x.
// If x cannot be represented in a uint64, the result is undefined. // If x cannot be represented in a uint64, the result is undefined.
func (x *Int) Uint64() uint64 { func (x *Int) Uint64() uint64 {
panic("todo big.Uint64")
} }
// IsInt64 reports whether x can be represented as an int64. // IsInt64 reports whether x can be represented as an int64.
func (x *Int) IsInt64() bool { func (x *Int) IsInt64() bool {
panic("todo big.IsInt64")
} }
// IsUint64 reports whether x can be represented as a uint64. // IsUint64 reports whether x can be represented as a uint64.
func (x *Int) IsUint64() bool { func (x *Int) IsUint64() bool {
panic("todo big.IsUint64")
} }
// Float64 returns the float64 value nearest x, // Float64 returns the float64 value nearest x,
// and an indication of any rounding that occurred. // and an indication of any rounding that occurred.
// TODO(xsw): // TODO(xsw):
// func (x *Int) Float64() (float64, Accuracy) /*
func (x *Int) Float64() (float64, Accuracy) {
panic("todo big.Float64")
}*/
// SetString sets z to the value of s, interpreted in the given base, // SetString sets z to the value of s, interpreted in the given base,
// and returns z and a boolean indicating success. The entire string // and returns z and a boolean indicating success. The entire string
@@ -259,17 +293,20 @@ func (x *Int) IsUint64() bool {
// are no other errors. If base != 0, underscores are not recognized // are no other errors. If base != 0, underscores are not recognized
// and act like any other character that is not a valid digit. // and act like any other character that is not a valid digit.
func (z *Int) SetString(s string, base int) (*Int, bool) { func (z *Int) SetString(s string, base int) (*Int, bool) {
panic("todo big.SetString")
} }
// SetBytes interprets buf as the bytes of a big-endian unsigned // SetBytes interprets buf as the bytes of a big-endian unsigned
// integer, sets z to that value, and returns z. // integer, sets z to that value, and returns z.
func (z *Int) SetBytes(buf []byte) *Int { func (z *Int) SetBytes(buf []byte) *Int {
panic("todo big.SetBytes")
} }
// Bytes returns the absolute value of x as a big-endian byte slice. // Bytes returns the absolute value of x as a big-endian byte slice.
// //
// To use a fixed length slice, or a preallocated one, use FillBytes. // To use a fixed length slice, or a preallocated one, use FillBytes.
func (x *Int) Bytes() []byte { func (x *Int) Bytes() []byte {
panic("todo big.Bytes")
} }
// FillBytes sets buf to the absolute value of x, storing it as a zero-extended // FillBytes sets buf to the absolute value of x, storing it as a zero-extended
@@ -277,18 +314,20 @@ func (x *Int) Bytes() []byte {
// //
// If the absolute value of x doesn't fit in buf, FillBytes will panic. // If the absolute value of x doesn't fit in buf, FillBytes will panic.
func (x *Int) FillBytes(buf []byte) []byte { func (x *Int) FillBytes(buf []byte) []byte {
panic("todo big.FillBytes")
} }
// BitLen returns the length of the absolute value of x in bits. // BitLen returns the length of the absolute value of x in bits.
// The bit length of 0 is 0. // The bit length of 0 is 0.
func (x *Int) BitLen() int { func (x *Int) BitLen() int {
panic("todo big.BitLen")
} }
// TrailingZeroBits returns the number of consecutive least significant zero // TrailingZeroBits returns the number of consecutive least significant zero
// bits of |x|. // bits of |x|.
func (x *Int) TrailingZeroBits() uint { func (x *Int) TrailingZeroBits() uint {
panic("todo big.TrailingZeroBits")
} }
*/
// Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z. // Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z.
// If m == nil or m == 0, z = x**y unless y <= 0 then z = 1. If m != 0, y < 0, // If m == nil or m == 0, z = x**y unless y <= 0 then z = 1. If m != 0, y < 0,
@@ -308,7 +347,6 @@ func (z *Int) Exp(x, y, m *Int) *Int {
return z return z
} }
/*
// GCD sets z to the greatest common divisor of a and b and returns z. // GCD sets z to the greatest common divisor of a and b and returns z.
// If x or y are not nil, GCD sets their value such that z = a*x + b*y. // If x or y are not nil, GCD sets their value such that z = a*x + b*y.
// //
@@ -321,6 +359,7 @@ func (z *Int) Exp(x, y, m *Int) *Int {
// //
// If a != 0 and b == 0, GCD sets z = |a|, x = sign(a) * 1, y = 0. // If a != 0 and b == 0, GCD sets z = |a|, x = sign(a) * 1, y = 0.
func (z *Int) GCD(x, y, a, b *Int) *Int { func (z *Int) GCD(x, y, a, b *Int) *Int {
panic("todo big.GCD")
} }
// Rand sets z to a pseudo-random number in [0, n) and returns z. // Rand sets z to a pseudo-random number in [0, n) and returns z.
@@ -328,6 +367,7 @@ func (z *Int) GCD(x, y, a, b *Int) *Int {
// As this uses the math/rand package, it must not be used for // As this uses the math/rand package, it must not be used for
// security-sensitive work. Use crypto/rand.Int instead. // security-sensitive work. Use crypto/rand.Int instead.
func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int { func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int {
panic("todo big.Rand")
} }
// ModInverse sets z to the multiplicative inverse of g in the ring /n // ModInverse sets z to the multiplicative inverse of g in the ring /n
@@ -335,11 +375,13 @@ func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int {
// inverse in the ring /n. In this case, z is unchanged and the return value // inverse in the ring /n. In this case, z is unchanged and the return value
// is nil. If n == 0, a division-by-zero run-time panic occurs. // is nil. If n == 0, a division-by-zero run-time panic occurs.
func (z *Int) ModInverse(g, n *Int) *Int { func (z *Int) ModInverse(g, n *Int) *Int {
panic("todo big.ModInverse")
} }
// Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0. // Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0.
// The y argument must be an odd integer. // The y argument must be an odd integer.
func Jacobi(x, y *Int) int { func Jacobi(x, y *Int) int {
panic("todo big.Jacobi")
} }
// ModSqrt sets z to a square root of x mod p if such a square root exists, and // ModSqrt sets z to a square root of x mod p if such a square root exists, and
@@ -347,19 +389,29 @@ func Jacobi(x, y *Int) int {
// ModSqrt leaves z unchanged and returns nil. This function panics if p is // ModSqrt leaves z unchanged and returns nil. This function panics if p is
// not an odd integer, its behavior is undefined if p is odd but not prime. // not an odd integer, its behavior is undefined if p is odd but not prime.
func (z *Int) ModSqrt(x, p *Int) *Int { func (z *Int) ModSqrt(x, p *Int) *Int {
panic("todo big.ModSqrt")
} }
// Lsh sets z = x << n and returns z. // Lsh sets z = x << n and returns z.
func (z *Int) Lsh(x *Int, n uint) *Int { func (z *Int) Lsh(x *Int, n uint) *Int {
a := (*openssl.BIGNUM)(z)
b := (*openssl.BIGNUM)(x)
a.Lshift(b, c.Int(n))
return z
} }
// Rsh sets z = x >> n and returns z. // Rsh sets z = x >> n and returns z.
func (z *Int) Rsh(x *Int, n uint) *Int { func (z *Int) Rsh(x *Int, n uint) *Int {
a := (*openssl.BIGNUM)(z)
b := (*openssl.BIGNUM)(x)
a.Rshift(b, c.Int(n))
return z
} }
// Bit returns the value of the i'th bit of x. That is, it // Bit returns the value of the i'th bit of x. That is, it
// returns (x>>i)&1. The bit index i must be >= 0. // returns (x>>i)&1. The bit index i must be >= 0.
func (x *Int) Bit(i int) uint { func (x *Int) Bit(i int) uint {
panic("todo big.Bit")
} }
// SetBit sets z to x, with x's i'th bit set to b (0 or 1). // SetBit sets z to x, with x's i'th bit set to b (0 or 1).
@@ -367,32 +419,38 @@ func (x *Int) Bit(i int) uint {
// if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1, // if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1,
// SetBit will panic. // SetBit will panic.
func (z *Int) SetBit(x *Int, i int, b uint) *Int { func (z *Int) SetBit(x *Int, i int, b uint) *Int {
panic("todo big.SetBit")
} }
// And sets z = x & y and returns z. // And sets z = x & y and returns z.
func (z *Int) And(x, y *Int) *Int { func (z *Int) And(x, y *Int) *Int {
panic("todo big.And")
} }
// AndNot sets z = x &^ y and returns z. // AndNot sets z = x &^ y and returns z.
func (z *Int) AndNot(x, y *Int) *Int { func (z *Int) AndNot(x, y *Int) *Int {
panic("todo big.AndNot")
} }
// Or sets z = x | y and returns z. // Or sets z = x | y and returns z.
func (z *Int) Or(x, y *Int) *Int { func (z *Int) Or(x, y *Int) *Int {
panic("todo big.Or")
} }
// Xor sets z = x ^ y and returns z. // Xor sets z = x ^ y and returns z.
func (z *Int) Xor(x, y *Int) *Int { func (z *Int) Xor(x, y *Int) *Int {
panic("todo big.Xor")
} }
// Not sets z = ^x and returns z. // Not sets z = ^x and returns z.
func (z *Int) Not(x *Int) *Int { func (z *Int) Not(x *Int) *Int {
panic("todo big.Not")
} }
// Sqrt sets z to ⌊√x⌋, the largest integer such that z² ≤ x, and returns z. // Sqrt sets z to ⌊√x⌋, the largest integer such that z² ≤ x, and returns z.
// It panics if x is negative. // It panics if x is negative.
func (z *Int) Sqrt(x *Int) *Int { func (z *Int) Sqrt(x *Int) *Int {
panic("todo big.Sqrt")
} }
*/
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------

View File

@@ -70,14 +70,16 @@ func (w WaitStatus) StopSignal() Signal {
return Signal(w>>shift) & 0xFF return Signal(w>>shift) & 0xFF
} }
/* TODO(xsw):
func (w WaitStatus) TrapCause() int { func (w WaitStatus) TrapCause() int {
if w.StopSignal() != SIGTRAP { /*
return -1 if w.StopSignal() != SIGTRAP {
} return -1
return int(w>>shift) >> 8 }
return int(w>>shift) >> 8
*/
panic("todo: syscall.WaitStatus.TrapCause")
} }
*/
func Wait4(pid int, wstatus *WaitStatus, options int, rusage *syscall.Rusage) (wpid int, err error) { func Wait4(pid int, wstatus *WaitStatus, options int, rusage *syscall.Rusage) (wpid int, err error) {
var status c.Int var status c.Int