Skip to contentSkip to conversation

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

PATCH Superseded George Dunlap 2 participants 18 messages Dec 27, 2019 – Jan 16, 2020

v1 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/9 golang/xenlight: Don't try to marshall zero-length arrays

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.

Furthermore, the current toC array code will convert a nil slice into a zero-length malloc. The resulting pointer is non-NULL, and confuses libxl.

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).

The toC half of this should be folded into "golang/xenlight:
implement array Go to C marshaling".

---
CC: Nick Rosbrook <[email protected]>

---
 tools/golang/xenlight/gengotypes.py  |   13 +-
 tools/golang/xenlight/helpers.gen.go | 1232 ++++++++++++++------------
 2 files changed, 671 insertions(+), 574 deletions(-)
tools/golang/xenlight/gengotypes.py +7 -6
index a972754d36..5363ca062d 100644
@@ -419,7 +419,8 @@ def xenlight_golang_array_from_C(ty = None):
     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 {} := int(xc.{}); {} > 0 {{\n'.format(golenvar, clenvar, golenvar)
     s += '{} := '.format(cslice)
     s +='(*[1<<28]C.{})(unsafe.Pointer(xc.{}))[:{}:{}]\n'.format(ctypename, cname,
                                                                 golenvar, golenvar)
@@ -433,7 +434,7 @@ def xenlight_golang_array_from_C(ty = None):
         s += 'if err := x.{}[i].fromC(&v); err != nil {{\n'.format(goname)
         s += 'return err }\n'
 
-    s += '}\n'
+    s += '}\n}\n'
 
     return s
 
@@ -599,7 +600,7 @@ def xenlight_golang_array_to_C(ty = None, dispose_fn = ''):
 
     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 += 'if {} := len(x.{}); {} > 0 {{\n'.format(golenvar,goname, golenvar)
         s += 'xc.{} = (*C.{})(C.malloc(C.size_t({}*{})))\n'.format(cname,ctypename,
                                                                    golenvar,golenvar)
         s += 'xc.{} = C.int({})\n'.format(clenvar,golenvar)
@@ -608,11 +609,11 @@ def xenlight_golang_array_to_C(ty = None, dispose_fn = ''):
                                                                       golenvar,golenvar)
         s += 'for i,v := range x.{} {{\n'.format(goname)
         s += 'c{}[i] = C.{}(v)\n'.format(goname,ctypename)
-        s += '}\n'
+        s += '}\n}\n'
 
         return s
 
-    s += '{} := len(x.{})\n'.format(golenvar,goname)
+    s += 'if {} := len(x.{}); {} > 0 {{\n'.format(golenvar,goname, golenvar)
     s += 'xc.{} = (*C.{})(C.malloc(C.ulong({})*C.sizeof_{}))\n'.format(cname,ctypename,
                                                                    golenvar,ctypename)
     s += 'xc.{} = C.int({})\n'.format(clenvar,golenvar)
@@ -625,7 +626,7 @@ def xenlight_golang_array_to_C(ty = None, dispose_fn = ''):
     s += 'C.{}(&xc)\n'.format(dispose_fn)
     s += 'return xc,err\n}\n'
     s += 'c{}[i] = tmp\n'.format(goname)
-    s += '}\n'
+    s += '}\n}\n'
 
     return s
 
tools/golang/xenlight/helpers.gen.go +664 -568

1,451 lines not on this page · raw message

Signature · 7 lines
2.24.0


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

PATCH 2/9 golang/xenlight: Do proper nil / NULL conversions for builtin Bitmap type

Similar to the autogenerated types, but for builtin Bitmap type.

---
CC: Nick Rosbrook <[email protected]>

---
 tools/golang/xenlight/xenlight.go | 24 ++++++++++++++----------
 1 file changed, 14 insertions(+), 10 deletions(-)
tools/golang/xenlight/xenlight.go +14 -10
index 237f26bce9..e18f0f35f8 100644
@@ -408,15 +408,17 @@ type Bitmap struct {
 }
 
 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)
+	bm.bitmap = nil
+	if size := int(cbm.size); size > 0 {
+		// Alloc a Go slice for the bytes
+		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]
+		// 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)
+		// And copy the C array into the Go array
+		copy(bm.bitmap, cs)
+	}
 
 	return nil
 }
@@ -426,10 +428,12 @@ func (bm *Bitmap) toC() (C.libxl_bitmap, error) {
 
 	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]
+	if cbm.size > 0 {
+		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)
+		copy(cs, bm.bitmap)
+	}
 
 	return cbm, nil
 }
Signature · 7 lines
2.24.0


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

Re: [Xen-devel] [PATCH 2/9] golang/xenlight: Do proper nil / NULL conversions for builtin Bitmap type

Quoted 4 lines · George Dunlap

Similar to the autogenerated types, but for builtin Bitmap type.

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

#3 lore raw

PATCH 3/9 golang/xenlight: Convert "" to NULL

In reply to George Dunlap

C.GoString will handle NULL C strings properly, by passing back "". But C.CString will take an empty Go string and actually generate a '\0'-terminated empty string. This confuses libxl, which is expecting non-values to be NULL, not "".

Only call C.CString if the Go string is non-empty.

---
CC: Nick Rosbrook <[email protected]>

---
 tools/golang/xenlight/gengotypes.py  |   6 +-
 tools/golang/xenlight/helpers.gen.go | 628 ++++++++++++++++++++-------
 2 files changed, 475 insertions(+), 159 deletions(-)
tools/golang/xenlight/gengotypes.py +4 -2
index 5363ca062d..e4ed4d50f5 100644
@@ -487,7 +487,8 @@ def xenlight_golang_define_to_C(ty = None, typename = None, nested = False):
             if is_castable:
                 # Use the cgo helper for converting C strings.
                 if gotypename == 'string':
-                    s += 'xc.{} = C.CString(x.{})\n'.format(cname,goname)
+                    s += 'if x.{} != "" {{\n'.format(goname)
+                    s += 'xc.{} = C.CString(x.{})\n}}\n'.format(cname,goname)
                     continue
 
                 s += 'xc.{} = C.{}(x.{})\n'.format(cname,ctypename,goname)
@@ -569,7 +570,8 @@ def xenlight_golang_union_to_C(ty = None, union_name = '',
                 s += 'return xc,err \n}\n'
 
             elif gotypename == 'string':
-                s += '{}.{} = C.CString(tmp.{})\n'.format(f.name,uf.name,gofname)
+                s += 'if tmp.{} != "" {{\n'.format(gofname)
+                s += '{}.{} = C.CString(tmp.{})\n}}\n'.format(f.name,uf.name,gofname)
 
             else:
                 s += '{}.{} = C.{}(tmp.{})\n'.format(f.name,uf.name,ctypename,gofname)
tools/golang/xenlight/helpers.gen.go +471 -157

989 lines not on this page · raw message

Signature · 7 lines
2.24.0


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

Re: [Xen-devel] [PATCH 3/9] golang/xenlight: Convert "" to NULL

Quoted 6 lines

C.GoString will handle NULL C strings properly, by passing back "". But C.CString will take an empty Go string and actually generate a '\0'-terminated empty string. This confuses libxl, which is expecting non-values to be NULL, not "".

Only call C.CString if the Go string is non-empty.

Good catch, thanks. This should go in v5 of my series though, right? The toC code hasn't been checked-in yet.

-NR

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

#5 lore raw

PATCH 4/9 go/xenlight: Fix CpuidPoliclyList conversion

In reply to George Dunlap

Empty Go strings should be converted to nil libxl_cpuid_policy_list; otherwise libxl_cpuid_parse_config gets confused.

Also, libxl_cpuid_policy_list returns a weird error, not a "normal" libxl error; if it returns one of these non-standard errors, convert it to ErrorInval.

---
CC: Nick Rosbrook <[email protected]>

---
 tools/golang/xenlight/xenlight.go | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
tools/golang/xenlight/xenlight.go +6 -1
index e18f0f35f8..99de68320b 100644
@@ -317,6 +317,10 @@ 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) {
+	if cpl == "" {
+		return nil, nil
+	}
+
 	var ccpl C.libxl_cpuid_policy_list
 
 	s := C.CString(string(cpl))
@@ -326,7 +330,8 @@ func (cpl CpuidPolicyList) toC() (C.libxl_cpuid_policy_list, error) {
 	if ret != 0 {
 		C.libxl_cpuid_dispose(&ccpl)
 
-		return ccpl, Error(-ret)
+		// libxl_cpuid_parse_config doesn't return a normal libxl error.
+		return ccpl, ErrorInval
 	}
 
 	return ccpl, nil
Signature · 7 lines
2.24.0


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

Re: [Xen-devel] [PATCH 4/9] go/xenlight: Fix CpuidPoliclyList conversion

Quoted 8 lines

Empty Go strings should be converted to nil libxl_cpuid_policy_list; otherwise libxl_cpuid_parse_config gets confused.

Also, libxl_cpuid_policy_list returns a weird error, not a "normal" libxl error; if it returns one of these non-standard errors, convert it to ErrorInval.

Looks good to me. If "golang/xenlight: begin Go to C type marshaling" is committed before this, the signature of toC will need to be updated as per your suggestion.

Otherwise,

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

#7 lore raw

PATCH 5/9 go/xenlight: More informative error messages

In reply to George Dunlap

If an error is encountered deep in a complicated data structure, it's often difficult to tell where the error actually is. Make the error message from the generated toC() and fromC() structures more informative by tagging which field being converted encountered the error. This will have the effect of giving a "stack trace" of the failure inside a nested data structure.

---
CC: Nick Rosbrook <[email protected]>

---
 tools/golang/xenlight/gengotypes.py  |  10 +-
 tools/golang/xenlight/helpers.gen.go | 456 +++++++++++++--------------
 2 files changed, 233 insertions(+), 233 deletions(-)
tools/golang/xenlight/gengotypes.py +5 -5
index e4ed4d50f5..48e3d86f70 100644
@@ -314,7 +314,7 @@ def xenlight_golang_convert_from_C(ty = None, outer_name = None, cvarname = None
         # If the type is not castable, we need to call its fromC
         # function.
         s += 'if err := x.{}.fromC(&{}.{});'.format(goname,cvarname,cname)
-        s += 'err != nil {\n return err \n}\n'
+        s += 'err != nil {{\nreturn fmt.Errorf("Converting field {}: %v", err) \n}}\n'.format(goname)
 
     elif gotypename == 'string':
         # Use the cgo helper for converting C strings.
@@ -389,7 +389,7 @@ def xenlight_golang_union_from_C(ty = None, union_name = '', struct_name = ''):
 
         s += 'var {} {}\n'.format(goname, gotype)
         s += 'if err := {}.fromC(xc);'.format(goname)
-        s += 'err != nil {\n return err \n}\n'
+        s += 'err != nil {{\n return fmt.Errorf("Converting field {}: %v", err) \n}}\n'.format(goname)
 
         field_name = xenlight_golang_fmt_name('{}_union'.format(keyname))
         s += 'x.{} = {}\n'.format(field_name, goname)
@@ -432,7 +432,7 @@ def xenlight_golang_array_from_C(ty = None):
         s += 'x.{}[i] = {}(v)\n'.format(goname, gotypename)
     else:
         s += 'if err := x.{}[i].fromC(&v); err != nil {{\n'.format(goname)
-        s += 'return err }\n'
+        s += 'return fmt.Errorf("Converting field {}: %v", err) }}\n'.format(goname)
 
     s += '}\n}\n'
 
@@ -497,7 +497,7 @@ def xenlight_golang_define_to_C(ty = None, typename = None, nested = False):
                 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 += 'return xc, fmt.Errorf("Converting field {}: %v", err)\n'.format(goname)
                 s += '}\n'
 
         elif isinstance(f.type, idl.Struct):
@@ -567,7 +567,7 @@ def xenlight_golang_union_to_C(ty = None, union_name = '',
                 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'
+                s += 'return xc,fmt.Errorf("Converting field {}: %v", err) \n}}\n'.format(gofname)
 
             elif gotypename == 'string':
                 s += 'if tmp.{} != "" {{\n'.format(gofname)
tools/golang/xenlight/helpers.gen.go +228 -228

1,510 lines not on this page · raw message

Signature · 7 lines
2.24.0


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

Re: [Xen-devel] [PATCH 5/9] go/xenlight: More informative error messages

Quoted 9 lines · George Dunlap

If an error is encountered deep in a complicated data structure, it's often difficult to tell where the error actually is. Make the error message from the generated toC() and fromC() structures more informative by tagging which field being converted encountered the error. This will have the effect of giving a "stack trace" of the failure inside a nested data structure.

Looks good, just one nit-picky comment:

tools/golang/xenlight/gengotypes.py def xenlight_golang_convert_from_C(ty = None, outer_name = None, cvarname = None · line 317

Quoted 10 lines
tools/golang/xenlight/gengotypes.py +1 -1
index e4ed4d50f5..48e3d86f70 100644
@@ -314,7 +314,7 @@ def xenlight_golang_convert_from_C(ty = None, outer_name = None, cvarname = None
         # If the type is not castable, we need to call its fromC
         # function.
         s += 'if err := x.{}.fromC(&{}.{});'.format(goname,cvarname,cname)
-        s += 'err != nil {\n return err \n}\n'
+        s += 'err != nil {{\nreturn fmt.Errorf("Converting field {}: %v", err) \n}}\n'.format(goname)

It's preferred style to keep error messages lowercase, unless a proper noun or acronym is used (the field names would be considered proper nouns).

-NR

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

#9 lore raw

Re: [Xen-devel] [PATCH 5/9] go/xenlight: More informative error messages

Quoted 13 lines · Nick Rosbrook
Quoted 9 lines · George Dunlap

If an error is encountered deep in a complicated data structure, it's often difficult to tell where the error actually is. Make the error message from the generated toC() and fromC() structures more informative by tagging which field being converted encountered the error. This will have the effect of giving a "stack trace" of the failure inside a nested data structure.

Looks good, just one nit-picky comment:

Quoted 14 lines

tools/golang/xenlight/gengotypes.py def xenlight_golang_convert_from_C(ty = None, outer_name = None, cvarname = None · line 317

Quoted 10 lines
tools/golang/xenlight/gengotypes.py +1 -1
index e4ed4d50f5..48e3d86f70 100644
@@ -314,7 +314,7 @@ def xenlight_golang_convert_from_C(ty = None, outer_name = None, cvarname = None
         # If the type is not castable, we need to call its fromC
         # function.
         s += 'if err := x.{}.fromC(&{}.{});'.format(goname,cvarname,cname)
-        s += 'err != nil {\n return err \n}\n'
+        s += 'err != nil {{\nreturn fmt.Errorf("Converting field {}: %v", err) \n}}\n'.format(goname)

It's preferred style to keep error messages lowercase, unless a proper noun or acronym is used (the field names would be considered proper nouns).

Ack.

-George

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

#10 lore raw

PATCH 6/9 golang/xenlight: Errors are negative

In reply to George Dunlap

Commit 871e51d2d4 changed the sign on the xenlight error types (making the values negative, same as the C-generated constants), but failed to flip the sign in the Error() string function. The result is that ErrorNonspecific.String() prints "libxl error: 1" rather than the human-readable error message.

Get the error message index by inverting the error number once.

Also, always print the actual error value, rather than the inverted value, for clarity.

---
CC: Nick Rosbrook <[email protected]>

---
 tools/golang/xenlight/xenlight.go | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
tools/golang/xenlight/xenlight.go +4 -3
index 99de68320b..c80f622e6b 100644
@@ -65,13 +65,14 @@ var libxlErrors = [...]string{
 }
 
 func (e Error) Error() string {
-	if 0 < int(e) && int(e) < len(libxlErrors) {
-		s := libxlErrors[e]
+	eidx := -int(e)
+	if 0 < eidx && eidx < len(libxlErrors) {
+		s := libxlErrors[eidx]
 		if s != "" {
 			return s
 		}
 	}
-	return fmt.Sprintf("libxl error: %d", -e)
+	return fmt.Sprintf("libxl error: %d", e)
 }
 
 // Context represents a libxl_ctx.
Signature · 7 lines
2.24.0


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

Re: [Xen-devel] [PATCH 6/9] golang/xenlight: Errors are negative

Quoted 6 lines · George Dunlap

Commit 871e51d2d4 changed the sign on the xenlight error types (making the values negative, same as the C-generated constants), but failed to flip the sign in the Error() string function. The result is that ErrorNonspecific.String() prints "libxl error: 1" rather than the human-readable error message.

Since we're here, what would you think about re-defining libxlErrors as a map[Error]string? That way, Error() can just be:

func (e Error) Error() string {
        if s, ok := libxlErrors[e]; ok {
                return s
        }

        return fmt.Sprintf("libxl error: %d", e)
}

I think it's less error-prone and easier to read. Thoughts?

-NR

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

#12 lore raw

Re: [Xen-devel] [PATCH 6/9] golang/xenlight: Errors are negative

Quoted 19 lines · Nick Rosbrook
Quoted 6 lines · George Dunlap

Commit 871e51d2d4 changed the sign on the xenlight error types (making the values negative, same as the C-generated constants), but failed to flip the sign in the Error() string function. The result is that ErrorNonspecific.String() prints "libxl error: 1" rather than the human-readable error message.

Since we're here, what would you think about re-defining libxlErrors as a map[Error]string? That way, Error() can just be:

func (e Error) Error() string {
        if s, ok := libxlErrors[e]; ok {
                return s
        }

        return fmt.Sprintf("libxl error: %d", e)
}
Quoted 1 line

I think it's less error-prone and easier to read. Thoughts?

Yes, that sounds better. Done.

-George

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

#13 lore raw

PATCH 7/9 golang/xenlight: Default loglevel to DEBUG until we get everything working

In reply to George Dunlap

---

The other option would be to expose the XTL logging levels and let the caller set them somehow.

CC Nick Rosbrook <[email protected]>
---
 tools/golang/xenlight/xenlight.go | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/golang/xenlight/xenlight.go +1 -1
index c80f622e6b..e115592257 100644
@@ -85,7 +85,7 @@ type Context struct {
 func NewContext() (*Context, error) {
 	var ctx Context
 
-	ctx.logger = C.xtl_createlogger_stdiostream(C.stderr, C.XTL_ERROR, 0)
+	ctx.logger = C.xtl_createlogger_stdiostream(C.stderr, C.XTL_DEBUG, 0)
 
 	ret := C.libxl_ctx_alloc(&ctx.ctx, C.LIBXL_VERSION, 0,
 		(*C.xentoollog_logger)(unsafe.Pointer(ctx.logger)))
Signature · 7 lines
2.24.0


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

PATCH 8/9 RFC: golang/xenlight: Notify xenlight of SIGCHLD

In reply to George Dunlap

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.

---
I have no idea if this is actually the right way to go about this; in particular, libxl_event.h's comment on this function refers to the comment on libxl_childproc_reaped, which says:

* May NOT be called from within a signal handler which might
* interrupt any libxl operation. The application will almost
* certainly need to use the self-pipe trick (or a working pselect or
* ppoll) to implement this.

I don't have a good way of knowing whether the goproc-receiving-a-channel satisfies this requirement or not. It seems to work, in the sense that the pygrub process works fine. But it gets stuck a bit further on, looks like waiting for the disk; and a diff of the output between xl create and the golang create seems to indicate that xenstore watches aren't being delivered. Not sure if that's explicitly do to SIGCHLD, or due to some other side effect of setting libxl_sigchld_owner_mainloop, or something else entirely.

CC Nick Rosbrook <[email protected]>
---
 tools/golang/xenlight/xenlight.go | 34 +++++++++++++++++++++++++++++--
 1 file changed, 32 insertions(+), 2 deletions(-)
tools/golang/xenlight/xenlight.go +32 -2
index e115592257..f70a4c6d96 100644
@@ -33,6 +33,9 @@ import "C"
 
 import (
 	"fmt"
+	"os"
+	"os/signal"
+	"syscall"
 	"unsafe"
 )
 
@@ -77,8 +80,23 @@ 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
+}
+
+// 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.
+func sigchldHandler(ctx *Context) {
+	for _ = range ctx.sigchld {
+		// Can we spin up another goroutine for this?
+		C.libxl_childproc_sigchld_occurred(ctx.ctx)
+	}
 }
 
 // NewContext returns a new Context.
@@ -93,6 +111,15 @@ func NewContext() (*Context, error) {
 		return nil, Error(ret)
 	}
 
+	ctx.sigchld = make(chan os.Signal, 2)
+	signal.Notify(ctx.sigchld, syscall.SIGCHLD)
+
+	go sigchldHandler(&ctx)
+
+	C.libxl_childproc_setmode(ctx.ctx,
+		&C.libxl_childproc_hooks{chldowner: C.libxl_sigchld_owner_mainloop},
+		nil)
+
 	return &ctx, nil
 }
 
@@ -102,6 +129,9 @@ func (ctx *Context) Close() error {
 	ctx.ctx = nil
 	C.xtl_logger_destroy((*C.xentoollog_logger)(unsafe.Pointer(ctx.logger)))
 
+	signal.Stop(ctx.sigchld)
+	close(ctx.sigchld)
+
 	if ret != 0 {
 		return Error(ret)
 	}
Signature · 7 lines
2.24.0


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

PATCH 9/9 DO NOT APPLY: Sketch constructors, DomainCreateNew

In reply to George Dunlap

This is a sketch of functionality suitable for creating a basic domain, with a disk and a vif. DomainConfig, DeviceDisk, and DeviceNic types are all created using constructor functions, which initialize them with libxl's defaults.

DomainCreateNew takes the config and calls without any updates.

Obviously some of these will need to be changed it we switch to passing references to .toC() rather than passing back by value.

The main purpose of this is to allow testing of creating a hard-coded domain.

---
CC: Nick Rosbrook <[email protected]>

---
 tools/golang/xenlight/xenlight.go | 66 +++++++++++++++++++++++++++++++
 1 file changed, 66 insertions(+)
tools/golang/xenlight/xenlight.go +66 -0
index f70a4c6d96..91da79bc68 100644
@@ -1079,3 +1079,69 @@ func (Ctx *Context) PrimaryConsoleGetTty(domid uint32) (path string, err error)
 	path = C.GoString(cpath)
 	return
 }
+
+func NewDomainConfig(t DomainType) (*DomainConfig, error) {
+	var cconfig C.libxl_domain_config
+
+	C.libxl_domain_config_init(&cconfig)
+	C.libxl_domain_build_info_init_type(&cconfig.b_info, C.libxl_domain_type(t))
+
+	gconfig := &DomainConfig{}
+	err := gconfig.fromC(&cconfig)
+	if err != nil {
+		return nil, err
+	}
+
+	return gconfig, nil
+}
+
+func NewDeviceDisk() (*DeviceDisk, error) {
+	var ctype C.libxl_device_disk
+
+	C.libxl_device_disk_init(&ctype)
+
+	gtype := &DeviceDisk{}
+	err := gtype.fromC(&ctype)
+
+	if err != nil {
+		return nil, err
+	}
+
+	return gtype, nil
+}
+
+func NewDeviceNic() (*DeviceNic, error) {
+	var ctype C.libxl_device_nic
+
+	C.libxl_device_nic_init(&ctype)
+
+	gtype := &DeviceNic{}
+	err := gtype.fromC(&ctype)
+
+	if err != nil {
+		return nil, err
+	}
+
+	return gtype, nil
+}
+
+// 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
+	cconfig, err := config.toC()
+	if err != nil {
+		return Domid(0), fmt.Errorf("Converting domain config to C: %v", err)
+	}
+	defer C.libxl_domain_config_dispose(&cconfig)
+
+	fmt.Errorf("Calling libxl_domain_create_new")
+	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.24.0


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#16 lore raw
In reply to George Dunlap
Quoted 8 lines · George Dunlap

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.

Furthermore, the current toC array code will convert a nil slice into a zero-length malloc. The resulting pointer is non-NULL, and confuses libxl.

Quoted 8 lines

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).

The toC half of this should be folded into "golang/xenlight:
implement array Go to C marshaling".

The .go program I used to test this series is attached, to give you an idea what the current iteration looks like, and potentially give it a spin.

-George

package main

import (

	"fmt"
	xl "golang.xenproject.org/xenlight"

)

func main() {
	ctx, err := xl.NewContext()
	if err != nil {
		fmt.Printf("Opening context: %v\n", err)
		return
	}
	defer ctx.Close()

	doms := ctx.ListDomain()
	for i := range doms {
		fmt.Printf("%d %v\n", doms[i].Domid, doms[i].Uuid)
	}

	fmt.Printf("String for error ErrorNonspecific: %v\n", xl.ErrorNonspecific)

	// type = "pv"
	dconf, err := xl.NewDomainConfig(xl.DomainTypePv)
	if err != nil {
		fmt.Printf("NewDomainConfig: %v\n", err)
		return
	}
	dconf.CInfo.Type = xl.DomainTypePv
	// name = "c6-01"
	dconf.CInfo.Name = "c6-01"
	// vcpus=4
	dconf.BInfo.MaxVcpus = 4
	// memory = "2048"
	dconf.BInfo.MaxMemkb = 2048 * 1024
	dconf.BInfo.TargetMemkb = 2048 * 1024
	// on_crash = 'destroy'
	dconf.OnCrash = xl.ActionOnShutdownDestroy
	// bootloader = "pygrub"
	dconf.BInfo.Bootloader = "pygrub"
	// disk = [ 'vdev=hda,format=raw,target=/images/c6-01.raw']
	{
		disk, err := xl.NewDeviceDisk()
		if err != nil {
			fmt.Printf("NewDeviceDisk: %v\n", err)
			return
		}
		disk.Vdev = "hda"
		//disk.DiskBackend = xl.DiskBackendPhy
		disk.Format = xl.DiskFormatRaw
		disk.PdevPath = "/images/c6-01.raw"
		dconf.Disks = append(dconf.Disks, *disk)
	}
	// vif = [ 'mac=5a:5b:d6:f1:d6:b4' ]
	{
		vif, err := xl.NewDeviceNic()
		if err != nil {
			fmt.Printf("NewDeviceNic: %v\n", err)
			return
		}
		vif.Mac = xl.Mac{ 0x5a, 0x5b, 0xd6, 0x31, 0xd6, 0xb4 }
		dconf.Nics = append(dconf.Nics, *vif)
	}
	// serial='pty' # HVM only

	did, err := ctx.DomainCreateNew(dconf)

	if err != nil {
		fmt.Printf("Creating domain: %v\n", err)
		return
	}

	fmt.Printf("Domain %s(%d) created successfully", dconf.CInfo.Name, did)
}

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

#17 lore raw
In reply to George Dunlap
Quoted 8 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.

Furthermore, the current toC array code will convert a nil slice into a zero-length malloc. The resulting pointer is non-NULL, and confuses libxl.

Quoted 6 lines

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).

The toC half of this should be folded into "golang/xenlight:
implement array Go to C marshaling".

Looks good to me. I will make the toC change when I send v5 of my series.

-NR

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