Fix various memory management bugs in GC mode.

This commit is contained in:
gmp
2019-06-27 11:41:58 -04:00
parent b5773b5525
commit acc8cab583
19 changed files with 696 additions and 223 deletions
+11 -2
View File
@@ -21,6 +21,10 @@ func pb2() {
a.Terminate(a)
}
func db() {
fmt.Println("button deallocated")
}
func didFinishLaunching(n *ns.NSNotification) {
fmt.Println("Go: did finish launching")
fmt.Printf("Notification: %s\n", n.Name().UTF8String())
@@ -68,12 +72,14 @@ func didFinishLaunching(n *ns.NSNotification) {
b1.Init()
b1.PressedCallback(pb1)
b1.DeallocCallback(db)
b1.SetAction(ns.Selector("pressed"))
b1.SetTarget(b1)
b1.SetTitle(nst("PUSH"))
b2.Init()
b2.PressedCallback(pb2)
b2.DeallocCallback(db)
b2.SetTarget(b2)
b2.SetAction(ns.Selector("pressed"))
b2.SetTitle(nst("QUIT"))
@@ -103,6 +109,7 @@ func didFinishLaunching(n *ns.NSNotification) {
}
func shouldTerminateAfterLastWindowClosed(s *ns.NSApplication) ns.BOOL {
fmt.Println("Go: should terminate after last window closed")
return 1
}
@@ -117,6 +124,7 @@ func didBecomeActive(n *ns.NSNotification) {
var (
a *ns.NSApplication
del *ns.AppDelegate
win *ns.NSWindow
)
@@ -127,7 +135,8 @@ func app() {
a.SetActivationPolicy(ns.NSApplicationActivationPolicyRegular)
// Set up an AppDelegate
del := ns.AppDelegateAlloc()
// assign it to a global variable so it doesn't get garbage collected
del = ns.AppDelegateAlloc()
del.ApplicationDidFinishLaunchingCallback(didFinishLaunching)
del.ApplicationShouldTerminateAfterLastWindowClosedCallback(shouldTerminateAfterLastWindowClosed)
del.ApplicationWillTerminateCallback(willTerminate)
@@ -149,6 +158,6 @@ func main() {
}()
// Run our app in an autorelease pool just for fun
go ns.Autoreleasepool(app)
go app()
select {}
}
+1
View File
@@ -41,6 +41,7 @@ subclasses:
GButton:
NSButton:
- -(void)pressed
- dealloc
frameworks: [ Foundation, AppKit ]
pragma: [ clang diagnostic ignored "-Wformat-security" ]
+2 -2
View File
@@ -100,12 +100,12 @@ func hr(d *ns.NSData) int {
func discoverCharacteristics(p *ns.CBPeripheral, s *ns.CBService, e *ns.NSError) {
fmt.Printf("Did discover characteristics\n")
uuid := s.UUID()
fmt.Printf("----%s\n", uuid.UUIDString().UTF8String())
fmt.Printf("----%s\n", uuid.UUIDString())
if uuid.IsEqualTo(hrm_uuid) {
s.Characteristics().ObjectEnumerator().ForIn(func(o *ns.Id) bool {
chr := o.CBCharacteristic()
chuuid := chr.UUID()
fmt.Printf("------%s\n", chuuid.UUIDString().UTF8String())
fmt.Printf("------%s\n", chuuid.UUIDString())
if chuuid.IsEqualTo(hrv_uuid) {
p.SetNotifyValue(1, chr)
v := chr.Value()
+41 -10
View File
@@ -4,6 +4,7 @@ package main
import (
"fmt"
"os"
"git.wow.st/gmp/nswrap/examples/foundation/ns"
)
@@ -43,8 +44,10 @@ func main() {
fmt.Printf("i1 = %@\n", i1)
fmt.Printf("i1.Ptr() = %p\n", i1.Ptr())
fmt.Printf("\nNSArray.ObjectEnumerator().ForIn():\n")
x := 0
a.ObjectEnumerator().ForIn(func(o *ns.Id) bool {
fmt.Println(o.NSString())
fmt.Printf("%d: %s\n",x,o.NSString())
x++
return true
})
fmt.Printf("\nNSSetWithObjectsCount():\n")
@@ -69,6 +72,7 @@ func main() {
}
return true
})
fmt.Printf("a = %p a.NSArray = %p\n",a,&a.NSArray)
fmt.Printf("\nNSArrayWithObjects() (length 1)\n")
a2 = ns.NSArrayWithObjects(n1)
a2.ObjectEnumerator().ForIn(func(o *ns.Id) bool {
@@ -102,19 +106,26 @@ func main() {
ns.NSArrayWithObjects(nst("obj1"), nst("obj2")),
ns.NSArrayWithObjects(nst("key1"), nst("key2")),
)
os := make([]*ns.Id, 0, 5)
fmt.Printf("Length of os is %d\n", len(os))
ks := make([]*ns.Id, 0, 5)
oarr := make([]*ns.Id, 0, 5)
fmt.Printf("Length of oarr is %d\n", len(oarr))
karr := make([]*ns.Id, 0, 5)
fmt.Printf("\nGetObjects()\n")
d.GetObjects(&os, &ks, 4)
fmt.Printf("Length of os is now %d\n", len(os))
for i, k := range ks {
fmt.Printf("-- %s -> %s\n", k.NSString(), os[i].NSString())
d.GetObjects(&oarr, &karr, 4)
fmt.Printf("Length of oarr is now %d\n", len(oarr))
for i, k := range karr {
fmt.Printf("-- %s -> %s\n", k.NSString(), oarr[i].NSString())
}
fmt.Printf("\nNSStringWithContentsOfURLEncoding()\n")
err := make([]*ns.NSError, 1)
n1 = ns.NSStringWithContentsOfURLEncoding(ns.NSURLWithGoString("htttypo://example.com"), 0, &err)
fmt.Printf("err: %s\n", err[0].LocalizedDescription())
n1 = ns.NSStringWithContentsOfURLEncoding(ns.NSURLWithGoString("http://captive.apple.com"), ns.NSUTF8StringEncoding, &err)
if len(err) == 0 {
fmt.Printf("n1 = %s\n",n1)
}
n1 = ns.NSStringWithContentsOfURLEncoding(ns.NSURLWithGoString("htttypo://example.com"), ns.NSUTF8StringEncoding, &err)
if len(err) > 0 {
fmt.Printf("err[0] = %p -> %p\n",err[0],err[0].Ptr())
fmt.Printf("err: %s\n", err[0].LocalizedDescription())
}
fmt.Printf("\nNSStringWithFormat()\n")
str := ns.NSStringWithFormat(nst("(%@) (%@)\n(%@)\n"), n2, n3, s1)
@@ -129,4 +140,24 @@ func main() {
fmt.Printf("--%s\n",o.NSString())
return true
})
dir,e := os.Getwd()
if e != nil {
fmt.Printf("Failed to get current working directory. %s\n",err)
os.Exit(-1)
}
path := nst(dir)
filter := ns.NSArrayWithObjects(nst("ast"),nst("yaml"))
ost := make([]*ns.NSString,0,1)
oar:= make([]*ns.NSArray,0,1)
fmt.Printf("\nCompletePathIntoString()\n")
i := path.CompletePathIntoString(&ost,0,&oar,filter)
fmt.Printf("%d matches\n",i)
if i > 0 {
fmt.Printf("ost = %s\n",ost[0])
fmt.Printf("oar =\n")
oar[0].ObjectEnumerator().ForIn(func(o *ns.Id) bool {
fmt.Printf("--%s\n",o.NSString())
return true
})
}
}
+1 -1
View File
@@ -19,7 +19,7 @@ classes:
- NSFileManager
- NSObject
functions: [ NSMakeRange ]
enums: [ P_ALL, CF.* ]
enums: [ P_ALL, CF.*, .*StringEncoding ]
frameworks: [ Foundation ]
pragma: [ clang diagnostic ignored "-Wformat-security" ]
vaargs: 32
+61 -4
View File
@@ -103,7 +103,7 @@ func memtest3() {
// check that our string was retained.
s1 := arr.ObjectAtIndex(0)
gstr := s1.NSString().UTF8String().String()
gstr := s1.NSString().String()
_ = gstr
}
}
@@ -122,6 +122,7 @@ func memtest4() {
_ = c1
runtime.GC()
time.Sleep(time.Second/50)
c1.Free() // you need to manually free UTF8Strings
}
}
@@ -145,22 +146,78 @@ func memtest5() {
u := sub.UTF8String()
u2 := sub2.UTF8String()
u3 := sub3.UTF8String()
_ = u
_ = u2
_ = u3
time.Sleep(time.Second/50)
runtime.GC()
i++
u.Free()
u2.Free()
u3.Free()
_ = u
_ = u2
_ = u3
//fmt.Printf("loop completed\n")
}
}
func tmpdict(i int) *ns.NSString {
o1 := ns.NSStringWithGoString(fmt.Sprintf("temp string 1-%d",i))
o2 := ns.NSStringWithGoString(fmt.Sprintf("temp string 2-%d",i))
k1 := ns.NSStringWithGoString(fmt.Sprintf("temp key 1-%d",i))
k2 := ns.NSStringWithGoString(fmt.Sprintf("temp key 2-%d",i))
dict := ns.NSDictionaryWithObjectsAndKeys(o1,k1,o2,k2)
ret := dict.ValueForKey(k1)
//fmt.Printf("tmpdict(): string = %s\n",ret.NSString())
defer runtime.GC() // o1, o2, k1, k2, and dict can be released after we return
return ret.NSString() // should be retained by NSDictionary.ValueForKey()
}
func tmparr(i int) *ns.NSString {
o1 := ns.NSStringWithGoString(fmt.Sprintf("temp string 3-%d",i))
o2 := ns.NSStringWithGoString(fmt.Sprintf("temp string 4-%d",i))
arr := ns.NSArrayWithObjects(o1,o2)
os := make([]*ns.Id,0,2)
arr.GetObjects(&os, ns.NSMakeRange(0,2))
defer runtime.GC() // collect o1, o2 and arr
return os[1].NSString() // should have been retained by NSArray.GetObjects()
}
func memtest6() {
fmt.Println("memtest6 started")
i := 0
for {
s1 := tmpdict(i)
s2 := tmparr(i)
time.Sleep(time.Second / 5)
u1 := s1.String() // make sure s1 and s2 are still available
u2 := s2.String()
e1 := fmt.Sprintf("temp string 1-%d",i)
if u1 != e1 {
fmt.Printf("tmpdict() error: %s != %s\n",u1,e1)
}
e2 := fmt.Sprintf("temp string 4-%d",i)
if u2 != e2 {
fmt.Printf("tmparr() error: %s != %s\n",u2,e2)
}
i++
}
}
func main() {
fmt.Printf("MultiThreaded? %t\n", ns.NSThreadIsMultiThreaded())
th := ns.NSThreadNew()
th.Start()
fmt.Printf("MultiThreaded? %t\n", ns.NSThreadIsMultiThreaded())
go memtest1()
go memtest2()
go memtest3()
go memtest4()
go memtest5()
go memtest6()
go func() {
for {
// print a progress indicator
+3 -1
View File
@@ -5,7 +5,8 @@ classes:
- NSArray
- NSMutableArray
- NSString
- NSObject
- NSDictionary
- NSThread
subclasses:
MyClass:
NSObject:
@@ -16,3 +17,4 @@ functions:
frameworks:
- Foundation
pragma: [ clang diagnostic ignored "-Wformat-security" ]
#nogc: true
+4 -5
View File
@@ -1,3 +1,4 @@
// An example of manual memory management (nogc directive in nswrap.yaml)
package main
import "C"
@@ -38,8 +39,6 @@ func memtest1() {
for {
pool := ns.NSAutoreleasePoolAlloc().Init()
o1 := ns.MyClassAlloc()
//If autorelease: true is set in nswrap.yaml, the manual calls to
//autorelease are not necessary.
o1.Autorelease()
o1.DeallocCallback(dealloc)
o1.ReleaseCallback(release)
@@ -133,6 +132,9 @@ func memtest4() {
go memtest1()
go memtest2()
go memtest3()
go memtest1()
go memtest2()
go memtest3()
}
func memtest4a() {
@@ -196,9 +198,6 @@ func main() {
//Within an autorelease pool, do not do anything that can result in a
//switch to a different thread.
//go memtest1()
//go memtest2()
//go memtest3()
go memtest4()
select {}
}
+1
View File
@@ -14,3 +14,4 @@ subclasses:
frameworks:
- Foundation
pragma: [ clang diagnostic ignored "-Wformat-security" ]
nogc: true
+2 -2
View File
@@ -1,6 +1,7 @@
package: ClassOne
inputfiles: [ ClassOne/simple.h ]
classes:
- NSObject
- ClassOne
- ClassTwo
subclasses:
@@ -8,8 +9,7 @@ subclasses:
ClassTwo:
- geti1
- -(void)myMethod1:(int)a
- +(const NSObject* _Nonnull)myMethod2:(int)a options:(NSDictionary<NSString*,NSObject*> *)opt
- -(const NSObject* _Nonnull)myMethod2:(int)a options:(NSDictionary<NSString*,NSObject*> *)opt
imports: [ simple.h ]
frameworks: [ Foundation ]
#arc: true
+157
View File
@@ -0,0 +1,157 @@
package main
import (
"fmt"
"os"
"runtime"
"sync"
"time"
"unsafe"
"git.wow.st/gmp/nswrap/examples/strings/ns"
)
func incr() func(bool) (int, float64) {
i := 0
b := 0.0
var mx sync.Mutex
return func(bad bool) (int, float64) {
mx.Lock()
if bad {
b++
defer mx.Unlock()
} else {
defer func() { i++; mx.Unlock() }()
}
if b == 0 {
return i, 0.0
} else {
return i, (b/float64(i)) * 100
}
}
}
type tracker struct {
add, drop func(*ns.Id)
check func()
i func(bool) (int, float64)
}
type record struct {
ptr unsafe.Pointer
goPtr *ns.Id
when time.Time
}
func newTracker() (func(*ns.Id), func(*ns.Id), func()) {
addch := make(chan *ns.Id)
dropch := make(chan *ns.Id)
data := []record{}
var mux sync.Mutex
go func() {
for {
select {
case x := <-addch:
mux.Lock()
data = append(data,record{
x.Ptr(),
x,
time.Now(),
})
mux.Unlock()
case x := <-dropch:
mux.Lock()
data = append(data,record{
nil,
x,
time.Now(),
})
mux.Unlock()
}
}
}()
add := func(x *ns.Id) {
addch<- x
}
drop := func(x *ns.Id) {
dropch<- x
}
check := func() {
live := map[unsafe.Pointer]*ns.Id{}
bad := false
mux.Lock()
for _,r := range data {
if r.ptr != nil {
if live[r.ptr] != nil {
fmt.Printf("COLLISION: %p & %p -> %p\n", r.goPtr, live[r.ptr], r.ptr)
bad = true
}
live[r.ptr] = r.goPtr
} else {
delete(live,r.ptr)
}
}
fmt.Printf("Checked %d records -- ",len(data))
if bad {
fmt.Printf("failed\n")
} else {
fmt.Printf("ok\n")
}
mux.Unlock()
}
return add,drop,check
}
func mkstrings(t tracker) {
for {
//fmt.Printf("main thread: %t\n",ns.NSThreadIsMainThread())
x,b := t.i(false)
str := fmt.Sprintf("string %d",x)
s := ns.NSStringWithGoString(str)
//t.add(&s.Id)
for j := 0; j < 10; j++ {
sout := s.String()
if str != sout {
_,b = t.i(true)
fmt.Printf("%3.2f%% -- %d: '%s' '%s'\n", b, x, str, sout)
}
time.Sleep(time.Second/1000)
}
if x % 1000 == 0 {
fmt.Printf("%3.2f%% -- %s\n", b, time.Now().Format("03:04:05.000"))
}
//t.drop(&s.Id)
}
}
func main() {
runtime.GOMAXPROCS(4)
fmt.Printf("Starting\n")
//ns.NSThreadNew().Start()
fmt.Printf("multithreaded: %t\n", ns.NSThreadIsMultiThreaded())
//pool := ns.NSAutoreleasePoolAlloc()
add, drop, check := newTracker()
i := tracker{add, drop, check, incr()}
go mkstrings(i)
go mkstrings(i)
go mkstrings(i)
go mkstrings(i)
go mkstrings(i)
go mkstrings(i)
go mkstrings(i)
go mkstrings(i)
go func() {
for {
runtime.GC()
time.Sleep(time.Second/100)
}
}()
time.Sleep(time.Second * 600)
i.check()
//pool.Drain()
os.Exit(0)
}
+9
View File
@@ -0,0 +1,9 @@
inputfiles:
- /System/Library/Frameworks/Foundation.framework/Headers/Foundation.h
classes:
- NSString
- NSThread
frameworks:
- Foundation
pragma: [ clang diagnostic ignored "-Wformat-security" ]
#nogc: true