Skip to contentSkip to conversation

generated Go libxl bindings using IDL

PATCH Superseded Nick Rosbrook 2 participants 33 messages Dec 10, 2019 – Dec 17, 2019

v3 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v3 cover generated Go libxl bindings using IDL

From: Nick Rosbrook <[email protected]>

After Xen summit, we started the discussion in this[1] RFC thread to figure out how to generate Go bindings for libxl. This series implements that Go code generation using the existing IDL, and updates the existing hand-written code in xenlight.go to use the generated code.

The goal of this series is to provide a good foundation for continued development of the Go package.

The v1 series can be found on my GitHub branch[2].

Changes in v2:
- GitHub branch for v2 [3].
- Drop patch 01/24 from v1 since was committed as a bug fix for 4.13.
- The Makefile changes in 24/24 from v1 have been moved to the patches where the build changes are introduced.

Changes in v3:
- GitHub branch for v3 [4].
- Simplify a pattern for iterating over builtin types in their fromC functions.
- Try not to duplicate as much code in gengotypes.py, and use consistent style in generated code when calling fromC.

[1] https://lists.xenproject.org/archives/html/xen-devel/2019-07/msg02259.html
[2] https://github.com/enr0n/xen/tree/golang-patches-v1
[3] https://github.com/enr0n/xen/tree/golang-patches-v2
[4] https://github.com/enr0n/xen/tree/golang-patches-v3

Nick Rosbrook (22):
golang/xenlight: generate enum types from IDL golang/xenlight: define Defbool builtin type golang/xenlight: define Devid type as int golang/xenlight: define KeyValueList as empty struct golang/xenlight: re-name Bitmap marshaling functions golang/xenlight: define StringList builtin type golang/xenlight: define Mac builtin type golang/xenlight: define MsVmGenid builtin type golang/xenlight: define EvLink builtin as empty struct golang/xenlight: define CpuidPolicyList builtin type golang/xenlight: re-factor Uuid type implementation golang/xenlight: re-factor Hwcap type implementation golang/xenlight: generate structs from the IDL golang/xenlight: remove no-longer used type MemKB golang/xenlight: begin C to Go type marshaling golang/xenlight: implement keyed union C to Go marshaling golang/xenlight: implement array C to Go marshaling golang/xenlight: begin Go to C type marshaling golang/xenlight: implement keyed union Go to C marshaling golang/xenlight: implement array Go to C marshaling golang/xenlight: revise use of Context type golang/xenlight: add error return type to Context.Cpupoolinfo

 tools/golang/xenlight/Makefile       |   20 +-
 tools/golang/xenlight/gengotypes.py  |  677 ++++++
 tools/golang/xenlight/helpers.gen.go | 3246 ++++++++++++++++++++++++++
 tools/golang/xenlight/types.gen.go   | 1224 ++++++++++
 tools/golang/xenlight/xenlight.go    |  901 +++----
 5 files changed, 5531 insertions(+), 537 deletions(-)
 create mode 100644 tools/golang/xenlight/gengotypes.py
 create mode 100644 tools/golang/xenlight/helpers.gen.go
 create mode 100644 tools/golang/xenlight/types.gen.go
Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#1 lore raw

PATCH v3 1/22 golang/xenlight: generate enum types from IDL

From: Nick Rosbrook <[email protected]>

Introduce gengotypes.py to generate Go code the from IDL. As a first step, implement 'enum' type generation.

As a result of the newly-generated code, remove the existing, and now conflicting definitions in xenlight.go. In the case of the Error type, rename the slice 'errors' to 'libxlErrors' so that it does not conflict with the standard library package 'errors.' And, negate the values used in 'libxlErrors' since the generated error values are negative.

---
Changes in v2:
- Introduce Makefile targets for code generation
- Re-generate Go code (includes new libxl_passtrhough enum).
- Use *.gen.go naming convention for generated Go files.

---
 tools/golang/xenlight/Makefile      |  18 +-
 tools/golang/xenlight/gengotypes.py | 109 ++++++++
 tools/golang/xenlight/types.gen.go  | 388 ++++++++++++++++++++++++++++
 tools/golang/xenlight/xenlight.go   | 140 ++--------
 4 files changed, 535 insertions(+), 120 deletions(-)
 create mode 100644 tools/golang/xenlight/gengotypes.py
 create mode 100644 tools/golang/xenlight/types.gen.go
tools/golang/xenlight/Makefile +10 -8
index 0987305224..681f32c234 100644
@@ -7,20 +7,21 @@ GOCODE_DIR ?= $(prefix)/share/gocode/
 GOXL_PKG_DIR = /src/$(XEN_GOCODE_URL)/xenlight/
 GOXL_INSTALL_DIR = $(GOCODE_DIR)$(GOXL_PKG_DIR)
 
-# PKGSOURCES: Files which comprise the distributed source package
-PKGSOURCES = xenlight.go
-
 GO ?= go
 
 .PHONY: all
 all: build
 
 .PHONY: package
-package: $(XEN_GOPATH)$(GOXL_PKG_DIR)$(PKGSOURCES)
+package: $(XEN_GOPATH)$(GOXL_PKG_DIR)
 
-$(XEN_GOPATH)/src/$(XEN_GOCODE_URL)/xenlight/$(PKGSOURCES): $(PKGSOURCES)
+$(XEN_GOPATH)/src/$(XEN_GOCODE_URL)/xenlight/: %.gen.go
 	$(INSTALL_DIR) $(XEN_GOPATH)$(GOXL_PKG_DIR)
-	$(INSTALL_DATA) $(PKGSOURCES) $(XEN_GOPATH)$(GOXL_PKG_DIR)
+	$(INSTALL_DATA) xenlight.go $(XEN_GOPATH)$(GOXL_PKG_DIR)
+	$(INSTALL_DATA) types.gen.go $(XEN_GOPATH)$(GOXL_PKG_DIR)
+
+%.gen.go: gengotypes.py $(XEN_ROOT)/tools/libxl/libxl_types.idl $(XEN_ROOT)/tools/libxl/idl.py
+	XEN_ROOT=$(XEN_ROOT) $(PYTHON) gengotypes.py ../../libxl/libxl_types.idl
 
 # Go will do its own dependency checking, and not actuall go through
 # with the build if none of the input files have changed.
@@ -36,10 +37,11 @@ build: package
 .PHONY: install
 install: build
 	$(INSTALL_DIR) $(DESTDIR)$(GOXL_INSTALL_DIR)
-	$(INSTALL_DATA) $(XEN_GOPATH)$(GOXL_PKG_DIR)$(PKGSOURCES) $(DESTDIR)$(GOXL_INSTALL_DIR)
+	$(INSTALL_DATA) $(XEN_GOPATH)$(GOXL_PKG_DIR)xenlight.go $(DESTDIR)$(GOXL_INSTALL_DIR)
+	$(INSTALL_DATA) $(XEN_GOPATH)$(GOXL_PKG_DIR)types.gen.go $(DESTDIR)$(GOXL_INSTALL_DIR)
 
 .PHONY: uninstall
-	rm -f $(addprefix $(DESTDIR)$(GOXL_INSTALL_DIR)/, $(PKGSOURCES))
+	rm -rf $(DESTDIR)$(GOXL_INSTALL_DIR)
 
 .PHONY: clean
 clean:
tools/golang/xenlight/gengotypes.py new file +109 -0

109 lines not on this page · raw message

tools/golang/xenlight/types.gen.go new file +388 -0

388 lines not on this page · raw message

tools/golang/xenlight/xenlight.go +28 -112

178 lines not on this page · raw message

Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#2 lore raw

Re: [Xen-devel] [PATCH v3 01/22] golang/xenlight: generate enum types from IDL

Quoted 39 lines · Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Introduce gengotypes.py to generate Go code the from IDL. As a first step, implement 'enum' type generation.

As a result of the newly-generated code, remove the existing, and now conflicting definitions in xenlight.go. In the case of the Error type, rename the slice 'errors' to 'libxlErrors' so that it does not conflict with the standard library package 'errors.' And, negate the values used in 'libxlErrors' since the generated error values are negative.

---
Changes in v2:
- Introduce Makefile targets for code generation
- Re-generate Go code (includes new libxl_passtrhough enum).
- Use *.gen.go naming convention for generated Go files.

---
 tools/golang/xenlight/Makefile      |  18 +-
 tools/golang/xenlight/gengotypes.py | 109 ++++++++
 tools/golang/xenlight/types.gen.go  | 388 ++++++++++++++++++++++++++++
 tools/golang/xenlight/xenlight.go   | 140 ++--------
 4 files changed, 535 insertions(+), 120 deletions(-)
 create mode 100644 tools/golang/xenlight/gengotypes.py
 create mode 100644 tools/golang/xenlight/types.gen.go
tools/golang/xenlight/Makefile +0 -3
index 0987305224..681f32c234 100644
@@ -7,20 +7,21 @@ GOCODE_DIR ?= $(prefix)/share/gocode/
 GOXL_PKG_DIR = /src/$(XEN_GOCODE_URL)/xenlight/
 GOXL_INSTALL_DIR = $(GOCODE_DIR)$(GOXL_PKG_DIR)
 
-# PKGSOURCES: Files which comprise the distributed source package
-PKGSOURCES = xenlight.go
-
 GO ?= go

tools/golang/xenlight/Makefile GOCODE_DIR ?= $(prefix)/share/gocode/ · line 18

Quoted 10 lines
tools/golang/xenlight/Makefile +2 -2
 
 .PHONY: all
 all: build
 
 .PHONY: package
-package: $(XEN_GOPATH)$(GOXL_PKG_DIR)$(PKGSOURCES)
+package: $(XEN_GOPATH)$(GOXL_PKG_DIR)
 
-$(XEN_GOPATH)/src/$(XEN_GOCODE_URL)/xenlight/$(PKGSOURCES): $(PKGSOURCES)
+$(XEN_GOPATH)/src/$(XEN_GOCODE_URL)/xenlight/: %.gen.go

I was expecting you to change this if you sent a v3. :-)

I can still change it on check-in, but if for some reason there's a v4, please make the change before resending. Thanks. :-)

-George

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#3 lore raw

Re: [Xen-devel] [PATCH v3 01/22] golang/xenlight: generate enum types from IDL

Quoted 4 lines

I was expecting you to change this if you sent a v3. :-)

I can still change it on check-in, but if for some reason there's a v4, please make the change before resending. Thanks. :-)

Sorry, my mistake. I will make the change if I send v4.

Thanks,
-NR

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#4 lore raw

PATCH v3 2/22 golang/xenlight: define Defbool builtin type

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Define Defbool as struct analagous to the C type, and define the type 'defboolVal' that represent true, false, and default defbool values.

Implement Set, Unset, SetIfDefault, IsDefault, Val, and String functions on Defbool so that the type can be used in Go analagously to how its used in C.

Finally, implement fromC and toC functions.

---
 tools/golang/xenlight/xenlight.go | 93 +++++++++++++++++++++++++++++++
 1 file changed, 93 insertions(+)
tools/golang/xenlight/xenlight.go +93 -0
index 89ed439fd0..640d82f35f 100644
@@ -85,6 +85,99 @@ type MemKB uint64
 
 type Uuid C.libxl_uuid
 
+// defboolVal represents a defbool value.
+type defboolVal int
+
+const (
+	defboolDefault defboolVal = 0
+	defboolFalse   defboolVal = -1
+	defboolTrue    defboolVal = 1
+)
+
+// Defbool represents a libxl_defbool.
+type Defbool struct {
+	val defboolVal
+}
+
+func (d Defbool) String() string {
+	switch d.val {
+	case defboolDefault:
+		return "<default>"
+	case defboolFalse:
+		return "False"
+	case defboolTrue:
+		return "True"
+	}
+
+	return ""
+}
+
+// Set sets the value of the Defbool.
+func (d *Defbool) Set(b bool) {
+	if b {
+		d.val = defboolTrue
+		return
+	}
+	d.val = defboolFalse
+}
+
+// Unset resets the Defbool to default value.
+func (d *Defbool) Unset() {
+	d.val = defboolDefault
+}
+
+// SetIfDefault sets the value of Defbool only if
+// its current value is default.
+func (d *Defbool) SetIfDefault(b bool) {
+	if d.IsDefault() {
+		d.Set(b)
+	}
+}
+
+// IsDefault returns true if the value of Defbool
+// is default, returns false otherwise.
+func (d *Defbool) IsDefault() bool {
+	return d.val == defboolDefault
+}
+
+// Val returns the boolean value associated with the
+// Defbool value. An error is returned if the value
+// is default.
+func (d *Defbool) Val() (bool, error) {
+	if d.IsDefault() {
+		return false, fmt.Errorf("%v: cannot take value of default defbool", ErrorInval)
+	}
+
+	return (d.val > 0), nil
+}
+
+func (d *Defbool) fromC(c *C.libxl_defbool) error {
+	if C.libxl_defbool_is_default(*c) {
+		d.val = defboolDefault
+		return nil
+	}
+
+	if C.libxl_defbool_val(*c) {
+		d.val = defboolTrue
+		return nil
+	}
+
+	d.val = defboolFalse
+
+	return nil
+}
+
+func (d *Defbool) toC() (C.libxl_defbool, error) {
+	var c C.libxl_defbool
+
+	if !d.IsDefault() {
+		val, _ := d.Val()
+		C.libxl_defbool_set(&c, C.bool(val))
+	}
+
+	return c, nil
+}
+
 type Context struct {
 	ctx    *C.libxl_ctx
 	logger *C.xentoollog_logger_stdiostream
Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#5 lore raw

PATCH v3 3/22 golang/xenlight: define Devid type as int

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

---
 tools/golang/xenlight/xenlight.go | 3 +++
 1 file changed, 3 insertions(+)
tools/golang/xenlight/xenlight.go +3 -0
index 640d82f35f..8ac26e63f0 100644
@@ -81,6 +81,9 @@ func (e Error) Error() string {
 
 type Domid uint32
 
+// Devid is a device ID.
+type Devid int
+
 type MemKB uint64
 
 type Uuid C.libxl_uuid
Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#6 lore raw

PATCH v3 4/22 golang/xenlight: define KeyValueList as empty struct

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Define KeyValueList as empty struct as there is currently no reason for this type to be available in the Go package.

Implement fromC and toC functions as no-ops.

---
Changes in v2:
- Re-define KeyValueList as empty struct, as it was decided this type probably shouldn't be exposed in the Go package.

---
 tools/golang/xenlight/xenlight.go | 10 ++++++++++
 1 file changed, 10 insertions(+)
tools/golang/xenlight/xenlight.go +10 -0
index 8ac26e63f0..3edff18471 100644
@@ -202,6 +202,16 @@ func (chwcap C.libxl_hwcap) toGo() (ghwcap Hwcap) {
 	return
 }
 
+// KeyValueList represents a libxl_key_value_list.
+//
+// Represented as an empty struct for now, as there is no
+// apparent need for this type to be exposed through the
+// Go package.
+type KeyValueList struct{}
+
+func (kvl KeyValueList) fromC(ckvl *C.libxl_key_value_list) error      { return nil }
+func (kvl KeyValueList) toC() (ckvl C.libxl_key_value_list, err error) { return }
+
 // typedef struct {
 //     uint32_t size;          /* number of bytes in map */
 //     uint8_t *map;
Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#7 lore raw

PATCH v3 5/22 golang/xenlight: re-name Bitmap marshaling functions

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Re-name and modify signature of toGo function to fromC. The reason for using 'fromC' rather than 'toGo' is that it is not a good idea to define methods on the C types. Also, add error return type to Bitmap's toC function.

Finally, as code-cleanup, re-organize the Bitmap type's comments as per Go conventions.

--
Changes in v2:
- Use consistent variable naming for slice created from libxl_bitmap.

---
 tools/golang/xenlight/xenlight.go | 94 ++++++++++++++++---------------
 1 file changed, 48 insertions(+), 46 deletions(-)
tools/golang/xenlight/xenlight.go +48 -46
index 3edff18471..1c5e3c0cc7 100644
@@ -212,20 +212,48 @@ type KeyValueList struct{}
 func (kvl KeyValueList) fromC(ckvl *C.libxl_key_value_list) error      { return nil }
 func (kvl KeyValueList) toC() (ckvl C.libxl_key_value_list, err error) { return }
 
-// typedef struct {
-//     uint32_t size;          /* number of bytes in map */
-//     uint8_t *map;
-// } libxl_bitmap;
-
+// Bitmap represents a libxl_bitmap.
+//
 // Implement the Go bitmap type such that the underlying data can
 // easily be copied in and out.  NB that we still have to do copies
 // both directions, because cgo runtime restrictions forbid passing to
 // a C function a pointer to a Go-allocated structure which contains a
 // pointer.
 type Bitmap struct {
+	// typedef struct {
+	//     uint32_t size;          /* number of bytes in map */
+	//     uint8_t *map;
+	// } libxl_bitmap;
 	bitmap []C.uint8_t
 }
 
+func (bm *Bitmap) fromC(cbm *C.libxl_bitmap) error {
+	// Alloc a Go slice for the bytes
+	size := int(cbm.size)
+	bm.bitmap = make([]C.uint8_t, size)
+
+	// Make a slice pointing to the C array
+	cs := (*[1 << 30]C.uint8_t)(unsafe.Pointer(cbm._map))[:size:size]
+
+	// And copy the C array into the Go array
+	copy(bm.bitmap, cs)
+
+	return nil
+}
+
+func (bm *Bitmap) toC() (C.libxl_bitmap, error) {
+	var cbm C.libxl_bitmap
+
+	size := len(bm.bitmap)
+	cbm.size = C.uint32_t(size)
+	cbm._map = (*C.uint8_t)(C.malloc(C.ulong(cbm.size) * C.sizeof_uint8_t))
+	cs := (*[1 << 31]C.uint8_t)(unsafe.Pointer(cbm._map))[:size:size]
+
+	copy(cs, bm.bitmap)
+
+	return cbm, nil
+}
+
 /*
  * Types: IDL
  *
@@ -426,7 +454,7 @@ func (cci C.libxl_cpupoolinfo) toGo() (gci CpupoolInfo) {
 	gci.PoolName = C.GoString(cci.pool_name)
 	gci.Scheduler = Scheduler(cci.sched)
 	gci.DomainCount = int(cci.n_dom)
-	gci.Cpumap = cci.cpumap.toGo()
+	gci.Cpumap.fromC(&cci.cpumap)
 
 	return
 }
@@ -500,7 +528,10 @@ func (Ctx *Context) CpupoolCreate(Name string, Scheduler Scheduler, Cpumap Bitma
 	var uuid C.libxl_uuid
 	C.libxl_uuid_generate(&uuid)
 
-	cbm := Cpumap.toC()
+	cbm, err := Cpumap.toC()
+	if err != nil {
+		return
+	}
 	defer C.libxl_bitmap_dispose(&cbm)
 
 	ret := C.libxl_cpupool_create(Ctx.ctx, name, C.libxl_scheduler(Scheduler),
@@ -555,7 +586,10 @@ func (Ctx *Context) CpupoolCpuaddCpumap(Poolid uint32, Cpumap Bitmap) (err error
 		return
 	}
 
-	cbm := Cpumap.toC()
+	cbm, err := Cpumap.toC()
+	if err != nil {
+		return
+	}
 	defer C.libxl_bitmap_dispose(&cbm)
 
 	ret := C.libxl_cpupool_cpuadd_cpumap(Ctx.ctx, C.uint32_t(Poolid), &cbm)
@@ -591,7 +625,10 @@ func (Ctx *Context) CpupoolCpuremoveCpumap(Poolid uint32, Cpumap Bitmap) (err er
 		return
 	}
 
-	cbm := Cpumap.toC()
+	cbm, err := Cpumap.toC()
+	if err != nil {
+		return
+	}
 	defer C.libxl_bitmap_dispose(&cbm)
 
 	ret := C.libxl_cpupool_cpuremove_cpumap(Ctx.ctx, C.uint32_t(Poolid), &cbm)
@@ -714,41 +751,6 @@ func (Ctx *Context) CpupoolMakeFree(Cpumap Bitmap) (err error) {
  * Bitmap operations
  */
 
-// Return a Go bitmap which is a copy of the referred C bitmap.
-func (cbm C.libxl_bitmap) toGo() (gbm Bitmap) {
-	// Alloc a Go slice for the bytes
-	size := int(cbm.size)
-	gbm.bitmap = make([]C.uint8_t, size)
-
-	// Make a slice pointing to the C array
-	mapslice := (*[1 << 30]C.uint8_t)(unsafe.Pointer(cbm._map))[:size:size]
-
-	// And copy the C array into the Go array
-	copy(gbm.bitmap, mapslice)
-
-	return
-}
-
-// Must be C.libxl_bitmap_dispose'd of afterwards
-func (gbm Bitmap) toC() (cbm C.libxl_bitmap) {
-	C.libxl_bitmap_init(&cbm)
-
-	size := len(gbm.bitmap)
-	cbm._map = (*C.uint8_t)(C.malloc(C.size_t(size)))
-	cbm.size = C.uint32_t(size)
-	if cbm._map == nil {
-		panic("C.calloc failed!")
-	}
-
-	// Make a slice pointing to the C array
-	mapslice := (*[1 << 30]C.uint8_t)(unsafe.Pointer(cbm._map))[:size:size]
-
-	// And copy the Go array into the C array
-	copy(mapslice, gbm.bitmap)
-
-	return
-}
-
 func (bm *Bitmap) Test(bit int) bool {
 	ubit := uint(bit)
 	if bit > bm.Max() || bm.bitmap == nil {
@@ -1137,8 +1139,8 @@ func (cvci C.libxl_vcpuinfo) toGo() (gvci Vcpuinfo) {
 	gvci.Blocked = bool(cvci.blocked)
 	gvci.Running = bool(cvci.running)
 	gvci.VCpuTime = time.Duration(cvci.vcpu_time)
-	gvci.Cpumap = cvci.cpumap.toGo()
-	gvci.CpumapSoft = cvci.cpumap_soft.toGo()
+	gvci.Cpumap.fromC(&cvci.cpumap)
+	gvci.CpumapSoft.fromC(&cvci.cpumap_soft)
 
 	return
 }
Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#8 lore raw

PATCH v3 6/22 golang/xenlight: define StringList builtin type

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Define StringList as []string an implement fromC and toC functions.

---
Changes in v2:
- Define fromC with a pointer receiver since a newly-allocated slice is being assigned to the StringList.

---
 tools/golang/xenlight/xenlight.go | 29 +++++++++++++++++++++++++++++
 1 file changed, 29 insertions(+)
tools/golang/xenlight/xenlight.go +29 -0
index 1c5e3c0cc7..72afc3cf14 100644
@@ -212,6 +212,35 @@ type KeyValueList struct{}
 func (kvl KeyValueList) fromC(ckvl *C.libxl_key_value_list) error      { return nil }
 func (kvl KeyValueList) toC() (ckvl C.libxl_key_value_list, err error) { return }
 
+// StringList represents a libxl_string_list.
+type StringList []string
+
+func (sl *StringList) fromC(csl *C.libxl_string_list) error {
+	size := int(C.libxl_string_list_length(csl))
+	list := (*[1 << 30]*C.char)(unsafe.Pointer(csl))[:size:size]
+
+	*sl = make([]string, size)
+
+	for i, v := range list {
+		(*sl)[i] = C.GoString(v)
+	}
+
+	return nil
+}
+
+func (sl StringList) toC() (C.libxl_string_list, error) {
+	var char *C.char
+	size := len(sl)
+	csl := (C.libxl_string_list)(C.malloc(C.ulong(size) * C.ulong(unsafe.Sizeof(char))))
+	clist := (*[1 << 30]*C.char)(unsafe.Pointer(csl))[:size:size]
+
+	for i, v := range sl {
+		clist[i] = C.CString(v)
+	}
+
+	return csl, nil
+}
+
 // Bitmap represents a libxl_bitmap.
 //
 // Implement the Go bitmap type such that the underlying data can
Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#9 lore raw

PATCH v3 7/22 golang/xenlight: define Mac builtin type

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Define Mac as [6]byte and implement fromC, toC, and String functions.

---
Changes in v2:
- Fix the format string in String function to use %02x.
- Use a value reciever for the toC function. Changes in v3:
- Iterate over the indirect of mac instead of creating a slice from the C type.

---
 tools/golang/xenlight/xenlight.go | 33 +++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
tools/golang/xenlight/xenlight.go +33 -0
index 72afc3cf14..17d146771e 100644
@@ -181,6 +181,39 @@ func (d *Defbool) toC() (C.libxl_defbool, error) {
 	return c, nil
 }
 
+// Mac represents a libxl_mac, or simply a MAC address.
+type Mac [6]byte
+
+// String formats a Mac address to string representation.
+func (mac Mac) String() string {
+	s := "%02x:%02x:%02x:%02x:%02x:%02x"
+	opts := make([]interface{}, 6)
+
+	for i, v := range mac {
+		opts[i] = v
+	}
+
+	return fmt.Sprintf(s, opts...)
+}
+
+func (mac *Mac) fromC(cmac *C.libxl_mac) error {
+	for i := range *mac {
+		mac[i] = byte(cmac[i])
+	}
+
+	return nil
+}
+
+func (mac Mac) toC() (C.libxl_mac, error) {
+	var cmac C.libxl_mac
+
+	for i, v := range mac {
+		cmac[i] = C.uint8_t(v)
+	}
+
+	return cmac, nil
+}
+
 type Context struct {
 	ctx    *C.libxl_ctx
 	logger *C.xentoollog_logger_stdiostream
Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#10 lore raw

Re: [Xen-devel] [PATCH v3 07/22] golang/xenlight: define Mac builtin type

Quoted 34 lines · Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Define Mac as [6]byte and implement fromC, toC, and String functions.

---
Changes in v2:
- Fix the format string in String function to use %02x.
- Use a value reciever for the toC function. Changes in v3:
- Iterate over the indirect of mac instead of creating a slice from the C type.

---
 tools/golang/xenlight/xenlight.go | 33 +++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
tools/golang/xenlight/xenlight.go +9 -0
index 72afc3cf14..17d146771e 100644
@@ -181,6 +181,39 @@ func (d *Defbool) toC() (C.libxl_defbool, error) {
 	return c, nil
 }
 
+// Mac represents a libxl_mac, or simply a MAC address.
+type Mac [6]byte
+
+// String formats a Mac address to string representation.
+func (mac Mac) String() string {
+	s := "%02x:%02x:%02x:%02x:%02x:%02x"
+	opts := make([]interface{}, 6)
+
+	for i, v := range mac {

tools/golang/xenlight/xenlight.go func (d *Defbool) toC() (C.libxl_defbool, error) { · line 202

Quoted 10 lines
tools/golang/xenlight/xenlight.go +10 -0
+		opts[i] = v
+	}
+
+	return fmt.Sprintf(s, opts...)
+}
+
+func (mac *Mac) fromC(cmac *C.libxl_mac) error {
+	for i := range *mac {
+		mac[i] = byte(cmac[i])
+	}

That's much better, thanks.

-George

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#11 lore raw

PATCH v3 8/22 golang/xenlight: define MsVmGenid builtin type

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Define MsVmGenid as [int(C.LIBXL_MS_VM_GENID_LEN)]byte and implement fromC and toC functions.

---
Changes in v3:
- In fromC, iterate over the indirect of mvg instead of creating a slice from the C type.

---
 tools/golang/xenlight/xenlight.go | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
tools/golang/xenlight/xenlight.go +21 -0
index 17d146771e..6c3868cd69 100644
@@ -214,6 +214,27 @@ func (mac Mac) toC() (C.libxl_mac, error) {
 	return cmac, nil
 }
 
+// MsVmGenid represents a libxl_ms_vm_genid.
+type MsVmGenid [int(C.LIBXL_MS_VM_GENID_LEN)]byte
+
+func (mvg *MsVmGenid) fromC(cmvg *C.libxl_ms_vm_genid) error {
+	for i := range *mvg {
+		mvg[i] = byte(cmvg.bytes[i])
+	}
+
+	return nil
+}
+
+func (mvg *MsVmGenid) toC() (C.libxl_ms_vm_genid, error) {
+	var cmvg C.libxl_ms_vm_genid
+
+	for i, v := range mvg {
+		cmvg.bytes[i] = C.uint8_t(v)
+	}
+
+	return cmvg, nil
+}
+
 type Context struct {
 	ctx    *C.libxl_ctx
 	logger *C.xentoollog_logger_stdiostream
Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#12 lore raw

PATCH v3 9/22 golang/xenlight: define EvLink builtin as empty struct

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Define EvLink as empty struct as there is currently no reason the internal of this type should be used in Go.

Implement fromC and toC functions as no-ops.

---
 tools/golang/xenlight/xenlight.go | 10 ++++++++++
 1 file changed, 10 insertions(+)
tools/golang/xenlight/xenlight.go +10 -0
index 6c3868cd69..c1d9fe85fd 100644
@@ -235,6 +235,16 @@ func (mvg *MsVmGenid) toC() (C.libxl_ms_vm_genid, error) {
 	return cmvg, nil
 }
 
+// EvLink represents a libxl_ev_link.
+//
+// Represented as an empty struct for now, as there is no
+// apparent need for the internals of this type to be exposed
+// through the Go package.
+type EvLink struct{}
+
+func (el *EvLink) fromC(cel *C.libxl_ev_link) error      { return nil }
+func (el *EvLink) toC() (cel C.libxl_ev_link, err error) { return }
+
 type Context struct {
 	ctx    *C.libxl_ctx
 	logger *C.xentoollog_logger_stdiostream
Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#13 lore raw

PATCH v3 10/22 golang/xenlight: define CpuidPolicyList builtin type

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Define CpuidPolicyList as a string so that libxl_cpuid_parse_config can be used in the toC function.

For now, fromC is a no-op since libxl does not support a way to read a policy, modify it,and then give it back to libxl.

---
Changes in v2:
- Re-define CpuidPolicyList as string.
- Make fromC a no-op.
- Use libxl_cpuid_parse_config in toC function.

---
 tools/golang/xenlight/xenlight.go | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
tools/golang/xenlight/xenlight.go +25 -0
index c1d9fe85fd..6b87bf857d 100644
@@ -245,6 +245,31 @@ type EvLink struct{}
 func (el *EvLink) fromC(cel *C.libxl_ev_link) error      { return nil }
 func (el *EvLink) toC() (cel C.libxl_ev_link, err error) { return }
 
+// CpuidPolicyList represents a libxl_cpuid_policy_list.
+//
+// The value of CpuidPolicyList is honored when used as input to libxl. If
+// a struct contains a field of type CpuidPolicyList, that field will be left
+// empty when it is returned from libxl.
+type CpuidPolicyList string
+
+func (cpl CpuidPolicyList) fromC(ccpl *C.libxl_cpuid_policy_list) error { return nil }
+
+func (cpl CpuidPolicyList) toC() (C.libxl_cpuid_policy_list, error) {
+	var ccpl C.libxl_cpuid_policy_list
+
+	s := C.CString(string(cpl))
+	defer C.free(unsafe.Pointer(s))
+
+	ret := C.libxl_cpuid_parse_config(&ccpl, s)
+	if ret != 0 {
+		C.libxl_cpuid_dispose(&ccpl)
+
+		return ccpl, Error(-ret)
+	}
+
+	return ccpl, nil
+}
+
 type Context struct {
 	ctx    *C.libxl_ctx
 	logger *C.xentoollog_logger_stdiostream
Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#14 lore raw

PATCH v3 11/22 golang/xenlight: re-factor Uuid type implementation

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Re-define Uuid as [16]byte and implement fromC, toC, and String functions.

---
Changes in v3:
- In fromC, iterate over the indirect of u instead of creating a slice from the C type.

---
 tools/golang/xenlight/xenlight.go | 35 +++++++++++++++++++++++++++++--
 1 file changed, 33 insertions(+), 2 deletions(-)
tools/golang/xenlight/xenlight.go +33 -2
index 6b87bf857d..f9c2f84c81 100644
@@ -86,7 +86,38 @@ type Devid int
 
 type MemKB uint64
 
-type Uuid C.libxl_uuid
+// Uuid is a domain UUID.
+type Uuid [16]byte
+
+// String formats a Uuid in the form "xxxx-xx-xx-xx-xxxxxx".
+func (u Uuid) String() string {
+	s := "%x%x%x%x-%x%x-%x%x-%x%x-%x%x%x%x%x%x"
+	opts := make([]interface{}, 16)
+
+	for i, v := range u {
+		opts[i] = v
+	}
+
+	return fmt.Sprintf(s, opts...)
+}
+
+func (u *Uuid) fromC(c *C.libxl_uuid) error {
+	for i := range *u {
+		u[i] = byte(c.uuid[i])
+	}
+
+	return nil
+}
+
+func (u *Uuid) toC() (C.libxl_uuid, error) {
+	var c C.libxl_uuid
+
+	for i, v := range u {
+		c.uuid[i] = C.uint8_t(v)
+	}
+
+	return c, nil
+}
 
 // defboolVal represents a defbool value.
 type defboolVal int
@@ -495,7 +526,7 @@ type Dominfo struct {
 func (cdi *C.libxl_dominfo) toGo() (di *Dominfo) {
 
 	di = &Dominfo{}
-	di.Uuid = Uuid(cdi.uuid)
+	di.Uuid.fromC(&cdi.uuid)
 	di.Domid = Domid(cdi.domid)
 	di.Ssidref = uint32(cdi.ssidref)
 	di.SsidLabel = C.GoString(cdi.ssid_label)
Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
Reviewed-by on v3 11/22
#15 lore raw

Re: [Xen-devel] [PATCH v3 11/22] golang/xenlight: re-factor Uuid type implementation

Quoted 5 lines · Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Re-define Uuid as [16]byte and implement fromC, toC, and String functions.

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#16 lore raw

PATCH v3 12/22 golang/xenlight: re-factor Hwcap type implementation

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Re-define Hwcap as [8]uint32, and implement toC function. Also, re-name and modify signature of toGo function to fromC.

---
Changes in v2:
- Fix comment in fromC since an array is being used now, not a slice.
- Use a concise variable name instead of mapslice for the C array. Changes in v3:
- In fromC, iterate over the indirect of hwcap instead of creating a slice from the C type.

---
 tools/golang/xenlight/xenlight.go | 27 ++++++++++++++++-----------
 1 file changed, 16 insertions(+), 11 deletions(-)
tools/golang/xenlight/xenlight.go +16 -11
index f9c2f84c81..b395963512 100644
@@ -306,20 +306,25 @@ type Context struct {
 	logger *C.xentoollog_logger_stdiostream
 }
 
-type Hwcap []C.uint32_t
+// Hwcap represents a libxl_hwcap.
+type Hwcap [8]uint32
 
-func (chwcap C.libxl_hwcap) toGo() (ghwcap Hwcap) {
-	// Alloc a Go slice for the bytes
-	size := 8
-	ghwcap = make([]C.uint32_t, size)
+func (hwcap *Hwcap) fromC(chwcap *C.libxl_hwcap) error {
+	for i := range *hwcap {
+		hwcap[i] = uint32(chwcap[i])
+	}
 
-	// Make a slice pointing to the C array
-	mapslice := (*[1 << 30]C.uint32_t)(unsafe.Pointer(&chwcap[0]))[:size:size]
+	return nil
+}
 
-	// And copy the C array into the Go array
-	copy(ghwcap, mapslice)
+func (hwcap *Hwcap) toC() (C.libxl_hwcap, error) {
+	var chwcap C.libxl_hwcap
 
-	return
+	for i, v := range hwcap {
+		chwcap[i] = C.uint32_t(v)
+	}
+
+	return chwcap, nil
 }
 
 // KeyValueList represents a libxl_key_value_list.
@@ -442,7 +447,7 @@ func (cphys *C.libxl_physinfo) toGo() (physinfo *Physinfo) {
 	physinfo.SharingFreedPages = uint64(cphys.sharing_freed_pages)
 	physinfo.SharingUsedFrames = uint64(cphys.sharing_used_frames)
 	physinfo.NrNodes = uint32(cphys.nr_nodes)
-	physinfo.HwCap = cphys.hw_cap.toGo()
+	physinfo.HwCap.fromC(&cphys.hw_cap)
 	physinfo.CapHvm = bool(cphys.cap_hvm)
 	physinfo.CapHvmDirectio = bool(cphys.cap_hvm_directio)
 
Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#17 lore raw

PATCH v3 13/22 golang/xenlight: generate structs from the IDL

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Add struct and keyed union generation to gengotypes.py. For keyed unions, use a method similar to gRPC's oneof to interpret C unions as Go types. Meaning, for a given struct with a union field, generate a struct for each sub-struct defined in the union. Then, define an interface of one method which is implemented by each of the defined sub-structs. For example:

  type domainBuildInfoTypeUnion interface {
          isdomainBuildInfoTypeUnion()
  }

  type DomainBuildInfoTypeUnionHvm struct {
      // HVM-specific fields...
  }

func (x DomainBuildInfoTypeUnionHvm) isdomainBuildInfoTypeUnion() {}

  type DomainBuildInfoTypeUnionPv struct {
      // PV-specific fields...
  }

func (x DomainBuildInfoTypeUnionPv) isdomainBuildInfoTypeUnion() {}

  type DomainBuildInfoTypeUnionPvh struct {
      // PVH-specific fields...
  }

func (x DomainBuildInfoTypeUnionPvh) isdomainBuildInfoTypeUnion() {}

Then, remove existing struct definitions in xenlight.go that conflict with the generated types, and modify existing marshaling functions to align with the new type definitions. Notably, drop "time" package since fields of type time.Duration are now of type uint64.

---
Changes in v2:
- Do not use global variables for extra type definitions. Instead, return a tuple which includes a list of extra type definitions associated with the original type.
- Re-generate types.gen.go to include changes to libxl after rebase.

---
 tools/golang/xenlight/gengotypes.py | 119 +++-
 tools/golang/xenlight/types.gen.go  | 836 ++++++++++++++++++++++++++++
 tools/golang/xenlight/xenlight.go   | 123 +---
 3 files changed, 966 insertions(+), 112 deletions(-)
tools/golang/xenlight/gengotypes.py +115 -4
index 2211541547..8963b14eee 100644
@@ -32,18 +32,32 @@ def xenlight_golang_generate_types(path = None, types = None, comment = None):
         f.write('package xenlight\n')
 
         for ty in types:
-            f.write(xenlight_golang_type_define(ty))
+            (tdef, extras) = xenlight_golang_type_define(ty)
+
+            f.write(tdef)
             f.write('\n')
 
+            # Append extra types
+            for extra in extras:
+                f.write(extra)
+                f.write('\n')
+
     go_fmt(path)
 
 def xenlight_golang_type_define(ty = None):
-    s = ''
+    """
+    Generate the Go type definition of ty.
 
+    Return a tuple that contains a string with the
+    type definition, and a (potentially empty) list
+    of extra definitions that are associated with
+    this type.
+    """
     if isinstance(ty, idl.Enumeration):
-        s += xenlight_golang_define_enum(ty)
+        return (xenlight_golang_define_enum(ty), [])
 
-    return s
+    elif isinstance(ty, idl.Aggregate):
+        return xenlight_golang_define_struct(ty)
 
 def xenlight_golang_define_enum(ty = None):
     s = ''
@@ -65,6 +79,103 @@ def xenlight_golang_define_enum(ty = None):
 
     return s
 
+def xenlight_golang_define_struct(ty = None, typename = None, nested = False):
+    s = ''
+    extras = []
+    name = ''
+
+    if typename is not None:
+        name = xenlight_golang_fmt_name(typename)
+    else:
+        name = xenlight_golang_fmt_name(ty.typename)
+
+    # Begin struct definition
+    if nested:
+        s += '{} struct {{\n'.format(name)
+    else:
+        s += 'type {} struct {{\n'.format(name)
+
+    # Write struct fields
+    for f in ty.fields:
+        if f.type.typename is not None:
+            if isinstance(f.type, idl.Array):
+                typename = f.type.elem_type.typename
+                typename = xenlight_golang_fmt_name(typename)
+                name     = xenlight_golang_fmt_name(f.name)
+
+                s += '{} []{}\n'.format(name, typename)
+            else:
+                typename = f.type.typename
+                typename = xenlight_golang_fmt_name(typename)
+                name     = xenlight_golang_fmt_name(f.name)
+
+                s += '{} {}\n'.format(name, typename)
+
+        elif isinstance(f.type, idl.Struct):
+            r = xenlight_golang_define_struct(f.type, typename=f.name, nested=True)
+
+            s += r[0]
+            extras.extend(r[1])
+
+        elif isinstance(f.type, idl.KeyedUnion):
+            r = xenlight_golang_define_union(f.type, ty.typename)
+
+            s += r[0]
+            extras.extend(r[1])
+
+        else:
+            raise Exception('type {} not supported'.format(f.type))
+
+    # End struct definition
+    s += '}\n'
+
+    return (s,extras)
+
+def xenlight_golang_define_union(ty = None, structname = ''):
+    """
+    Generate the Go translation of a KeyedUnion.
+
+    Define an unexported interface to be used as
+    the type of the union. Then, define a struct
+    for each field of the union which implements
+    that interface.
+    """
+    s = ''
+    extras = []
+
+    interface_name = '{}_{}_union'.format(structname, ty.keyvar.name)
+    interface_name = xenlight_golang_fmt_name(interface_name, exported=False)
+
+    s += 'type {} interface {{\n'.format(interface_name)
+    s += 'is{}()\n'.format(interface_name)
+    s += '}\n'
+
+    extras.append(s)
+
+    for f in ty.fields:
+        if f.type is None:
+            continue
+
+        # Define struct
+        name = '{}_{}_union_{}'.format(structname, ty.keyvar.name, f.name)
+        r = xenlight_golang_define_struct(f.type, typename=name)
+        extras.append(r[0])
+        extras.extend(r[1])
+
+        # Define function to implement 'union' interface
+        name = xenlight_golang_fmt_name(name)
+        s = 'func (x {}) is{}(){{}}\n'.format(name, interface_name)
+        extras.append(s)
+
+    fname = xenlight_golang_fmt_name(ty.keyvar.name)
+    ftype = xenlight_golang_fmt_name(ty.keyvar.type.typename)
+    s = '{} {}\n'.format(fname, ftype)
+
+    fname = xenlight_golang_fmt_name('{}_union'.format(ty.keyvar.name))
+    s += '{} {}\n'.format(fname, interface_name)
+
+    return (s,extras)
+
 def xenlight_golang_fmt_name(name, exported = True):
     """
     Take a given type name and return an
tools/golang/xenlight/types.gen.go +836 -0

887 lines not on this page · raw message

tools/golang/xenlight/xenlight.go +15 -108

194 lines not on this page · raw message

Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#18 lore raw

PATCH v3 14/22 golang/xenlight: remove no-longer used type MemKB

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

---
 tools/golang/xenlight/xenlight.go | 2 --
 1 file changed, 2 deletions(-)
tools/golang/xenlight/xenlight.go +0 -2
index 8f41047726..fb1c6d9e51 100644
@@ -83,8 +83,6 @@ type Domid uint32
 // Devid is a device ID.
 type Devid int
 
-type MemKB uint64
-
 // Uuid is a domain UUID.
 type Uuid [16]byte
 
Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#19 lore raw

PATCH v3 15/22 golang/xenlight: begin C to Go type marshaling

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Begin implementation of fromC marshaling functions for generated struct types. This includes support for converting fields that are basic primitive types such as string and integer types, nested anonymous structs, nested libxl structs, and libxl built-in types.

This patch does not implement conversion of arrays or keyed unions.

---
Changes in v2:
- Add Makefile changes for helpers.gen.go.
- Re-generate helpers.gen.go to include libxl changes after rebase. Changes in v3:
- Break out field copying/type conversion code into its own function called xenlight_golang_convert_from_C to allow that code to be easily re-used.
- Use consistent style for calling fromC on struct fields that require it. Namely, do not use a temporary variable - call fromC directly on the struct field.

---
 tools/golang/xenlight/Makefile       |   2 +
 tools/golang/xenlight/gengotypes.py  | 118 ++++
 tools/golang/xenlight/helpers.gen.go | 901 +++++++++++++++++++++++++++
 tools/golang/xenlight/xenlight.go    | 111 +---
 4 files changed, 1032 insertions(+), 100 deletions(-)
 create mode 100644 tools/golang/xenlight/helpers.gen.go
tools/golang/xenlight/Makefile +2 -0
index 681f32c234..07b8896e5b 100644
@@ -19,6 +19,7 @@ $(XEN_GOPATH)/src/$(XEN_GOCODE_URL)/xenlight/: %.gen.go
 	$(INSTALL_DIR) $(XEN_GOPATH)$(GOXL_PKG_DIR)
 	$(INSTALL_DATA) xenlight.go $(XEN_GOPATH)$(GOXL_PKG_DIR)
 	$(INSTALL_DATA) types.gen.go $(XEN_GOPATH)$(GOXL_PKG_DIR)
+	$(INSTALL_DATA) helpers.gen.go $(XEN_GOPATH)$(GOXL_PKG_DIR)
 
 %.gen.go: gengotypes.py $(XEN_ROOT)/tools/libxl/libxl_types.idl $(XEN_ROOT)/tools/libxl/idl.py
 	XEN_ROOT=$(XEN_ROOT) $(PYTHON) gengotypes.py ../../libxl/libxl_types.idl
@@ -39,6 +40,7 @@ install: build
 	$(INSTALL_DIR) $(DESTDIR)$(GOXL_INSTALL_DIR)
 	$(INSTALL_DATA) $(XEN_GOPATH)$(GOXL_PKG_DIR)xenlight.go $(DESTDIR)$(GOXL_INSTALL_DIR)
 	$(INSTALL_DATA) $(XEN_GOPATH)$(GOXL_PKG_DIR)types.gen.go $(DESTDIR)$(GOXL_INSTALL_DIR)
+	$(INSTALL_DATA) $(XEN_GOPATH)$(GOXL_PKG_DIR)helpers.gen.go $(DESTDIR)$(GOXL_INSTALL_DIR)
 
 .PHONY: uninstall
 	rm -rf $(DESTDIR)$(GOXL_INSTALL_DIR)
tools/golang/xenlight/gengotypes.py +118 -0

133 lines not on this page · raw message

tools/golang/xenlight/helpers.gen.go new file +901 -0

901 lines not on this page · raw message

tools/golang/xenlight/xenlight.go +11 -100

176 lines not on this page · raw message

Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
Reviewed-by on v3 15/22
#20 lore raw

Re: [Xen-devel] [PATCH v3 15/22] golang/xenlight: begin C to Go type marshaling

Quoted 10 lines · Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Begin implementation of fromC marshaling functions for generated struct types. This includes support for converting fields that are basic primitive types such as string and integer types, nested anonymous structs, nested libxl structs, and libxl built-in types.

This patch does not implement conversion of arrays or keyed unions.

Quoted 11 lines

---
Changes in v2:
- Add Makefile changes for helpers.gen.go.
- Re-generate helpers.gen.go to include libxl changes after rebase. Changes in v3:
- Break out field copying/type conversion code into its own function called xenlight_golang_convert_from_C to allow that code to be easily re-used.
- Use consistent style for calling fromC on struct fields that require it. Namely, do not use a temporary variable - call fromC directly on the struct field.

Looks good! One minor comment...

Quoted 13 lines
---
 tools/golang/xenlight/Makefile       |   2 +
 tools/golang/xenlight/gengotypes.py  | 118 ++++
 tools/golang/xenlight/helpers.gen.go | 901 +++++++++++++++++++++++++++
 tools/golang/xenlight/xenlight.go    | 111 +---
 4 files changed, 1032 insertions(+), 100 deletions(-)
 create mode 100644 tools/golang/xenlight/helpers.gen.go
tools/golang/xenlight/Makefile +0 -0
index 681f32c234..07b8896e5b 100644

tools/golang/xenlight/Makefile $(XEN_GOPATH)/src/$(XEN_GOCODE_URL)/xenlight/: %.gen.go · line 22

Quoted 4 lines
tools/golang/xenlight/Makefile +1 -0
@@ -19,6 +19,7 @@ $(XEN_GOPATH)/src/$(XEN_GOCODE_URL)/xenlight/: %.gen.go
 	$(INSTALL_DIR) $(XEN_GOPATH)$(GOXL_PKG_DIR)
 	$(INSTALL_DATA) xenlight.go $(XEN_GOPATH)$(GOXL_PKG_DIR)
 	$(INSTALL_DATA) types.gen.go $(XEN_GOPATH)$(GOXL_PKG_DIR)
+	$(INSTALL_DATA) helpers.gen.go $(XEN_GOPATH)$(GOXL_PKG_DIR)

I'll have to edit this stanza on check-in to depend on helpers.gen.go directly; with that:

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#21 lore raw

PATCH v3 16/22 golang/xenlight: implement keyed union C to Go marshaling

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Switch over union key to determine how to populate 'union' in Go struct.

Since the unions of C types cannot be directly accessed in cgo, use a typeof trick to typedef a struct in the cgo preamble that is analagous to each inner struct of a keyed union. For example, to define a struct for the hvm inner struct of libxl_domain_build_info, do:

  typedef typeof(((struct libxl_domain_build_info *)NULL)->u.hvm) libxl_domain_build_info_type_union_hvm;

---
Changes in v2:
- Do not use global variable for extra helper function definitions. Instead, return a tuple which contains a list of extra helper functions associated with the original.
Changes in v3:
- Use the new xenlight_golang_convert_from_C function for field copying/ type conversion.
- Use a typeof trick in the cgo preamble to define structs for the inner struct of keyed unions, instead of explicitly defining the fields.

---
 tools/golang/xenlight/gengotypes.py  | 129 +++++++++-
 tools/golang/xenlight/helpers.gen.go | 346 +++++++++++++++++++++++++++
 2 files changed, 464 insertions(+), 11 deletions(-)
tools/golang/xenlight/gengotypes.py +118 -11
index 1fe56179e2..b68c1aa66b 100644
@@ -24,6 +24,10 @@ go_keywords = ['type', 'func']
 go_builtin_types = ['bool', 'string', 'int', 'byte',
                     'uint16', 'uint32', 'uint64']
 
+# cgo preamble for xenlight_helpers.go, created during type generation and
+# written later.
+cgo_helpers_preamble = []
+
 def xenlight_golang_generate_types(path = None, types = None, comment = None):
     """
     Generate a .go file (types.gen.go by default)
@@ -124,7 +128,7 @@ def xenlight_golang_define_struct(ty = None, typename = None, nested = False):
             extras.extend(r[1])
 
         elif isinstance(f.type, idl.KeyedUnion):
-            r = xenlight_golang_define_union(f.type, ty.typename)
+            r = xenlight_golang_define_union(f.type, ty.typename, f.name)
 
             s += r[0]
             extras.extend(r[1])
@@ -137,7 +141,7 @@ def xenlight_golang_define_struct(ty = None, typename = None, nested = False):
 
     return (s,extras)
 
-def xenlight_golang_define_union(ty = None, structname = ''):
+def xenlight_golang_define_union(ty = None, struct_name = '', union_name = ''):
     """
     Generate the Go translation of a KeyedUnion.
 
@@ -149,7 +153,7 @@ def xenlight_golang_define_union(ty = None, structname = ''):
     s = ''
     extras = []
 
-    interface_name = '{}_{}_union'.format(structname, ty.keyvar.name)
+    interface_name = '{}_{}_union'.format(struct_name, ty.keyvar.name)
     interface_name = xenlight_golang_fmt_name(interface_name, exported=False)
 
     s += 'type {} interface {{\n'.format(interface_name)
@@ -163,11 +167,18 @@ def xenlight_golang_define_union(ty = None, structname = ''):
             continue
 
         # Define struct
-        name = '{}_{}_union_{}'.format(structname, ty.keyvar.name, f.name)
+        name = '{}_{}_union_{}'.format(struct_name, ty.keyvar.name, f.name)
         r = xenlight_golang_define_struct(f.type, typename=name)
         extras.append(r[0])
         extras.extend(r[1])
 
+        # This typeof trick ensures that the fields used in the cgo struct
+        # used for marshaling are the same as the fields of the union in the
+        # actual C type, and avoids re-defining all of those fields.
+        s = 'typedef typeof(((struct {} *)NULL)->{}.{}){};'
+        s = s.format(struct_name, union_name, f.name, name)
+        cgo_helpers_preamble.append(s)
+
         # Define function to implement 'union' interface
         name = xenlight_golang_fmt_name(name)
         s = 'func (x {}) is{}(){{}}\n'.format(name, interface_name)
@@ -195,6 +206,7 @@ def xenlight_golang_generate_helpers(path = None, types = None, comment = None):
         if comment is not None:
             f.write(comment)
         f.write('package xenlight\n')
+        f.write('import (\n"unsafe"\n"errors"\n"fmt"\n)\n')
 
         # Cgo preamble
         f.write('/*\n')
@@ -203,15 +215,25 @@ def xenlight_golang_generate_helpers(path = None, types = None, comment = None):
         f.write('#include <libxl.h>\n')
         f.write('\n')
 
+        for s in cgo_helpers_preamble:
+            f.write(s)
+            f.write('\n')
+
         f.write('*/\nimport "C"\n')
 
         for ty in types:
             if not isinstance(ty, idl.Struct):
                 continue
 
-            f.write(xenlight_golang_define_from_C(ty))
+            (fdef, extras) = xenlight_golang_define_from_C(ty)
+
+            f.write(fdef)
             f.write('\n')
 
+            for extra in extras:
+                f.write(extra)
+                f.write('\n')
+
     go_fmt(path)
 
 def xenlight_golang_define_from_C(ty = None):
@@ -225,6 +247,7 @@ def xenlight_golang_define_from_C(ty = None):
     cname  = ty.typename
 
     body = ''
+    extras = []
 
     for f in ty.fields:
         if f.type.typename is not None:
@@ -240,14 +263,17 @@ def xenlight_golang_define_from_C(ty = None):
                 body += xenlight_golang_convert_from_C(nf,outer_name=f.name)
 
         elif isinstance(f.type, idl.KeyedUnion):
-            pass
+            r = xenlight_golang_union_from_C(f.type, f.name, ty.typename)
+
+            body += r[0]
+            extras.extend(r[1])
 
         else:
             raise Exception('type {} not supported'.format(f.type))
 
-    return func.format(goname, cname, body)
+    return (func.format(goname, cname, body), extras)
 
-def xenlight_golang_convert_from_C(ty = None, outer_name = None):
+def xenlight_golang_convert_from_C(ty = None, outer_name = None, cvarname = None):
     """
     Returns a line of Go code that converts the C type represented
     by ty to its corresponding Go type.
@@ -257,6 +283,10 @@ def xenlight_golang_convert_from_C(ty = None, outer_name = None):
     """
     s = ''
 
+    # Use 'xc' as the name for the C variable unless otherwise specified
+    if cvarname is None:
+        cvarname = 'xc'
+
     gotypename = xenlight_golang_fmt_name(ty.type.typename)
     goname     = xenlight_golang_fmt_name(ty.name)
     cname      = ty.name
@@ -280,18 +310,95 @@ def xenlight_golang_convert_from_C(ty = None, outer_name = None):
     if not is_castable:
         # If the type is not castable, we need to call its fromC
         # function.
-        s += 'if err := x.{}.fromC(&xc.{});'.format(goname,cname)
+        s += 'if err := x.{}.fromC(&{}.{});'.format(goname,cvarname,cname)
         s += 'err != nil {\n return err \n}\n'
 
     elif gotypename == 'string':
         # Use the cgo helper for converting C strings.
-        s += 'x.{} = C.GoString(xc.{})\n'.format(goname, cname)
+        s += 'x.{} = C.GoString({}.{})\n'.format(goname,cvarname,cname)
 
     else:
-        s += 'x.{} = {}(xc.{})\n'.format(goname, gotypename, cname)
+        s += 'x.{} = {}({}.{})\n'.format(goname,gotypename,cvarname,cname)
 
     return s
 
+def xenlight_golang_union_from_C(ty = None, union_name = '', struct_name = ''):
+    extras = []
+
+    keyname   = ty.keyvar.name
+    gokeyname = xenlight_golang_fmt_name(keyname)
+    keytype   = ty.keyvar.type.typename
+    gokeytype = xenlight_golang_fmt_name(keytype)
+
+    interface_name = '{}_{}_union'.format(struct_name, keyname)
+    interface_name = xenlight_golang_fmt_name(interface_name, exported=False)
+
+    cgo_keyname = keyname
+    if cgo_keyname in go_keywords:
+        cgo_keyname = '_' + cgo_keyname
+
+    cases = {}
+
+    for f in ty.fields:
+        val = '{}_{}'.format(keytype, f.name)
+        val = xenlight_golang_fmt_name(val)
+
+        # Add to list of cases to make for the switch
+        # statement below.
+        if f.type is None:
+            continue
+
+        cases[f.name] = val
+
+        # Define fromC func for 'union' struct.
+        typename   = '{}_{}_union_{}'.format(struct_name,keyname,f.name)
+        gotypename = xenlight_golang_fmt_name(typename)
+
+        # Define the function here. The cases for keyed unions are a little
+        # different.
+        s = 'func (x *{}) fromC(xc *C.{}) error {{\n'.format(gotypename,struct_name)
+        s += 'if {}(xc.{}) != {} {{\n'.format(gokeytype,cgo_keyname,val)
+        err_string = '"expected union key {}"'.format(val)
+        s += 'return errors.New({})\n'.format(err_string)
+        s += '}\n\n'
+        s += 'tmp := (*C.{})(unsafe.Pointer(&xc.{}[0]))\n'.format(typename,union_name)
+
+        for nf in f.type.fields:
+            s += xenlight_golang_convert_from_C(nf,cvarname='tmp')
+
+        s += 'return nil\n'
+        s += '}\n'
+
+        extras.append(s)
+
+    s = 'x.{} = {}(xc.{})\n'.format(gokeyname,gokeytype,cgo_keyname)
+    s += 'switch x.{}{{\n'.format(gokeyname)
+
+    # Create switch statement to determine which 'union element'
+    # to populate in the Go struct.
+    for case_name, case_val in cases.items():
+        s += 'case {}:\n'.format(case_val)
+
+        gotype = '{}_{}_union_{}'.format(struct_name,keyname,case_name)
+        gotype = xenlight_golang_fmt_name(gotype)
+        goname = '{}_{}'.format(keyname,case_name)
+        goname = xenlight_golang_fmt_name(goname,exported=False)
+
+        s += 'var {} {}\n'.format(goname, gotype)
+        s += 'if err := {}.fromC(xc);'.format(goname)
+        s += 'err != nil {\n return err \n}\n'
+
+        field_name = xenlight_golang_fmt_name('{}_union'.format(keyname))
+        s += 'x.{} = {}\n'.format(field_name, goname)
+
+    # End switch statement
+    s += 'default:\n'
+    err_string = '"invalid union key \'%v\'", x.{}'.format(gokeyname)
+    s += 'return fmt.Errorf({})'.format(err_string)
+    s += '}\n'
+
+    return (s,extras)
+
 def xenlight_golang_fmt_name(name, exported = True):
     """
     Take a given type name and return an
tools/golang/xenlight/helpers.gen.go +346 -0

406 lines not on this page · raw message

Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
Reviewed-by on v3 16/22
#22 lore raw

Re: [Xen-devel] [PATCH v3 16/22] golang/xenlight: implement keyed union C to Go marshaling

Quoted 4 lines · Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Switch over union key to determine how to populate 'union' in Go struct.

Quoted 8 lines

Since the unions of C types cannot be directly accessed in cgo, use a typeof trick to typedef a struct in the cgo preamble that is analagous to each inner struct of a keyed union. For example, to define a struct for the hvm inner struct of libxl_domain_build_info, do:

  typedef typeof(((struct libxl_domain_build_info *)NULL)->u.hvm) libxl_domain_build_info_type_union_hvm;

Looks great, thanks:

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#23 lore raw

PATCH v3 17/22 golang/xenlight: implement array C to Go marshaling

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

---
 tools/golang/xenlight/gengotypes.py  |  39 +++-
 tools/golang/xenlight/helpers.gen.go | 300 +++++++++++++++++++++++++++
 2 files changed, 338 insertions(+), 1 deletion(-)
tools/golang/xenlight/gengotypes.py +38 -1
index b68c1aa66b..ee9aaf9eff 100644
@@ -252,7 +252,7 @@ def xenlight_golang_define_from_C(ty = None):
     for f in ty.fields:
         if f.type.typename is not None:
             if isinstance(f.type, idl.Array):
-                # TODO
+                body += xenlight_golang_array_from_C(f)
                 continue
 
             body += xenlight_golang_convert_from_C(f)
@@ -399,6 +399,43 @@ def xenlight_golang_union_from_C(ty = None, union_name = '', struct_name = ''):
 
     return (s,extras)
 
+def xenlight_golang_array_from_C(ty = None):
+    """
+    Convert C array to Go slice using the method
+    described here:
+
+    https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
+    """
+    s = ''
+
+    gotypename = xenlight_golang_fmt_name(ty.type.elem_type.typename)
+    goname     = xenlight_golang_fmt_name(ty.name)
+    ctypename  = ty.type.elem_type.typename
+    cname      = ty.name
+    cslice     = 'c{}'.format(goname)
+    clenvar    = ty.type.lenvar.name
+    golenvar   = xenlight_golang_fmt_name(clenvar,exported=False)
+
+    s += '{} := int(xc.{})\n'.format(golenvar, clenvar)
+    s += '{} := '.format(cslice)
+    s +='(*[1<<28]C.{})(unsafe.Pointer(xc.{}))[:{}:{}]\n'.format(ctypename, cname,
+                                                                golenvar, golenvar)
+    s += 'x.{} = make([]{}, {})\n'.format(goname, gotypename, golenvar)
+    s += 'for i, v := range {} {{\n'.format(cslice)
+
+    is_enum = isinstance(ty.type.elem_type,idl.Enumeration)
+    if gotypename in go_builtin_types or is_enum:
+        s += 'x.{}[i] = {}(v)\n'.format(goname, gotypename)
+    else:
+        s += 'var e {}\n'.format(gotypename)
+        s += 'if err := e.fromC(&v); err != nil {\n'
+        s += 'return err }\n'
+        s += 'x.{}[i] = e\n'.format(goname)
+
+    s += '}\n'
+
+    return s
+
 def xenlight_golang_fmt_name(name, exported = True):
     """
     Take a given type name and return an
tools/golang/xenlight/helpers.gen.go +300 -0

383 lines not on this page · raw message

Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#24 lore raw

Re: [Xen-devel] [PATCH v3 17/22] golang/xenlight: implement array C to Go marshaling

Quoted 72 lines · Nick Rosbrook

From: Nick Rosbrook <[email protected]>

---
 tools/golang/xenlight/gengotypes.py  |  39 +++-
 tools/golang/xenlight/helpers.gen.go | 300 +++++++++++++++++++++++++++
 2 files changed, 338 insertions(+), 1 deletion(-)
tools/golang/xenlight/gengotypes.py +38 -1
index b68c1aa66b..ee9aaf9eff 100644
@@ -252,7 +252,7 @@ def xenlight_golang_define_from_C(ty = None):
     for f in ty.fields:
         if f.type.typename is not None:
             if isinstance(f.type, idl.Array):
-                # TODO
+                body += xenlight_golang_array_from_C(f)
                 continue
 
             body += xenlight_golang_convert_from_C(f)
@@ -399,6 +399,43 @@ def xenlight_golang_union_from_C(ty = None, union_name = '', struct_name = ''):
 
     return (s,extras)
 
+def xenlight_golang_array_from_C(ty = None):
+    """
+    Convert C array to Go slice using the method
+    described here:
+
+    https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
+    """
+    s = ''
+
+    gotypename = xenlight_golang_fmt_name(ty.type.elem_type.typename)
+    goname     = xenlight_golang_fmt_name(ty.name)
+    ctypename  = ty.type.elem_type.typename
+    cname      = ty.name
+    cslice     = 'c{}'.format(goname)
+    clenvar    = ty.type.lenvar.name
+    golenvar   = xenlight_golang_fmt_name(clenvar,exported=False)
+
+    s += '{} := int(xc.{})\n'.format(golenvar, clenvar)
+    s += '{} := '.format(cslice)
+    s +='(*[1<<28]C.{})(unsafe.Pointer(xc.{}))[:{}:{}]\n'.format(ctypename, cname,
+                                                                golenvar, golenvar)
+    s += 'x.{} = make([]{}, {})\n'.format(goname, gotypename, golenvar)
+    s += 'for i, v := range {} {{\n'.format(cslice)
+
+    is_enum = isinstance(ty.type.elem_type,idl.Enumeration)
+    if gotypename in go_builtin_types or is_enum:
+        s += 'x.{}[i] = {}(v)\n'.format(goname, gotypename)
+    else:
+        s += 'var e {}\n'.format(gotypename)
+        s += 'if err := e.fromC(&v); err != nil {\n'
+        s += 'return err }\n'
+        s += 'x.{}[i] = e\n'.format(goname)
+
+    s += '}\n'
+
+    return s
+
 def xenlight_golang_fmt_name(name, exported = True):
     """
     Take a given type name and return an
tools/golang/xenlight/helpers.gen.go +0 -0
index e6eee234c0..2f917cac58 100644
@@ -263,6 +263,16 @@ func (x *SchedParams) fromC(xc *C.libxl_sched_params) error {
 
 func (x *VcpuSchedParams) fromC(xc *C.libxl_vcpu_sched_params) error {

tools/golang/xenlight/helpers.gen.go func (x *SchedParams) fromC(xc *C.libxl_sched_params) error { · line 274

Quoted 10 lines
tools/golang/xenlight/helpers.gen.go +9 -0
 	x.Sched = Scheduler(xc.sched)
+	numVcpus := int(xc.num_vcpus)
+	cVcpus := (*[1 << 28]C.libxl_sched_params)(unsafe.Pointer(xc.vcpus))[:numVcpus:numVcpus]
+	x.Vcpus = make([]SchedParams, numVcpus)
+	for i, v := range cVcpus {
+		var e SchedParams
+		if err := e.fromC(&v); err != nil {
+			return err
+		}
+		x.Vcpus[i] = e

Along the same lines, any reason not to do the following?

    if err := x.Vcpus[i].fromC(&v); err != nil {
        return err
    }

Everything else looks good.

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#25 lore raw

Re: [Xen-devel] [PATCH v3 17/22] golang/xenlight: implement array C to Go marshaling

Quoted 87 lines · George Dunlap
Quoted 72 lines · Nick Rosbrook

From: Nick Rosbrook <[email protected]>

---
 tools/golang/xenlight/gengotypes.py  |  39 +++-
 tools/golang/xenlight/helpers.gen.go | 300 +++++++++++++++++++++++++++
 2 files changed, 338 insertions(+), 1 deletion(-)
tools/golang/xenlight/gengotypes.py +38 -1
index b68c1aa66b..ee9aaf9eff 100644
@@ -252,7 +252,7 @@ def xenlight_golang_define_from_C(ty = None):
     for f in ty.fields:
         if f.type.typename is not None:
             if isinstance(f.type, idl.Array):
-                # TODO
+                body += xenlight_golang_array_from_C(f)
                 continue
 
             body += xenlight_golang_convert_from_C(f)
@@ -399,6 +399,43 @@ def xenlight_golang_union_from_C(ty = None, union_name = '', struct_name = ''):
 
     return (s,extras)
 
+def xenlight_golang_array_from_C(ty = None):
+    """
+    Convert C array to Go slice using the method
+    described here:
+
+    https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
+    """
+    s = ''
+
+    gotypename = xenlight_golang_fmt_name(ty.type.elem_type.typename)
+    goname     = xenlight_golang_fmt_name(ty.name)
+    ctypename  = ty.type.elem_type.typename
+    cname      = ty.name
+    cslice     = 'c{}'.format(goname)
+    clenvar    = ty.type.lenvar.name
+    golenvar   = xenlight_golang_fmt_name(clenvar,exported=False)
+
+    s += '{} := int(xc.{})\n'.format(golenvar, clenvar)
+    s += '{} := '.format(cslice)
+    s +='(*[1<<28]C.{})(unsafe.Pointer(xc.{}))[:{}:{}]\n'.format(ctypename, cname,
+                                                                golenvar, golenvar)
+    s += 'x.{} = make([]{}, {})\n'.format(goname, gotypename, golenvar)
+    s += 'for i, v := range {} {{\n'.format(cslice)
+
+    is_enum = isinstance(ty.type.elem_type,idl.Enumeration)
+    if gotypename in go_builtin_types or is_enum:
+        s += 'x.{}[i] = {}(v)\n'.format(goname, gotypename)
+    else:
+        s += 'var e {}\n'.format(gotypename)
+        s += 'if err := e.fromC(&v); err != nil {\n'
+        s += 'return err }\n'
+        s += 'x.{}[i] = e\n'.format(goname)
+
+    s += '}\n'
+
+    return s
+
 def xenlight_golang_fmt_name(name, exported = True):
     """
     Take a given type name and return an
tools/golang/xenlight/helpers.gen.go +0 -0
index e6eee234c0..2f917cac58 100644
@@ -263,6 +263,16 @@ func (x *SchedParams) fromC(xc *C.libxl_sched_params) error {
 
 func (x *VcpuSchedParams) fromC(xc *C.libxl_vcpu_sched_params) error {

tools/golang/xenlight/helpers.gen.go func (x *SchedParams) fromC(xc *C.libxl_sched_params) error { · line 274

Quoted 10 lines
tools/golang/xenlight/helpers.gen.go +9 -0
      x.Sched = Scheduler(xc.sched)
+     numVcpus := int(xc.num_vcpus)
+     cVcpus := (*[1 << 28]C.libxl_sched_params)(unsafe.Pointer(xc.vcpus))[:numVcpus:numVcpus]
+     x.Vcpus = make([]SchedParams, numVcpus)
+     for i, v := range cVcpus {
+             var e SchedParams
+             if err := e.fromC(&v); err != nil {
+                     return err
+             }
+             x.Vcpus[i] = e

Along the same lines, any reason not to do the following?

Quoted 3 lines
    if err := x.Vcpus[i].fromC(&v); err != nil {
        return err
    }

Nope, no problem with that.

Thanks,
-NR

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#26 lore raw

PATCH v3 18/22 golang/xenlight: begin Go to C type marshaling

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Implement conversion of basic type conversions such as strings and integer types in toC functions.

---
 tools/golang/xenlight/gengotypes.py  |   80 ++
 tools/golang/xenlight/helpers.gen.go | 1015 ++++++++++++++++++++++++++
 2 files changed, 1095 insertions(+)
tools/golang/xenlight/gengotypes.py +80 -0
index ee9aaf9eff..cb9b18218f 100644
@@ -234,6 +234,9 @@ def xenlight_golang_generate_helpers(path = None, types = None, comment = None):
                 f.write(extra)
                 f.write('\n')
 
+            f.write(xenlight_golang_define_to_C(ty))
+            f.write('\n')
+
     go_fmt(path)
 
 def xenlight_golang_define_from_C(ty = None):
@@ -436,6 +439,83 @@ def xenlight_golang_array_from_C(ty = None):
 
     return s
 
+def xenlight_golang_define_to_C(ty = None, typename = None, nested = False):
+    s = ''
+
+    gotypename = ctypename = ''
+
+    if typename is not None:
+        gotypename = xenlight_golang_fmt_name(typename)
+        ctypename  = typename
+    else:
+        gotypename = xenlight_golang_fmt_name(ty.typename)
+        ctypename  = ty.typename
+
+    if not nested:
+        s += 'func (x *{}) toC() (xc C.{},err error) {{\n'.format(gotypename,ctypename)
+        s += 'C.{}(&xc)\n'.format(ty.init_fn)
+
+    for f in ty.fields:
+        if f.type.typename is not None:
+            if isinstance(f.type, idl.Array):
+                # TODO
+                continue
+
+            gotypename = xenlight_golang_fmt_name(f.type.typename)
+            ctypename  = f.type.typename
+            gofname    = xenlight_golang_fmt_name(f.name)
+            cfname     = f.name
+
+            # In cgo, C names that conflict with Go keywords can be
+            # accessed by prepending an underscore to the name.
+            if cfname in go_keywords:
+                cfname = '_' + cfname
+
+            # If this is nested, we need the outer name too.
+            if nested and typename is not None:
+                goname = xenlight_golang_fmt_name(typename)
+                goname = '{}.{}'.format(goname, gofname)
+                cname  = '{}.{}'.format(typename, cfname)
+
+            else:
+                goname = gofname
+                cname  = cfname
+
+            is_castable = (f.type.json_parse_type == 'JSON_INTEGER' or
+                           isinstance(f.type, idl.Enumeration) or
+                           gotypename in go_builtin_types)
+
+            if is_castable:
+                # Use the cgo helper for converting C strings.
+                if gotypename == 'string':
+                    s += 'xc.{} = C.CString(x.{})\n'.format(cname,goname)
+                    continue
+
+                s += 'xc.{} = C.{}(x.{})\n'.format(cname,ctypename,goname)
+
+            else:
+                s += 'xc.{}, err = x.{}.toC()\n'.format(cname,goname)
+                s += 'if err != nil {\n'
+                s += 'C.{}(&xc)\n'.format(ty.dispose_fn)
+                s += 'return xc, err\n'
+                s += '}\n'
+
+        elif isinstance(f.type, idl.Struct):
+            s += xenlight_golang_define_to_C(f.type, typename=f.name, nested=True)
+
+        elif isinstance(f.type, idl.KeyedUnion):
+            # TODO
+            pass
+
+        else:
+            raise Exception('type {} not supported'.format(f.type))
+
+    if not nested:
+        s += 'return xc, nil'
+        s += '}\n'
+
+    return s
+
 def xenlight_golang_fmt_name(name, exported = True):
     """
     Take a given type name and return an
tools/golang/xenlight/helpers.gen.go +1015 -0

1,372 lines not on this page · raw message

Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#27 lore raw

PATCH v3 19/22 golang/xenlight: implement keyed union Go to C marshaling

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Since the C union cannot be directly populated, populate the fields of the corresponding C struct defined in the cgo preamble, and then copy that struct as bytes into the byte slice that Go uses as the union.

---
 tools/golang/xenlight/gengotypes.py  |  77 ++++++-
 tools/golang/xenlight/helpers.gen.go | 325 +++++++++++++++++++++++++++
 2 files changed, 400 insertions(+), 2 deletions(-)
tools/golang/xenlight/gengotypes.py +75 -2
index cb9b18218f..1839ac14b6 100644
@@ -504,8 +504,7 @@ def xenlight_golang_define_to_C(ty = None, typename = None, nested = False):
             s += xenlight_golang_define_to_C(f.type, typename=f.name, nested=True)
 
         elif isinstance(f.type, idl.KeyedUnion):
-            # TODO
-            pass
+            s += xenlight_golang_union_to_C(f.type, f.name, ty.typename, ty.dispose_fn)
 
         else:
             raise Exception('type {} not supported'.format(f.type))
@@ -516,6 +515,80 @@ def xenlight_golang_define_to_C(ty = None, typename = None, nested = False):
 
     return s
 
+def xenlight_golang_union_to_C(ty = None, union_name = '',
+                               struct_name = '', dispose_fn = ''):
+    keyname   = ty.keyvar.name
+    gokeyname = xenlight_golang_fmt_name(keyname)
+    keytype   = ty.keyvar.type.typename
+    gokeytype = xenlight_golang_fmt_name(keytype)
+
+    interface_name = '{}_{}_union'.format(struct_name, keyname)
+    interface_name = xenlight_golang_fmt_name(interface_name, exported=False)
+
+    cgo_keyname = keyname
+    if cgo_keyname in go_keywords:
+        cgo_keyname = '_' + cgo_keyname
+
+
+    s = 'xc.{} = C.{}(x.{})\n'.format(cgo_keyname,keytype,gokeyname)
+    s += 'switch x.{}{{\n'.format(gokeyname)
+
+    # Create switch statement to determine how to populate the C union.
+    for f in ty.fields:
+        key_val = '{}_{}'.format(keytype, f.name)
+        key_val = xenlight_golang_fmt_name(key_val)
+        if f.type is None:
+            continue
+
+        s += 'case {}:\n'.format(key_val)
+        cgotype = '{}_{}_union_{}'.format(struct_name,keyname,f.name)
+        gotype  = xenlight_golang_fmt_name(cgotype)
+        goname  = '{}_{}'.format(keyname,f.name)
+        goname  = xenlight_golang_fmt_name(goname,exported=False)
+
+        field_name = xenlight_golang_fmt_name('{}_union'.format(keyname))
+        s += 'tmp, ok := x.{}.({})\n'.format(field_name,gotype)
+        s += 'if !ok {\n'
+        s += 'C.{}(&xc)\n'.format(dispose_fn)
+        s += 'return xc,errors.New("wrong type for union key {}")\n'.format(keyname)
+        s += '}\n'
+
+        s += 'var {} C.{}\n'.format(f.name,cgotype)
+        for uf in f.type.fields:
+            gotypename = xenlight_golang_fmt_name(uf.type.typename)
+            ctypename  = uf.type.typename
+            gofname    = xenlight_golang_fmt_name(uf.name)
+
+            is_castable = (uf.type.json_parse_type == 'JSON_INTEGER' or
+                           isinstance(uf.type, idl.Enumeration) or
+                           gotypename in go_builtin_types)
+
+            if not is_castable:
+                s += '{}.{}, err = tmp.{}.toC()\n'.format(f.name,uf.name,gofname)
+                s += 'if err != nil {\n'
+                s += 'C.{}(&xc)\n'.format(dispose_fn)
+                s += 'return xc,err \n}\n'
+
+            elif gotypename == 'string':
+                s += '{}.{} = C.CString(tmp.{})\n'.format(f.name,uf.name,gofname)
+
+            else:
+                s += '{}.{} = C.{}(tmp.{})\n'.format(f.name,uf.name,ctypename,gofname)
+
+        # The union is still represented as Go []byte.
+        s += '{}Bytes := C.GoBytes(unsafe.Pointer(&{}),C.sizeof_{})\n'.format(f.name,
+                                                                              f.name,
+                                                                              cgotype)
+        s += 'copy(xc.{}[:],{}Bytes)\n'.format(union_name,f.name)
+
+    # End switch statement
+    s += 'default:\n'
+    err_string = '"invalid union key \'%v\'", x.{}'.format(gokeyname)
+    s += 'return xc, fmt.Errorf({})'.format(err_string)
+    s += '}\n'
+
+    return s
+
 def xenlight_golang_fmt_name(name, exported = True):
     """
     Take a given type name and return an
tools/golang/xenlight/helpers.gen.go +325 -0

360 lines not on this page · raw message

Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#28 lore raw

PATCH v3 20/22 golang/xenlight: implement array Go to C marshaling

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

---
 tools/golang/xenlight/gengotypes.py  |  44 +++-
 tools/golang/xenlight/helpers.gen.go | 359 +++++++++++++++++++++++++++
 2 files changed, 402 insertions(+), 1 deletion(-)
tools/golang/xenlight/gengotypes.py +43 -1
index 1839ac14b6..24d27e30ad 100644
@@ -458,7 +458,7 @@ def xenlight_golang_define_to_C(ty = None, typename = None, nested = False):
     for f in ty.fields:
         if f.type.typename is not None:
             if isinstance(f.type, idl.Array):
-                # TODO
+                s += xenlight_golang_array_to_C(f, ty.dispose_fn)
                 continue
 
             gotypename = xenlight_golang_fmt_name(f.type.typename)
@@ -589,6 +589,48 @@ def xenlight_golang_union_to_C(ty = None, union_name = '',
 
     return s
 
+def xenlight_golang_array_to_C(ty = None, dispose_fn = ''):
+    s = ''
+
+    gotypename = xenlight_golang_fmt_name(ty.type.elem_type.typename)
+    goname     = xenlight_golang_fmt_name(ty.name)
+    ctypename  = ty.type.elem_type.typename
+    cname      = ty.name
+    clenvar    = ty.type.lenvar.name
+    golenvar   = xenlight_golang_fmt_name(clenvar,exported=False)
+
+    is_enum = isinstance(ty.type.elem_type,idl.Enumeration)
+    if gotypename in go_builtin_types or is_enum:
+        s += '{} := len(x.{})\n'.format(golenvar,goname)
+        s += 'xc.{} = (*C.{})(C.malloc(C.size_t({}*{})))\n'.format(cname,ctypename,
+                                                                   golenvar,golenvar)
+        s += 'xc.{} = C.int({})\n'.format(clenvar,golenvar)
+        s += 'c{} := (*[1<<28]C.{})(unsafe.Pointer(xc.{}))[:{}:{}]\n'.format(goname,
+                                                                      ctypename,cname,
+                                                                      golenvar,golenvar)
+        s += 'for i,v := range x.{} {{\n'.format(goname)
+        s += 'c{}[i] = C.{}(v)\n'.format(goname,ctypename)
+        s += '}\n'
+
+        return s
+
+    s += '{} := len(x.{})\n'.format(golenvar,goname)
+    s += 'xc.{} = (*C.{})(C.malloc(C.ulong({})*C.sizeof_{}))\n'.format(cname,ctypename,
+                                                                   golenvar,ctypename)
+    s += 'xc.{} = C.int({})\n'.format(clenvar,golenvar)
+    s += 'c{} := (*[1<<28]C.{})(unsafe.Pointer(xc.{}))[:{}:{}]\n'.format(goname,
+                                                                         ctypename,cname,
+                                                                         golenvar,golenvar)
+    s += 'for i,v := range x.{} {{\n'.format(goname)
+    s += 'tmp, err := v.toC()\n'
+    s += 'if err != nil {\n'
+    s += 'C.{}(&xc)\n'.format(dispose_fn)
+    s += 'return xc,err\n}\n'
+    s += 'c{}[i] = tmp\n'.format(goname)
+    s += '}\n'
+
+    return s
+
 def xenlight_golang_fmt_name(name, exported = True):
     """
     Take a given type name and return an
tools/golang/xenlight/helpers.gen.go +359 -0

443 lines not on this page · raw message

Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#29 lore raw

PATCH v3 21/22 golang/xenlight: revise use of Context type

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Remove the exported global context variable, 'Ctx.' Generally, it is better to not export global variables for use through a Go package. However, there are some exceptions that can be found in the standard library.

Add a NewContext function instead, and remove the Open, IsOpen, and CheckOpen functions as a result.

Also, comment-out an ineffectual assignment to 'err' inside the function Context.CpupoolInfo so that compilation does not fail.

---
 tools/golang/xenlight/xenlight.go | 219 +++++-------------------------
 1 file changed, 34 insertions(+), 185 deletions(-)
tools/golang/xenlight/xenlight.go +34 -185
index f32eb11384..1c431fa4e5 100644
@@ -74,6 +74,39 @@ func (e Error) Error() string {
 	return fmt.Sprintf("libxl error: %d", -e)
 }
 
+// Context represents a libxl_ctx.
+type Context struct {
+	ctx    *C.libxl_ctx
+	logger *C.xentoollog_logger_stdiostream
+}
+
+// NewContext returns a new Context.
+func NewContext() (*Context, error) {
+	var ctx Context
+
+	ctx.logger = C.xtl_createlogger_stdiostream(C.stderr, C.XTL_ERROR, 0)
+
+	ret := C.libxl_ctx_alloc(&ctx.ctx, C.LIBXL_VERSION, 0, (*C.xentoollog_logger)(unsafe.Pointer(ctx.logger)))
+	if ret != 0 {
+		return nil, Error(ret)
+	}
+
+	return &ctx, nil
+}
+
+// Close closes the Context.
+func (ctx *Context) Close() error {
+	ret := C.libxl_ctx_free(ctx.ctx)
+	ctx.ctx = nil
+	C.xtl_logger_destroy((*C.xentoollog_logger)(unsafe.Pointer(ctx.logger)))
+
+	if ret != 0 {
+		return Error(ret)
+	}
+
+	return nil
+}
+
 /*
  * Types: Builtins
  */
@@ -298,11 +331,6 @@ func (cpl CpuidPolicyList) toC() (C.libxl_cpuid_policy_list, error) {
 	return ccpl, nil
 }
 
-type Context struct {
-	ctx    *C.libxl_ctx
-	logger *C.xentoollog_logger_stdiostream
-}
-
 // Hwcap represents a libxl_hwcap.
 type Hwcap [8]uint32
 
@@ -453,11 +481,6 @@ func SchedulerFromString(name string) (s Scheduler, err error) {
 // libxl_cpupoolinfo * libxl_list_cpupool(libxl_ctx*, int *nb_pool_out);
 // void libxl_cpupoolinfo_list_free(libxl_cpupoolinfo *list, int nb_pool);
 func (Ctx *Context) ListCpupool() (list []Cpupoolinfo) {
-	err := Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	var nbPool C.int
 
 	c_cpupool_list := C.libxl_list_cpupool(Ctx.ctx, &nbPool)
@@ -481,16 +504,11 @@ func (Ctx *Context) ListCpupool() (list []Cpupoolinfo) {
 
 // int libxl_cpupool_info(libxl_ctx *ctx, libxl_cpupoolinfo *info, uint32_t poolid);
 func (Ctx *Context) CpupoolInfo(Poolid uint32) (pool Cpupoolinfo) {
-	err := Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	var c_cpupool C.libxl_cpupoolinfo
 
 	ret := C.libxl_cpupool_info(Ctx.ctx, &c_cpupool, C.uint32_t(Poolid))
 	if ret != 0 {
-		err = Error(-ret)
+		//err = Error(-ret)
 		return
 	}
 	defer C.libxl_cpupoolinfo_dispose(&c_cpupool)
@@ -507,11 +525,6 @@ func (Ctx *Context) CpupoolInfo(Poolid uint32) (pool Cpupoolinfo) {
 // FIXME: uuid
 // FIXME: Setting poolid
 func (Ctx *Context) CpupoolCreate(Name string, Scheduler Scheduler, Cpumap Bitmap) (err error, Poolid uint32) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	poolid := C.uint32_t(C.LIBXL_CPUPOOL_POOLID_ANY)
 	name := C.CString(Name)
 	defer C.free(unsafe.Pointer(name))
@@ -540,11 +553,6 @@ func (Ctx *Context) CpupoolCreate(Name string, Scheduler Scheduler, Cpumap Bitma
 
 // int libxl_cpupool_destroy(libxl_ctx *ctx, uint32_t poolid);
 func (Ctx *Context) CpupoolDestroy(Poolid uint32) (err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	ret := C.libxl_cpupool_destroy(Ctx.ctx, C.uint32_t(Poolid))
 	if ret != 0 {
 		err = Error(-ret)
@@ -556,11 +564,6 @@ func (Ctx *Context) CpupoolDestroy(Poolid uint32) (err error) {
 
 // int libxl_cpupool_cpuadd(libxl_ctx *ctx, uint32_t poolid, int cpu);
 func (Ctx *Context) CpupoolCpuadd(Poolid uint32, Cpu int) (err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	ret := C.libxl_cpupool_cpuadd(Ctx.ctx, C.uint32_t(Poolid), C.int(Cpu))
 	if ret != 0 {
 		err = Error(-ret)
@@ -573,11 +576,6 @@ func (Ctx *Context) CpupoolCpuadd(Poolid uint32, Cpu int) (err error) {
 // int libxl_cpupool_cpuadd_cpumap(libxl_ctx *ctx, uint32_t poolid,
 //                                 const libxl_bitmap *cpumap);
 func (Ctx *Context) CpupoolCpuaddCpumap(Poolid uint32, Cpumap Bitmap) (err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	cbm, err := Cpumap.toC()
 	if err != nil {
 		return
@@ -595,11 +593,6 @@ func (Ctx *Context) CpupoolCpuaddCpumap(Poolid uint32, Cpumap Bitmap) (err error
 
 // int libxl_cpupool_cpuremove(libxl_ctx *ctx, uint32_t poolid, int cpu);
 func (Ctx *Context) CpupoolCpuremove(Poolid uint32, Cpu int) (err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	ret := C.libxl_cpupool_cpuremove(Ctx.ctx, C.uint32_t(Poolid), C.int(Cpu))
 	if ret != 0 {
 		err = Error(-ret)
@@ -612,11 +605,6 @@ func (Ctx *Context) CpupoolCpuremove(Poolid uint32, Cpu int) (err error) {
 // int libxl_cpupool_cpuremove_cpumap(libxl_ctx *ctx, uint32_t poolid,
 //                                    const libxl_bitmap *cpumap);
 func (Ctx *Context) CpupoolCpuremoveCpumap(Poolid uint32, Cpumap Bitmap) (err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	cbm, err := Cpumap.toC()
 	if err != nil {
 		return
@@ -634,11 +622,6 @@ func (Ctx *Context) CpupoolCpuremoveCpumap(Poolid uint32, Cpumap Bitmap) (err er
 
 // int libxl_cpupool_rename(libxl_ctx *ctx, const char *name, uint32_t poolid);
 func (Ctx *Context) CpupoolRename(Name string, Poolid uint32) (err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	name := C.CString(Name)
 	defer C.free(unsafe.Pointer(name))
 
@@ -653,11 +636,6 @@ func (Ctx *Context) CpupoolRename(Name string, Poolid uint32) (err error) {
 
 // int libxl_cpupool_cpuadd_node(libxl_ctx *ctx, uint32_t poolid, int node, int *cpus);
 func (Ctx *Context) CpupoolCpuaddNode(Poolid uint32, Node int) (Cpus int, err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	ccpus := C.int(0)
 
 	ret := C.libxl_cpupool_cpuadd_node(Ctx.ctx, C.uint32_t(Poolid), C.int(Node), &ccpus)
@@ -673,11 +651,6 @@ func (Ctx *Context) CpupoolCpuaddNode(Poolid uint32, Node int) (Cpus int, err er
 
 // int libxl_cpupool_cpuremove_node(libxl_ctx *ctx, uint32_t poolid, int node, int *cpus);
 func (Ctx *Context) CpupoolCpuremoveNode(Poolid uint32, Node int) (Cpus int, err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	ccpus := C.int(0)
 
 	ret := C.libxl_cpupool_cpuremove_node(Ctx.ctx, C.uint32_t(Poolid), C.int(Node), &ccpus)
@@ -693,11 +666,6 @@ func (Ctx *Context) CpupoolCpuremoveNode(Poolid uint32, Node int) (Cpus int, err
 
 // int libxl_cpupool_movedomain(libxl_ctx *ctx, uint32_t poolid, uint32_t domid);
 func (Ctx *Context) CpupoolMovedomain(Poolid uint32, Id Domid) (err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	ret := C.libxl_cpupool_movedomain(Ctx.ctx, C.uint32_t(Poolid), C.uint32_t(Id))
 	if ret != 0 {
 		err = Error(-ret)
@@ -857,60 +825,8 @@ func (bm Bitmap) String() (s string) {
 	return
 }
 
-/*
- * Context
- */
-var Ctx Context
-
-func (Ctx *Context) IsOpen() bool {
-	return Ctx.ctx != nil
-}
-
-func (Ctx *Context) Open() (err error) {
-	if Ctx.ctx != nil {
-		return
-	}
-
-	Ctx.logger = C.xtl_createlogger_stdiostream(C.stderr, C.XTL_ERROR, 0)
-	if Ctx.logger == nil {
-		err = fmt.Errorf("Cannot open stdiostream")
-		return
-	}
-
-	ret := C.libxl_ctx_alloc(&Ctx.ctx, C.LIBXL_VERSION,
-		0, (*C.xentoollog_logger)(unsafe.Pointer(Ctx.logger)))
-
-	if ret != 0 {
-		err = Error(-ret)
-	}
-	return
-}
-
-func (Ctx *Context) Close() (err error) {
-	ret := C.libxl_ctx_free(Ctx.ctx)
-	Ctx.ctx = nil
-
-	if ret != 0 {
-		err = Error(-ret)
-	}
-	C.xtl_logger_destroy((*C.xentoollog_logger)(unsafe.Pointer(Ctx.logger)))
-	return
-}
-
-func (Ctx *Context) CheckOpen() (err error) {
-	if Ctx.ctx == nil {
-		err = fmt.Errorf("Context not opened")
-	}
-	return
-}
-
 //int libxl_get_max_cpus(libxl_ctx *ctx);
 func (Ctx *Context) GetMaxCpus() (maxCpus int, err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	ret := C.libxl_get_max_cpus(Ctx.ctx)
 	if ret < 0 {
 		err = Error(-ret)
@@ -922,11 +838,6 @@ func (Ctx *Context) GetMaxCpus() (maxCpus int, err error) {
 
 //int libxl_get_online_cpus(libxl_ctx *ctx);
 func (Ctx *Context) GetOnlineCpus() (onCpus int, err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	ret := C.libxl_get_online_cpus(Ctx.ctx)
 	if ret < 0 {
 		err = Error(-ret)
@@ -938,10 +849,6 @@ func (Ctx *Context) GetOnlineCpus() (onCpus int, err error) {
 
 //int libxl_get_max_nodes(libxl_ctx *ctx);
 func (Ctx *Context) GetMaxNodes() (maxNodes int, err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
 	ret := C.libxl_get_max_nodes(Ctx.ctx)
 	if ret < 0 {
 		err = Error(-ret)
@@ -953,10 +860,6 @@ func (Ctx *Context) GetMaxNodes() (maxNodes int, err error) {
 
 //int libxl_get_free_memory(libxl_ctx *ctx, uint64_t *memkb);
 func (Ctx *Context) GetFreeMemory() (memkb uint64, err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
 	var cmem C.uint64_t
 	ret := C.libxl_get_free_memory(Ctx.ctx, &cmem)
 
@@ -972,10 +875,6 @@ func (Ctx *Context) GetFreeMemory() (memkb uint64, err error) {
 
 //int libxl_get_physinfo(libxl_ctx *ctx, libxl_physinfo *physinfo)
 func (Ctx *Context) GetPhysinfo() (physinfo *Physinfo, err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
 	var cphys C.libxl_physinfo
 	C.libxl_physinfo_init(&cphys)
 	defer C.libxl_physinfo_dispose(&cphys)
@@ -993,11 +892,6 @@ func (Ctx *Context) GetPhysinfo() (physinfo *Physinfo, err error) {
 
 //const libxl_version_info* libxl_get_version_info(libxl_ctx *ctx);
 func (Ctx *Context) GetVersionInfo() (info *VersionInfo, err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	var cinfo *C.libxl_version_info
 
 	cinfo = C.libxl_get_version_info(Ctx.ctx)
@@ -1008,11 +902,6 @@ func (Ctx *Context) GetVersionInfo() (info *VersionInfo, err error) {
 }
 
 func (Ctx *Context) DomainInfo(Id Domid) (di *Dominfo, err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	var cdi C.libxl_dominfo
 	C.libxl_dominfo_init(&cdi)
 	defer C.libxl_dominfo_dispose(&cdi)
@@ -1030,11 +919,6 @@ func (Ctx *Context) DomainInfo(Id Domid) (di *Dominfo, err error) {
 }
 
 func (Ctx *Context) DomainUnpause(Id Domid) (err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	ret := C.libxl_domain_unpause(Ctx.ctx, C.uint32_t(Id), nil)
 
 	if ret != 0 {
@@ -1045,11 +929,6 @@ func (Ctx *Context) DomainUnpause(Id Domid) (err error) {
 
 //int libxl_domain_pause(libxl_ctx *ctx, uint32_t domain);
 func (Ctx *Context) DomainPause(id Domid) (err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	ret := C.libxl_domain_pause(Ctx.ctx, C.uint32_t(id), nil)
 
 	if ret != 0 {
@@ -1060,11 +939,6 @@ func (Ctx *Context) DomainPause(id Domid) (err error) {
 
 //int libxl_domain_shutdown(libxl_ctx *ctx, uint32_t domid);
 func (Ctx *Context) DomainShutdown(id Domid) (err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	ret := C.libxl_domain_shutdown(Ctx.ctx, C.uint32_t(id), nil)
 
 	if ret != 0 {
@@ -1075,11 +949,6 @@ func (Ctx *Context) DomainShutdown(id Domid) (err error) {
 
 //int libxl_domain_reboot(libxl_ctx *ctx, uint32_t domid);
 func (Ctx *Context) DomainReboot(id Domid) (err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	ret := C.libxl_domain_reboot(Ctx.ctx, C.uint32_t(id), nil)
 
 	if ret != 0 {
@@ -1091,11 +960,6 @@ func (Ctx *Context) DomainReboot(id Domid) (err error) {
 //libxl_dominfo * libxl_list_domain(libxl_ctx*, int *nb_domain_out);
 //void libxl_dominfo_list_free(libxl_dominfo *list, int nb_domain);
 func (Ctx *Context) ListDomain() (glist []Dominfo) {
-	err := Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	var nbDomain C.int
 	clist := C.libxl_list_domain(Ctx.ctx, &nbDomain)
 	defer C.libxl_dominfo_list_free(clist, nbDomain)
@@ -1118,11 +982,6 @@ func (Ctx *Context) ListDomain() (glist []Dominfo) {
 //				int *nb_vcpu, int *nr_cpus_out);
 //void libxl_vcpuinfo_list_free(libxl_vcpuinfo *, int nr_vcpus);
 func (Ctx *Context) ListVcpu(id Domid) (glist []Vcpuinfo) {
-	err := Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	var nbVcpu C.int
 	var nrCpu C.int
 
@@ -1153,11 +1012,6 @@ func (ct ConsoleType) String() (str string) {
 //int libxl_console_get_tty(libxl_ctx *ctx, uint32_t domid, int cons_num,
 //libxl_console_type type, char **path);
 func (Ctx *Context) ConsoleGetTty(id Domid, consNum int, conType ConsoleType) (path string, err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	var cpath *C.char
 	ret := C.libxl_console_get_tty(Ctx.ctx, C.uint32_t(id), C.int(consNum), C.libxl_console_type(conType), &cpath)
 	if ret != 0 {
@@ -1173,11 +1027,6 @@ func (Ctx *Context) ConsoleGetTty(id Domid, consNum int, conType ConsoleType) (p
 //int libxl_primary_console_get_tty(libxl_ctx *ctx, uint32_t domid_vm,
 //					char **path);
 func (Ctx *Context) PrimaryConsoleGetTty(domid uint32) (path string, err error) {
-	err = Ctx.CheckOpen()
-	if err != nil {
-		return
-	}
-
 	var cpath *C.char
 	ret := C.libxl_primary_console_get_tty(Ctx.ctx, C.uint32_t(domid), &cpath)
 	if ret != 0 {
Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
Reviewed-by on v3 21/22
#30 lore raw

Re: [Xen-devel] [PATCH v3 21/22] golang/xenlight: revise use of Context type

Quoted 7 lines · Nick Rosbrook

From: Nick Rosbrook <[email protected]>

Remove the exported global context variable, 'Ctx.' Generally, it is better to not export global variables for use through a Go package. However, there are some exceptions that can be found in the standard library.

Quoted 7 lines

Add a NewContext function instead, and remove the Open, IsOpen, and CheckOpen functions as a result.

Also, comment-out an ineffectual assignment to 'err' inside the function Context.CpupoolInfo so that compilation does not fail.

With one requested change...

Quoted 15 lines
---
 tools/golang/xenlight/xenlight.go | 219 +++++-------------------------
 1 file changed, 34 insertions(+), 185 deletions(-)
tools/golang/xenlight/xenlight.go +3 -0
index f32eb11384..1c431fa4e5 100644
@@ -74,6 +74,39 @@ func (e Error) Error() string {
 	return fmt.Sprintf("libxl error: %d", -e)
 }
 
+// Context represents a libxl_ctx.
+type Context struct {
+	ctx    *C.libxl_ctx

tools/golang/xenlight/xenlight.go func (e Error) Error() string { · line 89

Quoted 10 lines
tools/golang/xenlight/xenlight.go +10 -0
+	logger *C.xentoollog_logger_stdiostream
+}
+
+// NewContext returns a new Context.
+func NewContext() (*Context, error) {
+	var ctx Context
+
+	ctx.logger = C.xtl_createlogger_stdiostream(C.stderr, C.XTL_ERROR, 0)
+
+	ret := C.libxl_ctx_alloc(&ctx.ctx, C.LIBXL_VERSION, 0, (*C.xentoollog_logger)(unsafe.Pointer(ctx.logger)))

This line looks to be 114 characters long, which seems a bit much. :-) Mind breaking it just before the last argument?

Thanks,
-George

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#31 lore raw

PATCH v3 22/22 golang/xenlight: add error return type to Context.Cpupoolinfo

In reply to Nick Rosbrook

From: Nick Rosbrook <[email protected]>

A previous commit that removed Context.CheckOpen revealed an ineffectual assignent to err in Context.Cpupoolinfo, as there is no error return type.

Since it appears that the intent is to return an error here, add an error return value to the function signature.

---
 tools/golang/xenlight/xenlight.go | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
tools/golang/xenlight/xenlight.go +3 -3
index 1c431fa4e5..38d2ba8aa8 100644
@@ -503,17 +503,17 @@ func (Ctx *Context) ListCpupool() (list []Cpupoolinfo) {
 }
 
 // int libxl_cpupool_info(libxl_ctx *ctx, libxl_cpupoolinfo *info, uint32_t poolid);
-func (Ctx *Context) CpupoolInfo(Poolid uint32) (pool Cpupoolinfo) {
+func (Ctx *Context) CpupoolInfo(Poolid uint32) (pool Cpupoolinfo, err error) {
 	var c_cpupool C.libxl_cpupoolinfo
 
 	ret := C.libxl_cpupool_info(Ctx.ctx, &c_cpupool, C.uint32_t(Poolid))
 	if ret != 0 {
-		//err = Error(-ret)
+		err = Error(-ret)
 		return
 	}
 	defer C.libxl_cpupoolinfo_dispose(&c_cpupool)
 
-	_ = pool.fromC(&c_cpupool)
+	err = pool.fromC(&c_cpupool)
 
 	return
 }
Signature · 7 lines
2.19.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
Reviewed-by on v3 22/22
#32 lore raw

Re: [Xen-devel] [PATCH v3 22/22] golang/xenlight: add error return type to Context.Cpupoolinfo

Quoted 10 lines · Nick Rosbrook

From: Nick Rosbrook <[email protected]>

A previous commit that removed Context.CheckOpen revealed an ineffectual assignent to err in Context.Cpupoolinfo, as there is no error return type.

Since it appears that the intent is to return an error here, add an error return value to the function signature.

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel