Run gofmt -w on everything. Add 'gogc' option to use Go garbage

collector for memory management.
This commit is contained in:
gmp
2019-06-11 12:38:22 -04:00
parent d0654613ea
commit 9a4fabda24
297 changed files with 6690 additions and 6641 deletions
+15 -15
View File
@@ -1,10 +1,11 @@
package main
//go:generate nswrap
import (
"fmt"
"runtime"
"git.wow.st/gmp/nswrap/examples/app/ns"
"runtime"
)
//Shortcut for literal NSStrings
@@ -21,12 +22,12 @@ func pb2() {
func didFinishLaunching(n ns.NSNotification) {
fmt.Println("Go: did finish launching")
fmt.Printf("Notification: %s\n",n.Name().UTF8String())
fmt.Printf("Notification: %s\n", n.Name().UTF8String())
//Set up an NSWindow
win = ns.NSWindowAlloc().InitWithContentRectStyleMask(
ns.NSMakeRect(200,200,600,600),
ns.NSWindowStyleMaskTitled | ns.NSWindowStyleMaskClosable |
ns.NSWindowStyleMaskResizable,
ns.NSMakeRect(200, 200, 600, 600),
ns.NSWindowStyleMaskTitled|ns.NSWindowStyleMaskClosable|
ns.NSWindowStyleMaskResizable,
ns.NSBackingStoreBuffered,
0,
)
@@ -51,7 +52,7 @@ func didFinishLaunching(n ns.NSNotification) {
appMenu.AddItemWithTitle(nst("About"), nil, nst(""))
appMenu.AddItemWithTitle(nst("Preferences"), nil, nst(""))
appMenu.AddItemWithTitle(nst("Quit"),ns.Selector("terminate:"), nst("q"))
appMenu.AddItemWithTitle(nst("Quit"), ns.Selector("terminate:"), nst("q"))
a.SetMainMenu(m1)
fileMenu.AddItemWithTitle(nst("Open"), nil, nst(""))
fileMenu.AddItemWithTitle(nst("New"), nil, nst(""))
@@ -86,15 +87,15 @@ func didFinishLaunching(n ns.NSNotification) {
cv.AddSubview(b2.NSView)
viewmap := ns.NSDictionaryWithObjectsForKeys(
ns.NSArrayWithObjects(b1,b2),
ns.NSArrayWithObjects(nst("b1"),nst("b2")))
ns.NSArrayWithObjects(b1, b2),
ns.NSArrayWithObjects(nst("b1"), nst("b2")))
cv.AddConstraints(ns.NSLayoutConstraintsWithVisualFormat(
nst("V:|-[b1]"),0, ns.NSDictionary{}, viewmap))
nst("V:|-[b1]"), 0, ns.NSDictionary{}, viewmap))
cv.AddConstraints(ns.NSLayoutConstraintsWithVisualFormat(
nst("H:|-[b1]"),0, ns.NSDictionary{}, viewmap))
nst("H:|-[b1]"), 0, ns.NSDictionary{}, viewmap))
cv.AddConstraints(ns.NSLayoutConstraintsWithVisualFormat(
nst("H:[b1]-[b2]"),ns.NSLayoutFormatAlignAllBaseline,
nst("H:[b1]-[b2]"), ns.NSLayoutFormatAlignAllBaseline,
ns.NSDictionary{}, viewmap))
a.ActivateIgnoringOtherApps(1)
@@ -110,11 +111,11 @@ func willTerminate(n ns.NSNotification) {
func didBecomeActive(n ns.NSNotification) {
fmt.Println("Go: did become active")
fmt.Printf("Notification: %s\n",n.Name().UTF8String())
fmt.Printf("Notification: %s\n", n.Name().UTF8String())
}
var (
a ns.NSApplication
a ns.NSApplication
win ns.NSWindow
)
@@ -140,6 +141,5 @@ func app() {
func main() {
//Run our app in an autorelease pool just for fun
go ns.Autoreleasepool(app)
select { }
select {}
}
+17 -17
View File
@@ -23,7 +23,7 @@ func updateState(c ns.CBCentralManager) {
fmt.Printf(" powered off\n")
case ns.CBManagerStatePoweredOn:
fmt.Printf(" powered on\n")
cm.ScanForPeripheralsWithServices(ns.NSArrayWithObjects(hrm_uuid),ns.NSDictionary{})
cm.ScanForPeripheralsWithServices(ns.NSArrayWithObjects(hrm_uuid), ns.NSDictionary{})
}
}
@@ -35,7 +35,7 @@ func discoverPeripheral(c ns.CBCentralManager, p ns.CBPeripheral, d ns.NSDiction
}
peripheral = p
peripheral.Retain()
c.ConnectPeripheral(peripheral,ns.NSDictionary{})
c.ConnectPeripheral(peripheral, ns.NSDictionary{})
}
func connectPeripheral(c ns.CBCentralManager, p ns.CBPeripheral) {
@@ -51,10 +51,10 @@ func discoverServices(p ns.CBPeripheral, e ns.NSError) {
switch {
case serv.UUID().IsEqualTo(hrm_uuid):
fmt.Printf("--heart rate monitor service\n")
p.DiscoverCharacteristics(ns.NSArray{},serv)
p.DiscoverCharacteristics(ns.NSArray{}, serv)
case serv.UUID().IsEqualTo(ns.CBUUIDWithGoString("180A")):
fmt.Printf("--device information service\n")
p.DiscoverCharacteristics(ns.NSArray{},serv)
p.DiscoverCharacteristics(ns.NSArray{}, serv)
}
return true
})
@@ -64,9 +64,9 @@ func hr(d ns.NSData) int {
if l := int(d.Length()); l < 4 {
return 0
}
x := C.GoBytes(d.Bytes(),4)
x := C.GoBytes(d.Bytes(), 4)
flags := x[0]
if flags & 0x80 != 0 { // uint16 format
if flags&0x80 != 0 { // uint16 format
return int(binary.BigEndian.Uint16(x[1:2]))
} else {
return int(x[1])
@@ -75,13 +75,13 @@ func hr(d ns.NSData) int {
func discoverCharacteristics(p ns.CBPeripheral, s ns.CBService, e ns.NSError) {
fmt.Printf("Did discover characteristics\n")
fmt.Printf("----%s\n",s.UUID().UUIDString().UTF8String())
fmt.Printf("----%s\n", s.UUID().UUIDString().UTF8String())
if s.UUID().IsEqualTo(hrm_uuid) {
s.Characteristics().ObjectEnumerator().ForIn(func(o ns.Id) bool {
chr := o.CBCharacteristic()
fmt.Printf("------%s\n",chr.UUID().UUIDString().UTF8String())
fmt.Printf("------%s\n", chr.UUID().UUIDString().UTF8String())
if chr.UUID().IsEqualTo(hrv_uuid) {
p.SetNotifyValue(1,chr)
p.SetNotifyValue(1, chr)
v := chr.Value()
fmt.Println(hr(v))
}
@@ -93,20 +93,20 @@ func discoverCharacteristics(p ns.CBPeripheral, s ns.CBService, e ns.NSError) {
func updateValue(p ns.CBPeripheral, chr ns.CBCharacteristic, e ns.NSError) {
if chr.UUID().IsEqualTo(hrv_uuid) {
v := chr.Value()
fmt.Printf("Heart rate: %d\n",hr(v))
fmt.Printf("Heart rate: %d\n", hr(v))
}
}
var (
hrm_uuid ns.CBUUID
hrv_uuid ns.CBUUID
cd ns.CBDelegate
cm ns.CBCentralManager
hrm_uuid ns.CBUUID
hrv_uuid ns.CBUUID
cd ns.CBDelegate
cm ns.CBCentralManager
peripheral ns.CBPeripheral
)
func main() {
queue := ns.DispatchQueueCreate(ns.CharWithGoString("my_new_queue"),nil)
queue := ns.DispatchQueueCreate(ns.CharWithGoString("my_new_queue"), nil)
cd = ns.CBDelegateAlloc()
@@ -121,7 +121,7 @@ func main() {
hrv_uuid = ns.CBUUIDWithGoString("2A37")
//We defined our own queue because this won't work on the main queue.
cm = ns.CBCentralManagerAlloc().InitWithDelegateQueue(cd,queue)
cm = ns.CBCentralManagerAlloc().InitWithDelegateQueue(cd, queue)
select { }
select {}
}
+32 -31
View File
@@ -1,4 +1,5 @@
package main
//go:generate nswrap
import (
@@ -16,43 +17,43 @@ func main() {
n2 := ns.NSStringAlloc()
n2 = n2.InitWithGoString("hi world")
n3 := ns.NSStringWithGoString("ok bye")
fmt.Printf("%s\n",n3)
fmt.Printf("%s\n", n3)
fmt.Printf("\nCreating an array:\n")
a := ns.NSMutableArrayWithObjects(n1,n2,n3)
fmt.Println("Length(a) = ",a.Count())
fmt.Println("is n2 in a?",a.ContainsObject(n2))
fmt.Println("is c1 in a?",a.ContainsObject(c1))
a := ns.NSMutableArrayWithObjects(n1, n2, n3)
fmt.Println("Length(a) = ", a.Count())
fmt.Println("is n2 in a?", a.ContainsObject(n2))
fmt.Println("is c1 in a?", a.ContainsObject(c1))
fmt.Printf("\nCreating substrings and adding to the array:\n")
n4 := n2.SubstringFromIndex(3)
n5 := n3.SubstringToIndex(4)
a.AddObject(n4)
a.AddObject(n5)
fmt.Println("Length(a) = ",a.Count())
fmt.Println("Length(a) = ", a.Count())
fmt.Printf("\nSubarray with range:\n")
a2 := a.SubarrayWithRange(ns.NSMakeRange(1,3))
fmt.Println("Length(a2) = ",a2.Count())
a2 := a.SubarrayWithRange(ns.NSMakeRange(1, 3))
fmt.Println("Length(a2) = ", a2.Count())
fmt.Printf("\nObjectAtIndex(1):\n")
i1 := a.ObjectAtIndex(1).NSString()
fmt.Printf("i1 = %@\n",i1)
fmt.Printf("i1.Ptr() = %p\n",i1.Ptr())
fmt.Printf("i1 = %@\n", i1)
fmt.Printf("i1.Ptr() = %p\n", i1.Ptr())
fmt.Printf("\nNSArray.ObjectEnumerator().ForIn():\n")
a.ObjectEnumerator().ForIn(func(o ns.Id) bool {
fmt.Println(o.NSString())
return true
})
fmt.Printf("\nNSSetWithObjectsCount():\n")
s1 := ns.NSSetWithObjectsCount(&[]ns.Id{n1.Id,n2.Id},2)
s1 := ns.NSSetWithObjectsCount(&[]ns.Id{n1.Id, n2.Id}, 2)
fmt.Printf("\nNSSet.ObjectEnumerator().ForIn():\n")
s1.ObjectEnumerator().ForIn(func(o ns.Id) bool {
fmt.Println(o.NSString())
return true
})
fmt.Printf("\nNSMutableArrayWithObjects()\n")
a = ns.NSMutableArrayWithObjects(n1,s1)
a = ns.NSMutableArrayWithObjects(n1, s1)
fmt.Printf("\nNSArray.ObjectEnumerator().ForIn():\n")
a.ObjectEnumerator().ForIn(func(o ns.Id) bool {
fmt.Printf("%s -- ",o.ClassName().UTF8String())
fmt.Printf("%s -- ", o.ClassName().UTF8String())
switch {
case o.IsKindOfClass(ns.NSStringClass()):
fmt.Printf(" It's a string\n")
@@ -64,40 +65,40 @@ func main() {
return true
})
fmt.Printf("\nNSArrayWithObjects()\n")
a2 = ns.NSArrayWithObjects(n1,n2,n3,s1)
a2 = ns.NSArrayWithObjects(n1, n2, n3, s1)
fmt.Printf("\nNSArray.ObjectEnumerator().ForIn():\n")
a2.ObjectEnumerator().ForIn(func (o ns.Id) bool {
a2.ObjectEnumerator().ForIn(func(o ns.Id) bool {
switch {
case o.IsKindOfClass(ns.NSStringClass()):
fmt.Println(o.NSString().UTF8String())
return true // continue enumeration
return true // continue enumeration
default:
fmt.Println("Unknown class")
return false // terminate enumeration
return false // terminate enumeration
}
})
nst := ns.NSStringWithGoString
fmt.Printf("\nNSDictionaryWithObjectsForKeys()\n")
d := ns.NSDictionaryWithObjectsForKeys(
ns.NSArrayWithObjects(nst("obj1"),nst("obj2")),
ns.NSArrayWithObjects(nst("key1"),nst("key2")),
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)
os := make([]ns.Id, 0, 5)
fmt.Printf("Length of os is %d\n", len(os))
ks := 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(&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())
}
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())
err := make([]ns.NSError, 1)
n1 = ns.NSStringWithContentsOfURLEncoding(ns.NSURLWithGoString("htttypo://example.com"), 0, &err)
fmt.Printf("err: %s\n", err[0].LocalizedDescription())
fmt.Printf("\nNSStringWithFormat()\n")
str := ns.NSStringWithFormat(nst("(%@) (%@)\n(%@)\n"),n2,n3,s1)
fmt.Printf("%s\n",str)
str := ns.NSStringWithFormat(nst("(%@) (%@)\n(%@)\n"), n2, n3, s1)
fmt.Printf("%s\n", str)
}
+99
View File
@@ -0,0 +1,99 @@
package main
import "C"
import (
"fmt"
"runtime"
"time"
"git.wow.st/gmp/nswrap/examples/gc/ns"
)
func releaseX(x int) func (ns.MyClassSupermethods) {
return func(super ns.MyClassSupermethods) {
//fmt.Printf("--release %d\n", x)
super.Release() // comment out for leak
}
}
func memtest1() {
fmt.Println("memtest1 started")
for {
arr := make([]ns.MyClass,1000)
for i := 0; i < 1000; i++ {
// Alloc methods set a finalizer that causes the Go GC to
// Release these objects.
arr[i] = ns.MyClassAlloc()
arr[i].ReleaseCallback(releaseX(i))
// You can still manually retain objects, but that will cause
// them to stick around after their Go pointers are collected.
// This may be necessary if you are adding objects to an
// Objective-C collection?
//arr[i].Retain() // uncomment for leak
}
// Manually run the Go GC at every loop iteration. May not be needed
// in a real program.
runtime.GC()
time.Sleep(time.Second/50)
fmt.Printf("Loop complete\n")
}
}
func memtest2() {
fmt.Println("memtest2 started")
for {
o1 := ns.NSStringAlloc().InitWithGoString("one string")
// NSWrap runs object constructors inside an @autoreleasepool block,
// and then calls "retain" on them before returning to Go. A Go
// finalizer is set allowing the Go GC to call Release().
o2 := ns.NSStringWithGoString("two string") // does not leak
arr := ns.NSArrayWithObjects(o1,o2)
_ = arr
runtime.GC()
time.Sleep(time.Second/50)
}
}
func addStr(arr ns.NSMutableArray) {
s1 := ns.NSStringAlloc().InitWithGoString("a string")
arr.AddObject(s1)
// s1 should be eligible for Go garbage collection here, but is still referenced
// on the Objective-C side. By adding s1 to an array, the array automatically
// calls 'retain' on the underlying Objective-C string.
}
func memtest3() {
fmt.Println("memtest3 started")
arr := ns.NSMutableArrayAlloc().Init() // arr will be garbage collected by Go
addStr(arr)
runtime.GC()
time.Sleep(time.Second)
s1 := arr.ObjectAtIndex(0)
fmt.Println(s1.NSString().UTF8String())
fmt.Println("memtest3 done")
}
func memtest4() {
fmt.Println("memtest4 started")
for {
o1 := ns.NSStringAlloc().InitWithGoString("four string")
c1 := o1.UTF8String()
_ = o1
_ = c1
time.Sleep(time.Second/10)
}
}
func main() {
go memtest1()
go memtest2()
go memtest3()
go memtest4()
select {}
}
@@ -16,16 +16,11 @@ import (
"unsafe"
)
//export MyClassDealloc
func MyClassDealloc(o unsafe.Pointer) {
cb := MyClassLookup[o].Dealloc
if cb == nil { return }
cb()
}
//export MyClassRelease
func MyClassRelease(o unsafe.Pointer) {
MyClassMux.RLock()
cb := MyClassLookup[o].Release
MyClassMux.RUnlock()
if cb == nil { return }
self := MyClass{}
self.ptr = o
@@ -34,3 +29,12 @@ func MyClassRelease(o unsafe.Pointer) {
}
cb(super)
}
//export MyClassDealloc
func MyClassDealloc(o unsafe.Pointer) {
MyClassMux.RLock()
cb := MyClassLookup[o].Dealloc
MyClassMux.RUnlock()
if cb == nil { return }
cb()
}
File diff suppressed because it is too large Load Diff
+17
View File
@@ -0,0 +1,17 @@
inputfiles:
- /System/Library/Frameworks/Foundation.framework/Headers/Foundation.h
classes:
- NSAutoreleasePool
- NSArray
- NSMutableArray
- NSString
- NSObject
subclasses:
MyClass:
NSObject:
- dealloc
- release
frameworks:
- Foundation
pragma: [ clang diagnostic ignored "-Wformat-security" ]
gogc: true
+51 -28
View File
@@ -17,7 +17,6 @@ func dealloc() {
func release(super ns.MyClassSupermethods) {
fmt.Println("--release called")
super.Release() // comment out for leak
}
@@ -39,8 +38,8 @@ 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.
//If autorelease: true is set in nswrap.yaml, the manual calls to
//autorelease are not necessary.
o1.Autorelease()
o1.DeallocCallback(dealloc)
o1.ReleaseCallback(release)
@@ -55,7 +54,7 @@ func memtest1() {
_ = o3
_ = o4
pool.Drain()
time.Sleep(time.Second/2)
time.Sleep(time.Second / 2)
}
fmt.Println("memtest1: done")
}
@@ -71,11 +70,12 @@ func memtest2() {
ns.Autoreleasepool(func() {
o1 := ns.NSObjectAlloc()
o1.Autorelease()
s1 := ns.NSStringWithGoString(fmt.Sprintf("string-%d",i))
//Does not leak strings within an autorelease pool
s1 := ns.NSStringWithGoString(fmt.Sprintf("string-%d", i))
_ = s1
//o1.Retain() // uncomment for leak
})
time.Sleep(time.Second/3)
time.Sleep(time.Second / 3)
}
fmt.Println("memtest2: done")
}
@@ -87,18 +87,26 @@ func memtest3() {
runtime.LockOSThread() // comment out for crash
fmt.Println("memtest3: started")
for { ns.Autoreleasepool(func() {
arr := ns.NSMutableArrayAlloc().Init()
arr.Autorelease()
arr.AddObject(ns.NSStringWithGoString("my string"))
i := 0
for {
ns.Autoreleasepool(func() {
arr := ns.NSMutableArrayAlloc().Init()
arr.Autorelease()
arr.AddObject(ns.NSStringWithGoString(fmt.Sprintf("my string %d",i)))
s1 := ns.NSStringWithGoString(fmt.Sprintf("my other string %d",i))
_ = s1
i++
for { ns.Autoreleasepool(func() {
str := arr.ObjectAtIndex(0).NSString()
fmt.Println(str) // does not leak in an autorelease pool
time.Sleep(time.Second / 2)
})}
time.Sleep(time.Second)
})}
for {
ns.Autoreleasepool(func() {
str := arr.ObjectAtIndex(0).NSString()
fmt.Println(str) // does not leak in an autorelease pool
time.Sleep(time.Second / 2)
})
}
time.Sleep(time.Second)
})
}
fmt.Println("memtest3: done")
}
@@ -117,34 +125,39 @@ func memtest4() {
// Exactly one goroutine (locked to an OS thread) can use an
// autorelease pool (?)
go memtest1()
go memtest2()
}
func memtest4a() {
for {
o1 := ns.NSObjectAlloc()
o1.Init()
time.Sleep(time.Second/50)
time.Sleep(time.Second / 50)
o1.Release()
}
}
func memtest4b() {
i := 0
for {
o1 := ns.NSObjectAlloc() // need to Release
//s1 := ns.NSStringWithGoString(fmt.Sprintf("a string %d",i)) // uncomment for leak
s1 := ns.NSStringWithGoString("a string")
arr := ns.NSArrayAlloc().InitWithObjects(s1) // need to Release
i++
arr := ns.NSArrayAlloc().InitWithObjects(s1) // need to Release arr
s2 := arr.ObjectAtIndex(0).NSString()
//If you try to convert an NSString to UTF8String, CString (*Char),
//or GoString, Objective-C runtime will leak an
//NSTaggedPointerCStringContainer. Don't know why or how to fix it.
//There would be no leak if we were using an autorelease pool.
//If you try to convert an NSString to UTF8String, CString (*Char),
//or GoString, Objective-C runtime will leak an
//NSTaggedPointerCStringContainer. Don't know why or how to fix it.
//There would be no leak if we were using an autorelease pool.
//u := str.UTF8String() // uncomment for leak
//fmt.Println(s1) // uncomment for leak
time.Sleep(time.Second/50)
time.Sleep(time.Second / 50)
o1.Release()
arr.Release()
//s1.Release() // does not work
_ = o1
_ = s2
}
@@ -154,12 +167,22 @@ func memtest4c() {
o1 := ns.NSArrayAlloc()
o2 := ns.NSStringAlloc()
time.Sleep(time.Second/50)
time.Sleep(time.Second / 50)
o1.Release()
o2.Release()
}
}
func fin(o *ns.MyClass) {
o.Release()
}
func releaseX(x int) func (ns.MyClassSupermethods) {
return func(super ns.MyClassSupermethods) {
fmt.Printf("--release %d\n", x)
super.Release() // comment out for leak
}
}
func main() {
//Uncomment more than one test at a time for a crash.
@@ -169,7 +192,7 @@ func main() {
//go memtest1()
//go memtest2()
go memtest3()
//go memtest4()
select { }
//go memtest3()
go memtest4()
select {}
}
Binary file not shown.
Binary file not shown.
+3 -3
View File
@@ -1,4 +1,5 @@
package main
//go:generate nswrap
import (
@@ -13,8 +14,8 @@ func cb(super ns.ClassThreeSupermethods) ns.Int {
func main() {
o := ns.ClassOneAlloc().Init()
fmt.Println("i1 = ",o.Geti1())
fmt.Println("p1 = ",o.Getp1())
fmt.Println("i1 = ", o.Geti1())
fmt.Println("p1 = ", o.Getp1())
p1 := o.Getp1()
fmt.Println("*p1 = ", *p1)
*p1 = 17
@@ -31,4 +32,3 @@ func main() {
fmt.Println(o3.Hi2(np))
fmt.Println(o3.Geti1())
}