Skip to contentSkip to conversation

golang/xenlight: Don't try to marshall zero-length arrays in fromC

PATCH In review George Dunlap 3 participants 7 messages Mar 9, 2020 – Mar 11, 2020

lore
Share & tools
lore
#0 lore raw

PATCH v4 1/3 golang/xenlight: Don't try to marshall zero-length arrays in fromC

The current fromC array code will do the "magic" casting and martialling even when num_foo variable is 0. Go crashes when doing the cast.

Only do array marshalling if the number of elements is non-zero; otherwise, leave the target pointer empty (nil for Go slices, NULL for C arrays).

---
v4:
- Replace fieldname-based variable with 'n'
v2:
- Remove toC part of this, which has been folded into Nick's patch series.

CC Nick Rosbrook <[email protected]>
---
 tools/golang/xenlight/gengotypes.py  |  11 +-
 tools/golang/xenlight/helpers.gen.go | 440 +++++++++++++++------------
 2 files changed, 257 insertions(+), 194 deletions(-)
tools/golang/xenlight/gengotypes.py +5 -6
index 50dada309b..e9ad92afa0 100644
@@ -426,13 +426,12 @@ def xenlight_golang_array_from_C(ty = None):
     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 += 'x.{} = nil\n'.format(goname)
+    s += 'if n := int(xc.{}); n > 0 {{\n'.format(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 +='(*[1<<28]C.{})(unsafe.Pointer(xc.{}))[:n:n]\n'.format(ctypename, cname)
+    s += 'x.{} = make([]{}, n)\n'.format(goname, gotypename)
     s += 'for i, v := range {} {{\n'.format(cslice)
 
     is_enum = isinstance(ty.type.elem_type,idl.Enumeration)
@@ -442,7 +441,7 @@ def xenlight_golang_array_from_C(ty = None):
         s += 'if err := x.{}[i].fromC(&v); err != nil {{\n'.format(goname)
         s += 'return fmt.Errorf("converting field {}: %v", err) }}\n'.format(goname)
 
-    s += '}\n'
+    s += '}\n}\n'
 
     return s
 
tools/golang/xenlight/helpers.gen.go +252 -188

557 lines not on this page · raw message

Signature · 7 lines
2.25.1


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

PATCH v4 2/3 golang/xenlight: Notify xenlight of SIGCHLD

libxl forks external processes and waits for them to complete; it therefore needs to be notified when children exit.

In absence of instructions to the contrary, libxl sets up its own SIGCHLD handlers.

Golang always unmasks and handles SIGCHLD itself. libxl thankfully notices this and throws an assert() rather than clobbering SIGCHLD handlers.

Tell libxl that we'll be responsible for getting SIGCHLD notifications to it. Arrange for a channel in the context to receive notifications on SIGCHLD, and set up a goroutine that will pass these on to libxl.

NB that every libxl context needs a notification; so multiple contexts will each spin up their own goroutine when opening a context, and shut it down on close.

libxl also wants to hold on to a const pointer to xenlight_childproc_hooks rather than do a copy; so make a global structure in C space. Make it static const, just for extra safety; this requires making a function in the C space to pass it to libxl.

While here, add a few comments to make the context set-up a bit easier to follow.

---
v4:
- Skip v3 to avoid confusion
- Don't bother doing a separate goroutine for libxl_childproc_sigchld_occurred.
- Allow chidlproc_hooks to be static const, by:
- initializing it in the C space, and
- Making a C function to pass it to libxl_childproc_setmode
- Cleanup on ctx.sigchld != nil, not == nil
- Use struct{} rather than bool for clarity
- Add a comment above the sigchldHandler goroutine describing its lifetime v2:
- Fix unsafe libxl_childproc_hooks pointer behavior
- Close down the SIGCHLD handler first, and make sure it's exited before closing the context
- Explicitly decide to have a separate goroutine per ctx

NB that due to a bug in libxl, this will hang without Ian's "[PATCH v2 00/10] libxl: event: Fix hang for some applications" series.

CC Nick Rosbrook <[email protected]>
CC Ian Jackson <[email protected]>
---
 tools/golang/xenlight/xenlight.go | 70 ++++++++++++++++++++++++++++++-
 1 file changed, 68 insertions(+), 2 deletions(-)
tools/golang/xenlight/xenlight.go +68 -2
index 3f1b0baa0c..56fa31fd7b 100644
@@ -17,9 +17,17 @@
 package xenlight
 
 /*
+
 #cgo LDFLAGS: -lxenlight -lyajl -lxentoollog
 #include <stdlib.h>
 #include <libxl.h>
+
+static const libxl_childproc_hooks childproc_hooks = { .chldowner = libxl_sigchld_owner_mainloop };
+
+void xenlight_set_chldproc(libxl_ctx *ctx) {
+	libxl_childproc_setmode(ctx, &childproc_hooks, NULL);
+}
+
 */
 import "C"
 
@@ -33,6 +41,9 @@ import "C"
 
 import (
 	"fmt"
+	"os"
+	"os/signal"
+	"syscall"
 	"unsafe"
 )
 
@@ -74,8 +85,37 @@ func (e Error) Error() string {
 
 // Context represents a libxl_ctx.
 type Context struct {
-	ctx    *C.libxl_ctx
-	logger *C.xentoollog_logger_stdiostream
+	ctx         *C.libxl_ctx
+	logger      *C.xentoollog_logger_stdiostream
+	sigchld     chan os.Signal
+	sigchldDone chan struct{}
+}
+
+// Golang always unmasks SIGCHLD, and internally has ways of
+// distributing SIGCHLD to multiple recipients.  libxl has provision
+// for this model: just tell it when a SIGCHLD happened, and it will
+// look after its own processes.
+//
+// This should "play nicely" with other users of SIGCHLD as long as
+// they don't reap libxl's processes.
+//
+// Every context needs to be notified on each SIGCHLD; so spin up a
+// new goroutine for each context.  If there are a large number of
+// contexts, this means each context will be woken up looking through
+// its own list of children.
+//
+// The alternate would be to register a fork callback, such that the
+// xenlight package can make a single list of all children, and only
+// notify the specific libxl context(s) that have children woken.  But
+// it's not clear to me this will be much more work than having the
+// xenlight go library do the same thing; doing it in separate go
+// threads has the potential to do it in parallel.  Leave that as an
+// optimization for later if it turns out to be a bottleneck.
+func sigchldHandler(ctx *Context) {
+	for _ = range ctx.sigchld {
+		C.libxl_childproc_sigchld_occurred(ctx.ctx)
+	}
+	close(ctx.sigchldDone)
 }
 
 // NewContext returns a new Context.
@@ -89,19 +129,45 @@ func NewContext() (ctx *Context, err error) {
 		}
 	}()
 
+	// Create a logger
 	ctx.logger = C.xtl_createlogger_stdiostream(C.stderr, C.XTL_ERROR, 0)
 
+	// Allocate a context
 	ret := C.libxl_ctx_alloc(&ctx.ctx, C.LIBXL_VERSION, 0,
 		(*C.xentoollog_logger)(unsafe.Pointer(ctx.logger)))
 	if ret != 0 {
 		return ctx, Error(ret)
 	}
 
+	// Tell libxl that we'll be dealing with SIGCHLD...
+	C.xenlight_set_chldproc(ctx.ctx)
+
+	// ...and arrange to keep that promise.
+	ctx.sigchld = make(chan os.Signal, 2)
+	ctx.sigchldDone = make(chan struct{}, 1)
+	signal.Notify(ctx.sigchld, syscall.SIGCHLD)
+
+	// This goroutine will run until the ctx.sigchld is closed in
+	// ctx.Close(); at which point it will close ctx.sigchldDone.
+	go sigchldHandler(ctx)
+
 	return ctx, nil
 }
 
 // Close closes the Context.
 func (ctx *Context) Close() error {
+	// Tell our SIGCHLD notifier to shut down, and wait for it to exit
+	// before we free the context.
+	if ctx.sigchld != nil {
+		signal.Stop(ctx.sigchld)
+		close(ctx.sigchld)
+
+		<-ctx.sigchldDone
+
+		ctx.sigchld = nil
+		ctx.sigchldDone = nil
+	}
+
 	if ctx.ctx != nil {
 		ret := C.libxl_ctx_free(ctx.ctx)
 		if ret != 0 {
Signature · 7 lines
2.25.1


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

Re: [Xen-devel] [PATCH v4 2/3] golang/xenlight: Notify xenlight of SIGCHLD

Quoted 23 lines

libxl forks external processes and waits for them to complete; it therefore needs to be notified when children exit.

In absence of instructions to the contrary, libxl sets up its own SIGCHLD handlers.

Golang always unmasks and handles SIGCHLD itself. libxl thankfully notices this and throws an assert() rather than clobbering SIGCHLD handlers.

Tell libxl that we'll be responsible for getting SIGCHLD notifications to it. Arrange for a channel in the context to receive notifications on SIGCHLD, and set up a goroutine that will pass these on to libxl.

NB that every libxl context needs a notification; so multiple contexts will each spin up their own goroutine when opening a context, and shut it down on close.

libxl also wants to hold on to a const pointer to xenlight_childproc_hooks rather than do a copy; so make a global structure in C space. Make it static const, just for extra safety; this requires making a function in the C space to pass it to libxl.

Quoted 4 lines

While here, add a few comments to make the context set-up a bit easier to follow.

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

#3 lore raw

PATCH v4 3/3 golang/xenlight: Implement DomainCreateNew

In reply to George Dunlap

This implements the wrapper around libxl_domain_create_new(). With the previous changes, it's now possible to create a domain using the golang bindings (although not yet to unpause it or harvest it after it shuts down).

---
v4:
- Remove hand-crafted constructor code, make non-RFC

CC Nick Rosbrook <[email protected]>
---
 tools/golang/xenlight/xenlight.go | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
tools/golang/xenlight/xenlight.go +21 -0
index 56fa31fd7b..808b4a327c 100644
@@ -1111,3 +1111,24 @@ func (Ctx *Context) PrimaryConsoleGetTty(domid uint32) (path string, err error)
 	path = C.GoString(cpath)
 	return
 }
+
+// int libxl_domain_create_new(libxl_ctx *ctx, libxl_domain_config *d_config,
+//                             uint32_t *domid,
+//                             const libxl_asyncop_how *ao_how,
+//                             const libxl_asyncprogress_how *aop_console_how)
+func (Ctx *Context) DomainCreateNew(config *DomainConfig) (Domid, error) {
+	var cdomid C.uint32_t
+	var cconfig C.libxl_domain_config
+	err := config.toC(&cconfig)
+	if err != nil {
+		return Domid(0), fmt.Errorf("converting domain config to C: %v", err)
+	}
+	defer C.libxl_domain_config_dispose(&cconfig)
+
+	ret := C.libxl_domain_create_new(Ctx.ctx, &cconfig, &cdomid, nil, nil)
+	if ret != 0 {
+		return Domid(0), Error(ret)
+	}
+
+	return Domid(cdomid), nil
+}
Signature · 7 lines
2.25.1


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

Re: [Xen-devel] [PATCH v4 3/3] golang/xenlight: Implement DomainCreateNew

Looks good, I just have two small comments:

tools/golang/xenlight/xenlight.go func (Ctx *Context) PrimaryConsoleGetTty(domid uint32) (path string, err error) · line 1118

Quoted 13 lines
tools/golang/xenlight/xenlight.go +5 -0
index 56fa31fd7b..808b4a327c 100644
@@ -1111,3 +1111,24 @@ func (Ctx *Context) PrimaryConsoleGetTty(domid uint32) (path string, err error)
        path = C.GoString(cpath)
        return
 }
+
+// int libxl_domain_create_new(libxl_ctx *ctx, libxl_domain_config *d_config,
+//                             uint32_t *domid,
+//                             const libxl_asyncop_how *ao_how,
+//                             const libxl_asyncprogress_how *aop_console_how)

Conventionally, we want to have comments for exported functions along the lines of:

    // DomainCreateNew creates a new domain with config, and returns
its Domid on success.
    // A non-nil error is returned if config cannot be marshaled, or

an error occurs within libxl.

Besides being easier to read, it makes documentation more clear on godoc/pkg.go.dev.

tools/golang/xenlight/xenlight.go func (Ctx *Context) PrimaryConsoleGetTty(domid uint32) (path string, err error) · line 1119

Quoted 1 line
tools/golang/xenlight/xenlight.go +1 -0
+func (Ctx *Context) DomainCreateNew(config *DomainConfig) (Domid, error) {

Capitalizing "Ctx" here is a little weird to me. Since it's only the receiver name, there's no effect, but since capitalized identifiers have special-meaning in other contexts, I would avoid doing this.

I only point those out in case you want to change it on check-in. Besides that,

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

#5 lore raw

Re: [Xen-devel] [PATCH v4 3/3] golang/xenlight: Implement DomainCreateNew

Quoted 19 lines · Nick Rosbrook

Looks good, I just have two small comments:

tools/golang/xenlight/xenlight.go func (Ctx *Context) PrimaryConsoleGetTty(domid uint32) (path string, err error) · line 1118

Quoted 13 lines
tools/golang/xenlight/xenlight.go +5 -0
index 56fa31fd7b..808b4a327c 100644
@@ -1111,3 +1111,24 @@ func (Ctx *Context) PrimaryConsoleGetTty(domid uint32) (path string, err error)
        path = C.GoString(cpath)
        return
 }
+
+// int libxl_domain_create_new(libxl_ctx *ctx, libxl_domain_config *d_config,
+//                             uint32_t *domid,
+//                             const libxl_asyncop_how *ao_how,
+//                             const libxl_asyncprogress_how *aop_console_how)

Conventionally, we want to have comments for exported functions along the lines of:

Quoted 7 lines
    // DomainCreateNew creates a new domain with config, and returns
its Domid on success.
    // A non-nil error is returned if config cannot be marshaled, or

an error occurs within libxl.

Besides being easier to read, it makes documentation more clear on godoc/pkg.go.dev.

Yes, absolutely, that's something we need to change before we declare "1.0". But that should probably be done in a series which changes all such comments together.

Quoted 5 lines

tools/golang/xenlight/xenlight.go func (Ctx *Context) PrimaryConsoleGetTty(domid uint32) (path string, err error) · line 1119

Quoted 1 line
tools/golang/xenlight/xenlight.go +1 -0
+func (Ctx *Context) DomainCreateNew(config *DomainConfig) (Domid, error) {

Capitalizing "Ctx" here is a little weird to me. Since it's only the receiver name, there's no effect, but since capitalized identifiers have special-meaning in other contexts, I would avoid doing this.

I c&p'd this from another method and just changed the signature. It probably would be good to make all of them lower-case. I may change this one on check in though.

Quoted 3 lines

I only point those out in case you want to change it on check-in. Besides that,

Thanks!

-George

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

Reviewed-by on v4 1/3
#6 lore raw
In reply to George Dunlap
Quoted 9 lines

The current fromC array code will do the "magic" casting and martialling even when num_foo variable is 0.  Go crashes when doing the cast.

Only do array marshalling if the number of elements is non-zero; otherwise, leave the target pointer empty (nil for Go slices, NULL for C arrays).

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