[libvirt] [PATCH v3 00/34] Introduce VIR_STRDUP

Previously this aimed on dropping OOM report from almost everywhere (v1), then just prepare the ground (v2). Now, it just aims on introducing VIR_STRDUP and VIR_STRNDUP which do report OOM error. This will cause rebase conflicts, for sure. Sorry. Patches available at: git://gitorious.org/~zippy2/libvirt/michal-staging.git branch oom4 Michal Privoznik (34): virstring: Introduce VIR_STRDUP and VIR_STRNDUP Adapt to VIR_STRDUP and VIR_STRNDUP in daemon/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/conf/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/cpu/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/esx/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/hyperv/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/libxl/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/locking/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/lxc/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/network/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/node_device/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/interface/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/nwfilter/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/openvz/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/parallels/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/phyp/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/qemu/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/remote/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/rpc/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/secret/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/security/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/storage/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/test/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/uml/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/util/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/vbox/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/vmware/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/vmx/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/xen/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/xenapi/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/xenxs/* Adapt to VIR_STRDUP and VIR_STRNDUP in tests/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/* Introduce syntax-check rule to prefer VIR_STRDUP over strdup HACKING | 11 + cfg.mk | 8 + daemon/libvirtd-config.c | 50 ++-- daemon/libvirtd.c | 29 +-- daemon/remote.c | 161 +++++------- docs/hacking.html.in | 14 + include/libvirt/libvirt.h.in | 10 +- src/conf/capabilities.c | 30 +-- src/conf/cpu_conf.c | 19 +- src/conf/domain_conf.c | 105 +++----- src/conf/domain_event.c | 39 ++- src/conf/node_device_conf.c | 29 +-- src/conf/nwfilter_conf.c | 17 +- src/conf/nwfilter_params.c | 30 +-- src/conf/snapshot_conf.c | 11 +- src/conf/storage_conf.c | 13 +- src/conf/virchrdev.c | 12 +- src/cpu/cpu_generic.c | 8 +- src/cpu/cpu_map.c | 3 +- src/cpu/cpu_powerpc.c | 13 +- src/cpu/cpu_x86.c | 10 +- src/datatypes.c | 76 +++--- src/esx/esx_driver.c | 43 +-- src/esx/esx_interface_driver.c | 7 +- src/esx/esx_network_driver.c | 28 +- src/esx/esx_storage_backend_iscsi.c | 21 +- src/esx/esx_storage_backend_vmfs.c | 16 +- src/esx/esx_util.c | 45 +--- src/esx/esx_vi.c | 79 ++---- src/esx/esx_vi_types.c | 36 +-- src/hyperv/hyperv_driver.c | 50 +--- src/hyperv/hyperv_util.c | 18 +- src/interface/interface_backend_udev.c | 36 +-- src/libvirt.c | 14 +- src/libvirt_private.syms | 2 + src/libxl/libxl_conf.c | 86 ++---- src/libxl/libxl_driver.c | 14 +- src/locking/lock_daemon.c | 30 +-- src/locking/lock_daemon_config.c | 12 +- src/locking/lock_daemon_dispatch.c | 6 +- src/locking/lock_driver_lockd.c | 41 ++- src/locking/lock_driver_sanlock.c | 12 +- src/locking/lock_manager.c | 4 +- src/lxc/lxc_cgroup.c | 3 +- src/lxc/lxc_conf.c | 36 ++- src/lxc/lxc_container.c | 18 +- src/lxc/lxc_controller.c | 20 +- src/lxc/lxc_driver.c | 9 +- src/lxc/lxc_process.c | 7 +- src/network/bridge_driver.c | 34 +-- src/node_device/node_device_driver.c | 33 +-- src/node_device/node_device_hal.c | 13 +- src/node_device/node_device_udev.c | 99 ++----- src/nodeinfo.c | 5 +- src/nwfilter/nwfilter_dhcpsnoop.c | 22 +- src/nwfilter/nwfilter_driver.c | 7 +- src/nwfilter/nwfilter_ebiptables_driver.c | 2 +- src/nwfilter/nwfilter_gentech_driver.c | 5 +- src/nwfilter/nwfilter_learnipaddr.c | 5 +- src/openvz/openvz_conf.c | 45 ++-- src/openvz/openvz_driver.c | 39 ++- src/parallels/parallels_driver.c | 71 +++-- src/parallels/parallels_network.c | 23 +- src/parallels/parallels_storage.c | 62 ++--- src/phyp/phyp_driver.c | 50 +--- src/qemu/qemu_capabilities.c | 79 +++--- src/qemu/qemu_cgroup.c | 4 +- src/qemu/qemu_command.c | 419 ++++++++++++------------------ src/qemu/qemu_conf.c | 58 ++--- src/qemu/qemu_domain.c | 26 +- src/qemu/qemu_driver.c | 113 +++----- src/qemu/qemu_hotplug.c | 15 +- src/qemu/qemu_migration.c | 20 +- src/qemu/qemu_monitor_json.c | 63 ++--- src/qemu/qemu_monitor_text.c | 15 +- src/qemu/qemu_process.c | 64 ++--- src/remote/remote_driver.c | 116 ++++----- src/rpc/gendispatch.pl | 21 +- src/rpc/virnetclient.c | 16 +- src/rpc/virnetmessage.c | 12 +- src/rpc/virnetsaslcontext.c | 6 +- src/rpc/virnetserver.c | 6 +- src/rpc/virnetserverclient.c | 10 +- src/rpc/virnetservermdns.c | 6 +- src/rpc/virnetsocket.c | 10 +- src/rpc/virnetsshsession.c | 76 +++--- src/rpc/virnettlscontext.c | 26 +- src/secret/secret_driver.c | 5 +- src/security/security_apparmor.c | 20 +- src/security/security_dac.c | 23 +- src/security/security_nop.c | 7 +- src/security/security_selinux.c | 79 ++---- src/security/virt-aa-helper.c | 4 +- src/storage/parthelper.c | 5 +- src/storage/storage_backend.c | 22 +- src/storage/storage_backend_disk.c | 26 +- src/storage/storage_backend_fs.c | 34 +-- src/storage/storage_backend_iscsi.c | 17 +- src/storage/storage_backend_logical.c | 32 +-- src/storage/storage_backend_mpath.c | 5 +- src/storage/storage_backend_rbd.c | 5 +- src/storage/storage_backend_scsi.c | 19 +- src/storage/storage_backend_sheepdog.c | 6 +- src/storage/storage_driver.c | 18 +- src/test/test_driver.c | 144 ++++------ src/uml/uml_conf.c | 10 +- src/uml/uml_driver.c | 8 +- src/util/virauth.c | 17 +- src/util/virauthconfig.c | 8 +- src/util/virbitmap.c | 9 +- src/util/vircgroup.c | 36 ++- src/util/vircommand.c | 33 ++- src/util/virconf.c | 34 +-- src/util/virdnsmasq.c | 22 +- src/util/virebtables.c | 34 +-- src/util/virebtables.h | 2 +- src/util/virerror.c | 19 +- src/util/virhash.c | 5 +- src/util/viridentity.c | 15 +- src/util/virinitctl.c | 4 +- src/util/viriptables.c | 4 +- src/util/virjson.c | 18 +- src/util/virkeyfile.c | 13 +- src/util/virlockspace.c | 25 +- src/util/virlog.c | 25 +- src/util/virnetdevmacvlan.c | 16 +- src/util/virnetdevtap.c | 11 +- src/util/virnetdevvportprofile.c | 4 +- src/util/virobject.c | 16 +- src/util/virpci.c | 14 +- src/util/virsexpr.c | 37 +-- src/util/virsocketaddr.c | 9 +- src/util/virstoragefile.c | 18 +- src/util/virstring.c | 91 ++++++- src/util/virstring.h | 62 +++++ src/util/virsysinfo.c | 290 ++++++++------------- src/util/virtypedparam.c | 14 +- src/util/viruri.c | 58 ++--- src/util/virutil.c | 91 +++---- src/util/virxml.c | 5 +- src/vbox/vbox_XPCOMCGlue.c | 6 +- src/vbox/vbox_tmpl.c | 278 +++++++++----------- src/vmware/vmware_conf.c | 28 +- src/vmware/vmware_driver.c | 11 +- src/vmx/vmx.c | 36 +-- src/xen/block_stats.c | 16 +- src/xen/xen_driver.c | 9 +- src/xen/xen_hypervisor.c | 19 +- src/xen/xen_inotify.c | 15 +- src/xen/xend_internal.c | 78 ++---- src/xen/xm_internal.c | 9 +- src/xen/xs_internal.c | 44 ++-- src/xenapi/xenapi_driver.c | 59 ++--- src/xenapi/xenapi_utils.c | 39 +-- src/xenxs/xen_sxpr.c | 192 ++++++-------- src/xenxs/xen_xm.c | 94 +++---- tests/commandhelper.c | 10 +- tests/commandtest.c | 2 +- tests/openvzutilstest.c | 6 +- tests/qemumonitortestutils.c | 15 +- tests/qemuxml2argvtest.c | 23 +- tests/qemuxmlnstest.c | 4 +- tests/securityselinuxhelper.c | 9 +- tests/securityselinuxlabeltest.c | 3 +- tests/securityselinuxtest.c | 9 +- tests/storagebackendsheepdogtest.c | 6 +- tests/testutils.c | 4 +- tests/testutilsqemu.c | 5 +- tests/vircgrouptest.c | 2 +- tests/virnetmessagetest.c | 21 +- tests/vmx2xmltest.c | 9 +- tests/xml2vmxtest.c | 9 +- 172 files changed, 2204 insertions(+), 3501 deletions(-) -- 1.8.1.5

The code adaptation is not done right now, but in subsequent patches. Hence I am not implementing syntax-check rule as it would break compilation. Developers are strongly advised to use these new macros. They are similar to VIR_ALLOC() logic: VIR_STRDUP(dst, src) returns zero on success, -1 otherwise. In case you don't want to report OOM error, use the _QUIET variant of a macro. --- HACKING | 11 +++++++ docs/hacking.html.in | 14 +++++++++ src/libvirt_private.syms | 2 ++ src/util/virstring.c | 74 ++++++++++++++++++++++++++++++++++++++++++++++++ src/util/virstring.h | 62 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 163 insertions(+) diff --git a/HACKING b/HACKING index e8bebd4..7823c08 100644 --- a/HACKING +++ b/HACKING @@ -719,6 +719,17 @@ sizeof(dest) returns something meaningful). Note that this is a macro, so arguments could be evaluated more than once. This is equivalent to virStrncpy(dest, src, strlen(src), sizeof(dest)). + VIR_STRDUP(char *dst, const char *src); + VIR_STRNDUP(char *dst, const char *src, size_t n); + +You should avoid using strdup or strndup directly as they do not report +out-of-memory error. Use VIR_STRDUP() or VIR_STRNDUP macros instead. Note, +that these two behave similar to VIR_ALLOC: on success zero is returned, +otherwise the result is -1 and dst is guaranteed to be NULL. In very specific +cases, when you don't want to report the out-of-memory error, you can use +VIR_STRDUP_QUIET or VIR_STRNDUP_QUIET, but such usage is very rare and usually +considered a flaw. + Variable length string buffer ============================= diff --git a/docs/hacking.html.in b/docs/hacking.html.in index 99933d1..7d9c042 100644 --- a/docs/hacking.html.in +++ b/docs/hacking.html.in @@ -853,6 +853,20 @@ virStrncpy(dest, src, strlen(src), sizeof(dest)). </p> +<pre> + VIR_STRDUP(char *dst, const char *src); + VIR_STRNDUP(char *dst, const char *src, size_t n); +</pre> + <p> + You should avoid using strdup or strndup directly as they do not report + out-of-memory error. Use VIR_STRDUP() or VIR_STRNDUP macros instead. + Note, that these two behave similar to VIR_ALLOC: on success zero is + returned, otherwise the result is -1 and dst is guaranteed to be NULL. In + very specific cases, when you don't want to report the out-of-memory + error, you can use VIR_STRDUP_QUIET or VIR_STRNDUP_QUIET, but such usage + is very rare and usually considered a flaw. + </p> + <h2><a name="strbuf">Variable length string buffer</a></h2> <p> diff --git a/src/libvirt_private.syms b/src/libvirt_private.syms index 98660dc..d4cb4a3 100644 --- a/src/libvirt_private.syms +++ b/src/libvirt_private.syms @@ -1751,11 +1751,13 @@ virSkipSpaces; virSkipSpacesAndBackslash; virSkipSpacesBackwards; virStrcpy; +virStrdup; virStringArrayHasString; virStringFreeList; virStringJoin; virStringSplit; virStrncpy; +virStrndup; virStrToDouble; virStrToLong_i; virStrToLong_l; diff --git a/src/util/virstring.c b/src/util/virstring.c index 9b4cb01..394a558 100644 --- a/src/util/virstring.c +++ b/src/util/virstring.c @@ -515,3 +515,77 @@ virArgvToString(const char *const *argv) return ret; } + +/** + * virStrdup: + * @dest: where to store duplicated string + * @src: the source string to duplicate + * @report: whether to report OOM error, if there is one + * @domcode: error domain code + * @filename: caller's filename + * @funcname: caller's funcname + * @linenr: caller's line number + * + * Wrapper over strdup, which reports OOM error if told so, + * in which case callers wants to pass @domcode, @filename, + * @funcname and @linenr which should represent location in + * caller's body where virStrdup is called from. Consider + * using VIR_STRDUP which sets these automatically. + * + * Returns: 0 on success, -1 otherwise. + */ +int +virStrdup(char **dest, + const char *src, + bool report, + int domcode, + const char *filename, + const char *funcname, + size_t linenr) +{ + if (!(*dest = strdup(src))) { + if (report) + virReportOOMErrorFull(domcode, filename, funcname, linenr); + return -1; + } + + return 0; +} + +/** + * virStrndup: + * @dest: where to store duplicated string + * @src: the source string to duplicate + * @n: how many bytes to copy + * @report: whether to report OOM error, if there is one + * @domcode: error domain code + * @filename: caller's filename + * @funcname: caller's funcname + * @linenr: caller's line number + * + * Wrapper over strndup, which reports OOM error if told so, + * in which case callers wants to pass @domcode, @filename, + * @funcname and @linenr which should represent location in + * caller's body where virStrndup is called from. Consider + * using VIR_STRNDUP which sets these automatically. + * + * Returns: 0 on success, -1 otherwise. + */ +int +virStrndup(char **dest, + const char *src, + size_t n, + bool report, + int domcode, + const char *filename, + const char *funcname, + size_t linenr) +{ + if (!(*dest = strndup(src, n))) { + if (report) + virReportOOMErrorFull(domcode, filename, funcname, linenr); + return -1; + } + + return 0; +} diff --git a/src/util/virstring.h b/src/util/virstring.h index 457caa2..58fa6c5 100644 --- a/src/util/virstring.h +++ b/src/util/virstring.h @@ -87,4 +87,66 @@ char *virStrncpy(char *dest, const char *src, size_t n, size_t destbytes) char *virStrcpy(char *dest, const char *src, size_t destbytes) ATTRIBUTE_RETURN_CHECK; # define virStrcpyStatic(dest, src) virStrcpy((dest), (src), sizeof(dest)) + + +/* Don't call these directly - use the macros below */ +int virStrdup(char **dest, const char *src, bool report, int domcode, + const char *filename, const char *funcname, size_t linenr) + ATTRIBUTE_RETURN_CHECK ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2); + +int virStrndup(char **dest, const char *src, size_t n, bool report, int domcode, + const char *filename, const char *funcname, size_t linenr) + ATTRIBUTE_RETURN_CHECK ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2); + +/** + * VIR_STRDUP: + * @dst: pointer to copied string + * @src: string to duplicate + * + * Duplicate @src string and store it into @dst. + * + * Returns -1 on failure (with OOM error reported), 0 on success + */ +# define VIR_STRDUP(dst, src) virStrdup(&(dst), src, true, VIR_FROM_THIS, \ + __FILE__, __FUNCTION__, __LINE__) + +/** + * VIR_STRDUP_QUIET: + * @dst: pointer to copied string + * @src: string to duplicate + * + * Duplicate @src string and store it into @dst. + * + * Returns -1 on failure, 0 on success + */ +# define VIR_STRDUP_QUIET(dst, src) virStrdup(&(dst), src, false, 0, NULL, NULL, 0) + +/** + * VIR_STRNDUP: + * @dst: pointer to copied string + * @src: string to duplicate + * @n: the maximum number of bytes to copy + * + * Duplicate @src string and store it ino @dst. If @src is longer than @n, + * only @n bytes are copied and terminating null byte '\0' is added. + * + * Returns -1 on failure (with OOM error reported), 0 on success + */ +# define VIR_STRNDUP(dst, src, n) virStrndup(&(dst), src, n, true, \ + VIR_FROM_THIS, __FILE__, \ + __FUNCTION__, __LINE__) + +/** + * VIR_STRNDUP: + * @dst: pointer to copied string + * @src: string to duplicate + * @n: the maximum number of bytes to copy + * + * Duplicate @src string and store it ino @dst. If @src is longer than @n, + * only @n bytes are copied and terminating null byte '\0' is added. + * + * Returns -1 on failure, 0 on success + */ +# define VIR_STRNDUP_QUIET(dst, src, n) virStrndup(&(dst), src, n, false, \ + 0, NULL, NULL, 0) #endif /* __VIR_STRING_H__ */ -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
The code adaptation is not done right now, but in subsequent patches. Hence I am not implementing syntax-check rule as it would break compilation. Developers are strongly advised to use these new macros. They are similar to VIR_ALLOC() logic: VIR_STRDUP(dst, src) returns zero on success, -1 otherwise. In case you don't want to report OOM error, use the _QUIET variant of a macro. --- HACKING | 11 +++++++ docs/hacking.html.in | 14 +++++++++ src/libvirt_private.syms | 2 ++ src/util/virstring.c | 74 ++++++++++++++++++++++++++++++++++++++++++++++++ src/util/virstring.h | 62 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 163 insertions(+)
+++ b/docs/hacking.html.in @@ -853,6 +853,20 @@ virStrncpy(dest, src, strlen(src), sizeof(dest)). </p>
+<pre> + VIR_STRDUP(char *dst, const char *src); + VIR_STRNDUP(char *dst, const char *src, size_t n); +</pre> + <p> + You should avoid using strdup or strndup directly as they do not report + out-of-memory error. Use VIR_STRDUP() or VIR_STRNDUP macros instead.
Hmm, you weren't consistent on whether to use () after the macro name...
+ Note, that these two behave similar to VIR_ALLOC: on success zero is + returned, otherwise the result is -1 and dst is guaranteed to be NULL. In + very specific cases, when you don't want to report the out-of-memory + error, you can use VIR_STRDUP_QUIET or VIR_STRNDUP_QUIET, but such usage + is very rare and usually considered a flaw.
Since most of the references didn't use it, I'd drop the one () you did use.
+++ b/src/util/virstring.h @@ -87,4 +87,66 @@ char *virStrncpy(char *dest, const char *src, size_t n, size_t destbytes) char *virStrcpy(char *dest, const char *src, size_t destbytes) ATTRIBUTE_RETURN_CHECK; # define virStrcpyStatic(dest, src) virStrcpy((dest), (src), sizeof(dest)) + + +/* Don't call these directly - use the macros below */ +int virStrdup(char **dest, const char *src, bool report, int domcode, + const char *filename, const char *funcname, size_t linenr) + ATTRIBUTE_RETURN_CHECK ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2);
You know, we COULD play games where we allow a NULL src (and in that case silently set dest to NULL, without an OOM message even when report is true), so that it is easier to blindly use src even if it stems from a failure earlier in the function. That is, right now, we have to do: void foo(char *source) { char *copy = NULL; if (source && VIR_STRDUP(copy, source) < 0) goto cleanup; do stuff with copy cleanup: VIR_FREE(copy); } whereas my proposal to drop ATTRIBUTE_NONNULL(2) would let us do the slightly shorter: void foo(char *source) { char *copy; if (VIR_STRDUP(copy, source) < 0) goto cleanup; do stuff with copy cleanup: VIR_FREE(copy); } That is, just because strdup(NULL) crashes with SEGV doesn't mean our function has to; and we could argue that duplicating NULL into NULL without OOM error is useful behavior. Maybe even return -1 for OOM, 0 for duplicating NULL, and 1 for actual duplication (so callers can use <0 vs. <=0 depending on what they care about). But I'm not sure if we need that yet (and it can be done as a separate patch, if we do decide that it simplifies things without the risk of problems).
+/** + * VIR_STRDUP: + * @dst: pointer to copied string
Maybe make it more obvious that you don't pass &src, by having this (and the other three macros) read: @dst: variable to hold result (char*, not char**)
+/** + * VIR_STRNDUP: + * @dst: pointer to copied string + * @src: string to duplicate + * @n: the maximum number of bytes to copy + * + * Duplicate @src string and store it ino @dst. If @src is longer than @n,
s/ino/into/ (here, and below) My findings (other than the suggestion of accepting NULL source, which would be a separate patch anyways) are minor, so I'm okay giving ACK; it might be worth pushing this in now so we can start using it in new code, even while still waiting for the rest of the series to be reviewed. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- daemon/libvirtd-config.c | 50 +++++---------- daemon/libvirtd.c | 29 +++++---- daemon/remote.c | 161 ++++++++++++++++++----------------------------- 3 files changed, 92 insertions(+), 148 deletions(-) diff --git a/daemon/libvirtd-config.c b/daemon/libvirtd-config.c index efb564e..346f7f5 100644 --- a/daemon/libvirtd-config.c +++ b/daemon/libvirtd-config.c @@ -59,15 +59,11 @@ remoteConfigGetStringList(virConfPtr conf, const char *key, char ***list_arg, key); return -1; } - list[0] = strdup(p->str); - list[1] = NULL; - if (list[0] == NULL) { - virReportError(VIR_ERR_CONFIG_UNSUPPORTED, - _("failed to allocate memory for %s config list value"), - key); + if (VIR_STRDUP(list[0], p->str) < 0) { VIR_FREE(list); return -1; } + list[1] = NULL; break; case VIR_CONF_LIST: { @@ -90,15 +86,11 @@ remoteConfigGetStringList(virConfPtr conf, const char *key, char ***list_arg, VIR_FREE(list); return -1; } - list[i] = strdup(pp->str); - if (list[i] == NULL) { + if (VIR_STRDUP(list[i], pp->str) < 0) { int j; for (j = 0 ; j < i ; j++) VIR_FREE(list[j]); VIR_FREE(list); - virReportError(VIR_ERR_CONFIG_UNSUPPORTED, - _("failed to allocate memory for %s config list value"), - key); return -1; } @@ -136,8 +128,8 @@ checkType(virConfValuePtr p, const char *filename, } /* If there is no config data for the key, #var_name, then do nothing. - If there is valid data of type VIR_CONF_STRING, and strdup succeeds, - store the result in var_name. Otherwise, (i.e. invalid type, or strdup + If there is valid data of type VIR_CONF_STRING, and VIR_STRDUP succeeds, + store the result in var_name. Otherwise, (i.e. invalid type, or VIR_STRDUP failure), give a diagnostic and "goto" the cleanup-and-fail label. */ #define GET_CONF_STR(conf, filename, var_name) \ do { \ @@ -146,10 +138,8 @@ checkType(virConfValuePtr p, const char *filename, if (checkType(p, filename, #var_name, VIR_CONF_STRING) < 0) \ goto error; \ VIR_FREE(data->var_name); \ - if (!(data->var_name = strdup(p->str))) { \ - virReportOOMError(); \ + if (VIR_STRDUP(data->var_name, p->str) < 0) \ goto error; \ - } \ } \ } while (0) @@ -200,8 +190,8 @@ int daemonConfigFilePath(bool privileged, char **configfile) { if (privileged) { - if (!(*configfile = strdup(SYSCONFDIR "/libvirt/libvirtd.conf"))) - goto no_memory; + if (VIR_STRDUP(*configfile, SYSCONFDIR "/libvirt/libvirtd.conf") < 0) + goto error; } else { char *configdir = NULL; @@ -238,10 +228,9 @@ daemonConfigNew(bool privileged ATTRIBUTE_UNUSED) data->listen_tls = 1; data->listen_tcp = 0; - if (!(data->tls_port = strdup(LIBVIRTD_TLS_PORT))) - goto no_memory; - if (!(data->tcp_port = strdup(LIBVIRTD_TCP_PORT))) - goto no_memory; + if (VIR_STRDUP(data->tls_port, LIBVIRTD_TLS_PORT) < 0 || + VIR_STRDUP(data->tcp_port, LIBVIRTD_TCP_PORT) < 0) + goto error; /* Only default to PolicyKit if running as root */ #if WITH_POLKIT @@ -256,14 +245,10 @@ daemonConfigNew(bool privileged ATTRIBUTE_UNUSED) } #endif - if (data->auth_unix_rw == REMOTE_AUTH_POLKIT) - data->unix_sock_rw_perms = strdup("0777"); /* Allow world */ - else - data->unix_sock_rw_perms = strdup("0700"); /* Allow user only */ - data->unix_sock_ro_perms = strdup("0777"); /* Always allow world */ - if (!data->unix_sock_ro_perms || - !data->unix_sock_rw_perms) - goto no_memory; + if (VIR_STRDUP(data->unix_sock_rw_perms, + data->auth_unix_rw == REMOTE_AUTH_POLKIT ? "0777" : "0700") < 0 || + VIR_STRDUP(data->unix_sock_ro_perms, "0777") < 0) + goto error; #if WITH_SASL data->auth_tcp = REMOTE_AUTH_SASL; @@ -315,6 +300,7 @@ daemonConfigNew(bool privileged ATTRIBUTE_UNUSED) no_memory: virReportOOMError(); +error: daemonConfigFree(data); return NULL; } @@ -382,10 +368,8 @@ daemonConfigLoadOptions(struct daemonConfig *data, */ if (data->auth_unix_rw == REMOTE_AUTH_POLKIT) { VIR_FREE(data->unix_sock_rw_perms); - if (!(data->unix_sock_rw_perms = strdup("0777"))) { - virReportOOMError(); + if (VIR_STRDUP(data->unix_sock_rw_perms, "0777") < 0) goto error; - } } #endif if (remoteConfigGetAuth(conf, "auth_unix_ro", &data->auth_unix_ro, filename) < 0) diff --git a/daemon/libvirtd.c b/daemon/libvirtd.c index 9f81a0f..9bf0e6f 100644 --- a/daemon/libvirtd.c +++ b/daemon/libvirtd.c @@ -241,8 +241,8 @@ daemonPidFilePath(bool privileged, char **pidfile) { if (privileged) { - if (!(*pidfile = strdup(LOCALSTATEDIR "/run/libvirtd.pid"))) - goto no_memory; + if (VIR_STRDUP(*pidfile, LOCALSTATEDIR "/run/libvirtd.pid") < 0) + goto error; } else { char *rundir = NULL; mode_t old_umask; @@ -287,10 +287,10 @@ daemonUnixSocketPaths(struct daemonConfig *config, goto no_memory; } else { if (privileged) { - if (!(*sockfile = strdup(LOCALSTATEDIR "/run/libvirt/libvirt-sock"))) - goto no_memory; - if (!(*rosockfile = strdup(LOCALSTATEDIR "/run/libvirt/libvirt-sock-ro"))) - goto no_memory; + if (VIR_STRDUP(*sockfile, LOCALSTATEDIR "/run/libvirt/libvirt-sock") < 0) + goto error; + if (VIR_STRDUP(*rosockfile, LOCALSTATEDIR "/run/libvirt/libvirt-sock-ro") < 0) + goto error; } else { char *rundir = NULL; mode_t old_umask; @@ -961,7 +961,8 @@ static int migrateProfile(void) config_home = getenv("XDG_CONFIG_HOME"); if (config_home && config_home[0] != '\0') { - xdg_dir = strdup(config_home); + if (VIR_STRDUP(xdg_dir, config_home) < 0) + goto cleanup; } else { if (virAsprintf(&xdg_dir, "%s/.config", home) < 0) { goto cleanup; @@ -1172,7 +1173,7 @@ int main(int argc, char **argv) { case 'p': VIR_FREE(pid_file); - if (!(pid_file = strdup(optarg))) { + if (VIR_STRDUP_QUIET(pid_file, optarg) < 0) { VIR_ERROR(_("Can't allocate memory")); exit(EXIT_FAILURE); } @@ -1180,7 +1181,7 @@ int main(int argc, char **argv) { case 'f': VIR_FREE(remote_config_file); - if (!(remote_config_file = strdup(optarg))) { + if (VIR_STRDUP_QUIET(remote_config_file, optarg) < 0) { VIR_ERROR(_("Can't allocate memory")); exit(EXIT_FAILURE); } @@ -1287,7 +1288,10 @@ int main(int argc, char **argv) { /* Ensure the rundir exists (on tmpfs on some systems) */ if (privileged) { - run_dir = strdup(LOCALSTATEDIR "/run/libvirt"); + if (VIR_STRDUP_QUIET(run_dir, LOCALSTATEDIR "/run/libvirt") < 0) { + VIR_ERROR(_("Can't allocate memory")); + goto cleanup; + } } else { run_dir = virGetUserRuntimeDirectory(); @@ -1296,11 +1300,6 @@ int main(int argc, char **argv) { goto cleanup; } } - if (!run_dir) { - virReportOOMError(); - goto cleanup; - } - if (privileged) old_umask = umask(022); else diff --git a/daemon/remote.c b/daemon/remote.c index 056afff..1f7cbe9 100644 --- a/daemon/remote.c +++ b/daemon/remote.c @@ -234,12 +234,9 @@ static int remoteRelayDomainEventIOError(virConnectPtr conn ATTRIBUTE_UNUSED, /* build return data */ memset(&data, 0, sizeof(data)); - data.srcPath = strdup(srcPath); - if (data.srcPath == NULL) - goto mem_error; - data.devAlias = strdup(devAlias); - if (data.devAlias == NULL) - goto mem_error; + if (VIR_STRDUP(data.srcPath, srcPath) < 0 || + VIR_STRDUP(data.devAlias, devAlias) < 0) + goto error; make_nonnull_domain(&data.dom, dom); data.action = action; @@ -248,8 +245,7 @@ static int remoteRelayDomainEventIOError(virConnectPtr conn ATTRIBUTE_UNUSED, (xdrproc_t)xdr_remote_domain_event_io_error_msg, &data); return 0; -mem_error: - virReportOOMError(); +error: VIR_FREE(data.srcPath); VIR_FREE(data.devAlias); return -1; @@ -275,16 +271,11 @@ static int remoteRelayDomainEventIOErrorReason(virConnectPtr conn ATTRIBUTE_UNUS /* build return data */ memset(&data, 0, sizeof(data)); - data.srcPath = strdup(srcPath); - if (data.srcPath == NULL) - goto mem_error; - data.devAlias = strdup(devAlias); - if (data.devAlias == NULL) - goto mem_error; + if (VIR_STRDUP(data.srcPath, srcPath) < 0 || + VIR_STRDUP(data.devAlias, devAlias) < 0 || + VIR_STRDUP(data.reason, reason) < 0) + goto error; data.action = action; - data.reason = strdup(reason); - if (data.reason == NULL) - goto mem_error; make_nonnull_domain(&data.dom, dom); @@ -294,8 +285,7 @@ static int remoteRelayDomainEventIOErrorReason(virConnectPtr conn ATTRIBUTE_UNUS return 0; -mem_error: - virReportOOMError(); +error: VIR_FREE(data.srcPath); VIR_FREE(data.devAlias); VIR_FREE(data.reason); @@ -334,35 +324,23 @@ static int remoteRelayDomainEventGraphics(virConnectPtr conn ATTRIBUTE_UNUSED, data.phase = phase; data.local.family = local->family; data.remote.family = remote->family; - data.authScheme = strdup(authScheme); - if (data.authScheme == NULL) - goto mem_error; - - data.local.node = strdup(local->node); - if (data.local.node == NULL) - goto mem_error; - data.local.service = strdup(local->service); - if (data.local.service == NULL) - goto mem_error; - - data.remote.node = strdup(remote->node); - if (data.remote.node == NULL) - goto mem_error; - data.remote.service = strdup(remote->service); - if (data.remote.service == NULL) - goto mem_error; + if (VIR_STRDUP(data.authScheme, authScheme) < 0 || + VIR_STRDUP(data.local.node, local->node) < 0 || + VIR_STRDUP(data.local.service, local->service) < 0 || + VIR_STRDUP(data.remote.node, remote->node) < 0 || + VIR_STRDUP(data.remote.service, remote->service) < 0) + goto error; data.subject.subject_len = subject->nidentity; - if (VIR_ALLOC_N(data.subject.subject_val, data.subject.subject_len) < 0) - goto mem_error; + if (VIR_ALLOC_N(data.subject.subject_val, data.subject.subject_len) < 0) { + virReportOOMError(); + goto error; + } for (i = 0 ; i < data.subject.subject_len ; i++) { - data.subject.subject_val[i].type = strdup(subject->identities[i].type); - if (data.subject.subject_val[i].type == NULL) - goto mem_error; - data.subject.subject_val[i].name = strdup(subject->identities[i].name); - if (data.subject.subject_val[i].name == NULL) - goto mem_error; + if (VIR_STRDUP(data.subject.subject_val[i].type, subject->identities[i].type) < 0 || + VIR_STRDUP(data.subject.subject_val[i].name, subject->identities[i].name) < 0) + goto error; } make_nonnull_domain(&data.dom, dom); @@ -372,8 +350,7 @@ static int remoteRelayDomainEventGraphics(virConnectPtr conn ATTRIBUTE_UNUSED, return 0; -mem_error: - virReportOOMError(); +error: VIR_FREE(data.authScheme); VIR_FREE(data.local.node); VIR_FREE(data.local.service); @@ -407,9 +384,8 @@ static int remoteRelayDomainEventBlockJob(virConnectPtr conn ATTRIBUTE_UNUSED, /* build return data */ memset(&data, 0, sizeof(data)); - data.path = strdup(path); - if (data.path == NULL) - goto mem_error; + if (VIR_STRDUP(data.path, path) < 0) + goto error; data.type = type; data.status = status; make_nonnull_domain(&data.dom, dom); @@ -419,9 +395,7 @@ static int remoteRelayDomainEventBlockJob(virConnectPtr conn ATTRIBUTE_UNUSED, (xdrproc_t)xdr_remote_domain_event_block_job_msg, &data); return 0; - -mem_error: - virReportOOMError(); +error: VIR_FREE(data.path); return -1; } @@ -473,18 +447,18 @@ static int remoteRelayDomainEventDiskChange(virConnectPtr conn ATTRIBUTE_UNUSED, memset(&data, 0, sizeof(data)); if (oldSrcPath && ((VIR_ALLOC(oldSrcPath_p) < 0) || - !(*oldSrcPath_p = strdup(oldSrcPath)))) + VIR_STRDUP(*oldSrcPath_p, oldSrcPath) < 0)) goto mem_error; if (newSrcPath && ((VIR_ALLOC(newSrcPath_p) < 0) || - !(*newSrcPath_p = strdup(newSrcPath)))) + VIR_STRDUP(*newSrcPath_p, newSrcPath) < 0)) goto mem_error; data.oldSrcPath = oldSrcPath_p; data.newSrcPath = newSrcPath_p; - if (!(data.devAlias = strdup(devAlias))) - goto mem_error; + if (VIR_STRDUP(data.devAlias, devAlias) < 0) + goto error; data.reason = reason; make_nonnull_domain(&data.dom, dom); @@ -496,9 +470,10 @@ static int remoteRelayDomainEventDiskChange(virConnectPtr conn ATTRIBUTE_UNUSED, return 0; mem_error: + virReportOOMError(); +error: VIR_FREE(oldSrcPath_p); VIR_FREE(newSrcPath_p); - virReportOOMError(); return -1; } @@ -520,10 +495,8 @@ static int remoteRelayDomainEventTrayChange(virConnectPtr conn ATTRIBUTE_UNUSED, /* build return data */ memset(&data, 0, sizeof(data)); - if (!(data.devAlias = strdup(devAlias))) { - virReportOOMError(); + if (VIR_STRDUP(data.devAlias, devAlias) < 0) return -1; - } data.reason = reason; make_nonnull_domain(&data.dom, dom); @@ -850,11 +823,8 @@ remoteSerializeTypedParameters(virTypedParameterPtr params, } /* remoteDispatchClientRequest will free this: */ - val[j].field = strdup(params[i].field); - if (val[j].field == NULL) { - virReportOOMError(); + if (VIR_STRDUP(val[j].field, params[i].field) < 0) goto cleanup; - } val[j].value.type = params[i].type; switch (params[i].type) { case VIR_TYPED_PARAM_INT: @@ -876,12 +846,8 @@ remoteSerializeTypedParameters(virTypedParameterPtr params, val[j].value.remote_typed_param_value_u.b = params[i].value.b; break; case VIR_TYPED_PARAM_STRING: - val[j].value.remote_typed_param_value_u.s = - strdup(params[i].value.s); - if (val[j].value.remote_typed_param_value_u.s == NULL) { - virReportOOMError(); + if (VIR_STRDUP(val[j].value.remote_typed_param_value_u.s, params[i].value.s) < 0) goto cleanup; - } break; default: virReportError(VIR_ERR_RPC, _("unknown parameter type: %d"), @@ -966,12 +932,9 @@ remoteDeserializeTypedParameters(remote_typed_param *args_params_val, args_params_val[i].value.remote_typed_param_value_u.b; break; case VIR_TYPED_PARAM_STRING: - params[i].value.s = - strdup(args_params_val[i].value.remote_typed_param_value_u.s); - if (params[i].value.s == NULL) { - virReportOOMError(); + if (VIR_STRDUP(params[i].value.s, + args_params_val[i].value.remote_typed_param_value_u.s) < 0) goto cleanup; - } break; default: virReportError(VIR_ERR_INTERNAL_ERROR, _("unknown parameter type: %d"), @@ -2152,9 +2115,8 @@ remoteDispatchNodeGetCPUStats(virNetServerPtr server ATTRIBUTE_UNUSED, for (i = 0; i < nparams; ++i) { /* remoteDispatchClientRequest will free this: */ - ret->params.params_val[i].field = strdup(params[i].field); - if (ret->params.params_val[i].field == NULL) - goto no_memory; + if (VIR_STRDUP(ret->params.params_val[i].field, params[i].field) < 0) + goto cleanup; ret->params.params_val[i].value = params[i].value; } @@ -2231,9 +2193,8 @@ remoteDispatchNodeGetMemoryStats(virNetServerPtr server ATTRIBUTE_UNUSED, for (i = 0; i < nparams; ++i) { /* remoteDispatchClientRequest will free this: */ - ret->params.params_val[i].field = strdup(params[i].field); - if (ret->params.params_val[i].field == NULL) - goto no_memory; + if (VIR_STRDUP(ret->params.params_val[i].field, params[i].field) < 0) + goto cleanup; ret->params.params_val[i].value = params[i].value; } @@ -3109,9 +3070,8 @@ remoteDispatchNodeDeviceGetParent(virNetServerPtr server ATTRIBUTE_UNUSED, virReportOOMError(); goto cleanup; } - if (!(*parent_p = strdup(parent))) { + if (VIR_STRDUP(*parent_p, parent) < 0) { VIR_FREE(parent_p); - virReportOOMError(); goto cleanup; } ret->parent = parent_p; @@ -4779,14 +4739,14 @@ static void make_nonnull_domain(remote_nonnull_domain *dom_dst, virDomainPtr dom_src) { dom_dst->id = dom_src->id; - dom_dst->name = strdup(dom_src->name); + ignore_value(VIR_STRDUP_QUIET(dom_dst->name, dom_src->name)); memcpy(dom_dst->uuid, dom_src->uuid, VIR_UUID_BUFLEN); } static void make_nonnull_network(remote_nonnull_network *net_dst, virNetworkPtr net_src) { - net_dst->name = strdup(net_src->name); + ignore_value(VIR_STRDUP_QUIET(net_dst->name, net_src->name)); memcpy(net_dst->uuid, net_src->uuid, VIR_UUID_BUFLEN); } @@ -4794,29 +4754,29 @@ static void make_nonnull_interface(remote_nonnull_interface *interface_dst, virInterfacePtr interface_src) { - interface_dst->name = strdup(interface_src->name); - interface_dst->mac = strdup(interface_src->mac); + ignore_value(VIR_STRDUP_QUIET(interface_dst->name, interface_src->name)); + ignore_value(VIR_STRDUP_QUIET(interface_dst->mac, interface_src->mac)); } static void make_nonnull_storage_pool(remote_nonnull_storage_pool *pool_dst, virStoragePoolPtr pool_src) { - pool_dst->name = strdup(pool_src->name); + ignore_value(VIR_STRDUP_QUIET(pool_dst->name, pool_src->name)); memcpy(pool_dst->uuid, pool_src->uuid, VIR_UUID_BUFLEN); } static void make_nonnull_storage_vol(remote_nonnull_storage_vol *vol_dst, virStorageVolPtr vol_src) { - vol_dst->pool = strdup(vol_src->pool); - vol_dst->name = strdup(vol_src->name); - vol_dst->key = strdup(vol_src->key); + ignore_value(VIR_STRDUP_QUIET(vol_dst->pool, vol_src->pool)); + ignore_value(VIR_STRDUP_QUIET(vol_dst->name, vol_src->name)); + ignore_value(VIR_STRDUP_QUIET(vol_dst->key, vol_src->key)); } static void make_nonnull_node_device(remote_nonnull_node_device *dev_dst, virNodeDevicePtr dev_src) { - dev_dst->name = strdup(dev_src->name); + ignore_value(VIR_STRDUP_QUIET(dev_dst->name, dev_src->name)); } static void @@ -4824,20 +4784,20 @@ make_nonnull_secret(remote_nonnull_secret *secret_dst, virSecretPtr secret_src) { memcpy(secret_dst->uuid, secret_src->uuid, VIR_UUID_BUFLEN); secret_dst->usageType = secret_src->usageType; - secret_dst->usageID = strdup(secret_src->usageID); + ignore_value(VIR_STRDUP_QUIET(secret_dst->usageID, secret_src->usageID)); } static void make_nonnull_nwfilter(remote_nonnull_nwfilter *nwfilter_dst, virNWFilterPtr nwfilter_src) { - nwfilter_dst->name = strdup(nwfilter_src->name); + ignore_value(VIR_STRDUP_QUIET(nwfilter_dst->name, nwfilter_src->name)); memcpy(nwfilter_dst->uuid, nwfilter_src->uuid, VIR_UUID_BUFLEN); } static void make_nonnull_domain_snapshot(remote_nonnull_domain_snapshot *snapshot_dst, virDomainSnapshotPtr snapshot_src) { - snapshot_dst->name = strdup(snapshot_src->name); + ignore_value(VIR_STRDUP_QUIET(snapshot_dst->name, snapshot_src->name)); make_nonnull_domain(&snapshot_dst->dom, snapshot_src->domain); } @@ -4850,12 +4810,14 @@ remoteSerializeDomainDiskErrors(virDomainDiskErrorPtr errors, remote_domain_disk_error *val = NULL; int i = 0; - if (VIR_ALLOC_N(val, nerrors) < 0) - goto no_memory; + if (VIR_ALLOC_N(val, nerrors) < 0) { + virReportOOMError(); + goto error; + } for (i = 0; i < nerrors; i++) { - if (!(val[i].disk = strdup(errors[i].disk))) - goto no_memory; + if (VIR_STRDUP(val[i].disk, errors[i].disk) < 0) + goto error; val[i].error = errors[i].error; } @@ -4864,13 +4826,12 @@ remoteSerializeDomainDiskErrors(virDomainDiskErrorPtr errors, return 0; -no_memory: +error: if (val) { int j; for (j = 0; j < i; j++) VIR_FREE(val[j].disk); VIR_FREE(val); } - virReportOOMError(); return -1; } -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- daemon/libvirtd-config.c | 50 +++++---------- daemon/libvirtd.c | 29 +++++---- daemon/remote.c | 161 ++++++++++++++++++----------------------------- 3 files changed, 92 insertions(+), 148 deletions(-)
Good sign that our interface is nice, because using it shrinks the code base.
@@ -287,10 +287,10 @@ daemonUnixSocketPaths(struct daemonConfig *config, goto no_memory; } else { if (privileged) { - if (!(*sockfile = strdup(LOCALSTATEDIR "/run/libvirt/libvirt-sock"))) - goto no_memory; - if (!(*rosockfile = strdup(LOCALSTATEDIR "/run/libvirt/libvirt-sock-ro"))) - goto no_memory; + if (VIR_STRDUP(*sockfile, LOCALSTATEDIR "/run/libvirt/libvirt-sock") < 0) + goto error; + if (VIR_STRDUP(*rosockfile, LOCALSTATEDIR "/run/libvirt/libvirt-sock-ro") < 0) + goto error;
Could merge these two 'if' into one, especially since you were doing it elsewhere in this patch, but not essential.
@@ -1172,7 +1173,7 @@ int main(int argc, char **argv) {
case 'p': VIR_FREE(pid_file); - if (!(pid_file = strdup(optarg))) { + if (VIR_STRDUP_QUIET(pid_file, optarg) < 0) { VIR_ERROR(_("Can't allocate memory")); exit(EXIT_FAILURE);
One of the few cases where _QUIET is right, since main() is early enough that normal error reporting may not be initialized yet :)
@@ -473,18 +447,18 @@ static int remoteRelayDomainEventDiskChange(virConnectPtr conn ATTRIBUTE_UNUSED, memset(&data, 0, sizeof(data)); if (oldSrcPath && ((VIR_ALLOC(oldSrcPath_p) < 0) || - !(*oldSrcPath_p = strdup(oldSrcPath)))) + VIR_STRDUP(*oldSrcPath_p, oldSrcPath) < 0)) goto mem_error;
Yep, I said I could live with the double OOM for now, and that we'll clean it up when we make our next pass over VIR_ALLOC.
@@ -4779,14 +4739,14 @@ static void make_nonnull_domain(remote_nonnull_domain *dom_dst, virDomainPtr dom_src) { dom_dst->id = dom_src->id; - dom_dst->name = strdup(dom_src->name); + ignore_value(VIR_STRDUP_QUIET(dom_dst->name, dom_src->name)); memcpy(dom_dst->uuid, dom_src->uuid, VIR_UUID_BUFLEN);
Aargh, I promised to work on this, and still haven't gotten around to it. But it's an independent cleanup to make the make_nonnull_ functions not return half-baked objects, so doesn't hold up your patch. ACK. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/conf/capabilities.c | 30 +++++-------- src/conf/cpu_conf.c | 19 ++++---- src/conf/domain_conf.c | 105 ++++++++++++++------------------------------ src/conf/domain_event.c | 39 ++++++++-------- src/conf/node_device_conf.c | 29 ++++++------ src/conf/nwfilter_conf.c | 17 ++----- src/conf/nwfilter_params.c | 30 ++++--------- src/conf/snapshot_conf.c | 11 ++--- src/conf/storage_conf.c | 13 ++---- src/conf/virchrdev.c | 12 ++--- 10 files changed, 107 insertions(+), 198 deletions(-) diff --git a/src/conf/capabilities.c b/src/conf/capabilities.c index 5340b63..fa05ad0 100644 --- a/src/conf/capabilities.c +++ b/src/conf/capabilities.c @@ -31,7 +31,7 @@ #include "viruuid.h" #include "cpu_conf.h" #include "virerror.h" - +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_CAPABILITIES @@ -228,7 +228,7 @@ virCapabilitiesAddHostFeature(virCapsPtr caps, caps->host.nfeatures, 1) < 0) return -1; - if ((caps->host.features[caps->host.nfeatures] = strdup(name)) == NULL) + if (VIR_STRDUP(caps->host.features[caps->host.nfeatures], name) < 0) return -1; caps->host.nfeatures++; @@ -250,7 +250,7 @@ virCapabilitiesAddHostMigrateTransport(virCapsPtr caps, caps->host.nmigrateTrans, 1) < 0) return -1; - if ((caps->host.migrateTrans[caps->host.nmigrateTrans] = strdup(name)) == NULL) + if (VIR_STRDUP(caps->host.migrateTrans[caps->host.nmigrateTrans], name) < 0) return -1; caps->host.nmigrateTrans++; @@ -334,7 +334,7 @@ virCapabilitiesAllocMachines(const char *const *names, int nnames) for (i = 0; i < nnames; i++) { if (VIR_ALLOC(machines[i]) < 0 || - !(machines[i]->name = strdup(names[i]))) { + VIR_STRDUP(machines[i]->name, names[i]) < 0) { virCapabilitiesFreeMachines(machines, nnames); return NULL; } @@ -392,17 +392,14 @@ virCapabilitiesAddGuest(virCapsPtr caps, if (VIR_ALLOC(guest) < 0) goto no_memory; - if ((guest->ostype = strdup(ostype)) == NULL) + if (VIR_STRDUP(guest->ostype, ostype) < 0) goto no_memory; guest->arch.id = arch; guest->arch.wordsize = virArchGetWordSize(arch); - if (emulator && - (guest->arch.defaultInfo.emulator = strdup(emulator)) == NULL) - goto no_memory; - if (loader && - (guest->arch.defaultInfo.loader = strdup(loader)) == NULL) + if ((emulator && VIR_STRDUP(guest->arch.defaultInfo.emulator, emulator) < 0) || + (loader && VIR_STRDUP(guest->arch.defaultInfo.loader, loader) < 0)) goto no_memory; if (VIR_RESIZE_N(caps->guests, caps->nguests_max, @@ -448,14 +445,9 @@ virCapabilitiesAddGuestDomain(virCapsGuestPtr guest, if (VIR_ALLOC(dom) < 0) goto no_memory; - if ((dom->type = strdup(hvtype)) == NULL) - goto no_memory; - - if (emulator && - (dom->info.emulator = strdup(emulator)) == NULL) - goto no_memory; - if (loader && - (dom->info.loader = strdup(loader)) == NULL) + if (VIR_STRDUP(dom->type, hvtype) < 0 || + (emulator && VIR_STRDUP(dom->info.emulator, emulator) < 0) || + (loader && VIR_STRDUP(dom->info.loader, loader) < 0)) goto no_memory; if (VIR_RESIZE_N(guest->arch.domains, guest->arch.ndomains_max, @@ -497,7 +489,7 @@ virCapabilitiesAddGuestFeature(virCapsGuestPtr guest, if (VIR_ALLOC(feature) < 0) goto no_memory; - if ((feature->name = strdup(name)) == NULL) + if (VIR_STRDUP(feature->name, name) < 0) goto no_memory; feature->defaultOn = defaultOn; feature->toggle = toggle; diff --git a/src/conf/cpu_conf.c b/src/conf/cpu_conf.c index 6aaee75..8bd51fe 100644 --- a/src/conf/cpu_conf.c +++ b/src/conf/cpu_conf.c @@ -99,10 +99,10 @@ virCPUDefCopyModel(virCPUDefPtr dst, { unsigned int i; - if ((src->model && !(dst->model = strdup(src->model))) - || (src->vendor && !(dst->vendor = strdup(src->vendor))) - || (src->vendor_id && !(dst->vendor_id = strdup(src->vendor_id))) - || VIR_ALLOC_N(dst->features, src->nfeatures) < 0) + if ((src->model && VIR_STRDUP(dst->model, src->model) < 0) || + (src->vendor && VIR_STRDUP(dst->vendor, src->vendor) < 0) || + (src->vendor_id && VIR_STRDUP(dst->vendor_id, src->vendor_id) < 0) || + VIR_ALLOC_N(dst->features, src->nfeatures) < 0) goto no_memory; dst->nfeatures_max = dst->nfeatures = src->nfeatures; @@ -118,7 +118,7 @@ virCPUDefCopyModel(virCPUDefPtr dst, dst->features[i].policy = src->features[i].policy; } - if (!(dst->features[i].name = strdup(src->features[i].name))) + if (VIR_STRDUP(dst->features[i].name, src->features[i].name) < 0) goto no_memory; } @@ -167,8 +167,8 @@ virCPUDefCopy(const virCPUDefPtr cpu) if (!copy->cells[i].cpumask) goto no_memory; - if (!(copy->cells[i].cpustr = strdup(cpu->cells[i].cpustr))) - goto no_memory; + if (VIR_STRDUP(copy->cells[i].cpustr, cpu->cells[i].cpustr) < 0) + goto error; } copy->cells_cpus = cpu->cells_cpus; } @@ -694,8 +694,8 @@ virCPUDefAddFeature(virCPUDefPtr def, if (def->type == VIR_CPU_TYPE_HOST) policy = -1; - if (!(def->features[def->nfeatures].name = strdup(name))) - goto no_memory; + if (VIR_STRDUP(def->features[def->nfeatures].name, name) < 0) + goto error; def->features[def->nfeatures].policy = policy; def->nfeatures++; @@ -704,6 +704,7 @@ virCPUDefAddFeature(virCPUDefPtr def, no_memory: virReportOOMError(); +error: return -1; } diff --git a/src/conf/domain_conf.c b/src/conf/domain_conf.c index fe97c02..7e1b530 100644 --- a/src/conf/domain_conf.c +++ b/src/conf/domain_conf.c @@ -1352,59 +1352,42 @@ virDomainChrSourceDefCopy(virDomainChrSourceDefPtr dest, case VIR_DOMAIN_CHR_TYPE_FILE: case VIR_DOMAIN_CHR_TYPE_PIPE: if (src->data.file.path && - !(dest->data.file.path = strdup(src->data.file.path))) { - virReportOOMError(); + VIR_STRDUP(dest->data.file.path, src->data.file.path) < 0) return -1; - } break; case VIR_DOMAIN_CHR_TYPE_UDP: if (src->data.udp.bindHost && - !(dest->data.udp.bindHost = strdup(src->data.udp.bindHost))) { - virReportOOMError(); + VIR_STRDUP(dest->data.udp.bindHost, src->data.udp.bindHost) < 0) return -1; - } if (src->data.udp.bindService && - !(dest->data.udp.bindService = strdup(src->data.udp.bindService))) { - virReportOOMError(); + VIR_STRDUP(dest->data.udp.bindService, src->data.udp.bindService) < 0) return -1; - } if (src->data.udp.connectHost && - !(dest->data.udp.connectHost = strdup(src->data.udp.connectHost))) { - virReportOOMError(); + VIR_STRDUP(dest->data.udp.connectHost, src->data.udp.connectHost) < 0) return -1; - } - if (src->data.udp.connectService && - !(dest->data.udp.connectService = strdup(src->data.udp.connectService))) { - virReportOOMError(); + VIR_STRDUP(dest->data.udp.connectService, src->data.udp.connectService) < 0) return -1; - } break; case VIR_DOMAIN_CHR_TYPE_TCP: if (src->data.tcp.host && - !(dest->data.tcp.host = strdup(src->data.tcp.host))) { - virReportOOMError(); + VIR_STRDUP(dest->data.tcp.host, src->data.tcp.host) < 0) return -1; - } if (src->data.tcp.service && - !(dest->data.tcp.service = strdup(src->data.tcp.service))) { - virReportOOMError(); + VIR_STRDUP(dest->data.tcp.service, src->data.tcp.service) < 0) return -1; - } break; case VIR_DOMAIN_CHR_TYPE_UNIX: if (src->data.nix.path && - !(dest->data.nix.path = strdup(src->data.nix.path))) { - virReportOOMError(); + VIR_STRDUP(dest->data.nix.path, src->data.nix.path) < 0) return -1; - } break; } @@ -2378,14 +2361,9 @@ virDomainDeviceInfoCopy(virDomainDeviceInfoPtr dst, dst->alias = NULL; dst->romfile = NULL; - if (src->alias && !(dst->alias = strdup(src->alias))) { - virReportOOMError(); + if ((src->alias && VIR_STRDUP(dst->alias, src->alias) < 0) || + (src->romfile && VIR_STRDUP(dst->romfile, src->romfile) < 0)) return -1; - } - if (src->romfile && !(dst->romfile = strdup(src->romfile))) { - virReportOOMError(); - return -1; - } return 0; } @@ -4124,11 +4102,8 @@ virSecurityLabelDefsParseXML(virDomainDefPtr def, /* Copy model from host. */ VIR_DEBUG("Found seclabel without a model, using '%s'", host->secModels[0].model); - def->seclabels[0]->model = strdup(host->secModels[0].model); - if (!def->seclabels[0]->model) { - virReportOOMError(); + if (VIR_STRDUP(def->seclabels[0]->model, host->secModels[0].model) < 0) goto error; - } } else { virReportError(VIR_ERR_XML_ERROR, "%s", _("missing security model in domain seclabel")); @@ -5741,10 +5716,8 @@ virDomainActualNetDefParseXML(xmlNodePtr node, addrtype = virXPathString("string(./source/address/@type)", ctxt); /* if not explicitly stated, source/vendor implies usb device */ if (!addrtype && virXPathNode("./source/vendor", ctxt) && - (addrtype = strdup("usb")) == NULL) { - virReportOOMError(); + VIR_STRDUP(addrtype, "usb") < 0) goto error; - } hostdev->mode = VIR_DOMAIN_HOSTDEV_MODE_SUBSYS; if (virDomainHostdevDefParseXMLSubsys(node, ctxt, addrtype, hostdev, flags) < 0) { @@ -6133,7 +6106,7 @@ virDomainNetDefParseXML(virDomainXMLOptionPtr xmlopt, addrtype = virXPathString("string(./source/address/@type)", ctxt); /* if not explicitly stated, source/vendor implies usb device */ if (!addrtype && virXPathNode("./source/vendor", ctxt) && - ((addrtype = strdup("usb")) == NULL)) { + VIR_STRDUP(addrtype, "usb") < 0) { virReportOOMError(); goto error; } @@ -7004,10 +6977,8 @@ virDomainTPMDefParseXML(const xmlNodePtr node, switch (def->type) { case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH: path = virXPathString("string(./backend/device/@path)", ctxt); - if (!path && !(path = strdup(VIR_DOMAIN_TPM_DEFAULT_DEVICE))) { - virReportOOMError(); + if (!path && VIR_STRDUP(path, VIR_DOMAIN_TPM_DEFAULT_DEVICE) < 0) goto error; - } def->data.passthrough.source.data.file.path = path; def->data.passthrough.source.type = VIR_DOMAIN_CHR_TYPE_DEV; path = NULL; @@ -8730,10 +8701,8 @@ virDomainRedirFilterUsbVersionHelper(const char *version, unsigned int minor; unsigned int hex; - if (!(version_copy = strdup(version))) { - virReportOOMError(); + if (VIR_STRDUP(version_copy, version) < 0) return -1; - } len = strlen(version_copy); /* @@ -9679,9 +9648,7 @@ virDomainDefGetDefaultEmulator(virDomainDefPtr def, return NULL; } - if (!(retemu = strdup(emulator))) - virReportOOMError(); - + ignore_value(VIR_STRDUP(retemu, emulator)); return retemu; } @@ -10782,10 +10749,8 @@ virDomainDefParseXML(xmlDocPtr xml, def->os.type = virXPathString("string(./os/type[1])", ctxt); if (!def->os.type) { if (def->os.bootloader) { - def->os.type = strdup("xen"); - if (!def->os.type) { - goto no_memory; - } + if (VIR_STRDUP(def->os.type, "xen") < 0) + goto error; } else { virReportError(VIR_ERR_OS_TYPE, "%s", _("no OS type")); @@ -10800,9 +10765,8 @@ virDomainDefParseXML(xmlDocPtr xml, if (STREQ(def->os.type, "linux") && def->virtType == VIR_DOMAIN_VIRT_XEN) { VIR_FREE(def->os.type); - if (!(def->os.type = strdup("xen"))) { - goto no_memory; - } + if (VIR_STRDUP(def->os.type, "xen") < 0) + goto error; } if (!virCapabilitiesSupportsGuestOSType(caps, def->os.type)) { @@ -10857,8 +10821,8 @@ virDomainDefParseXML(xmlDocPtr xml, def->os.arch, virDomainVirtTypeToString(def->virtType)); if (defaultMachine != NULL) { - if (!(def->os.machine = strdup(defaultMachine))) { - goto no_memory; + if (VIR_STRDUP(def->os.machine, defaultMachine) < 0) { + goto error; } } } @@ -10889,8 +10853,9 @@ virDomainDefParseXML(xmlDocPtr xml, _("No data supplied for <initarg> element")); goto error; } - if (!(def->os.initargv[i] = strdup((const char*)nodes[i]->children->content))) - goto no_memory; + if (VIR_STRDUP(def->os.initargv[i], + (const char*) nodes[i]->children->content) < 0) + goto error; } def->os.initargv[n] = NULL; VIR_FREE(nodes); @@ -16490,7 +16455,7 @@ virDomainObjListCopyInactiveNames(void *payload, virObjectLock(obj); if (!virDomainObjIsActive(obj) && data->numnames < data->maxnames) { - if (!(data->names[data->numnames] = strdup(obj->def->name))) + if (VIR_STRDUP(data->names[data->numnames], obj->def->name) < 0) data->oom = 1; else data->numnames++; @@ -17043,12 +17008,9 @@ virDomainGraphicsListenSetAddress(virDomainGraphicsDefPtr def, return 0; } - listenInfo->address = (len == -1) ? strdup(address) : strndup(address, len); - if (!listenInfo->address) { - virReportOOMError(); + if ((len == -1 && VIR_STRDUP(listenInfo->address, address) < 0) || + (len != -1 && VIR_STRNDUP(listenInfo->address, address, len) < 0)) return -1; - } - return 0; } @@ -17085,12 +17047,9 @@ virDomainGraphicsListenSetNetwork(virDomainGraphicsDefPtr def, return 0; } - listenInfo->network = (len == -1) ? strdup(network) : strndup(network, len); - if (!listenInfo->network) { - virReportOOMError(); + if ((len == -1 && VIR_STRDUP(listenInfo->network, network) < 0) || + (len != -1 && VIR_STRNDUP(listenInfo->network, network, len) < 0)) return -1; - } - return 0; } @@ -17425,7 +17384,7 @@ virDomainDefGenSecurityLabelDef(const char *model) virSecurityLabelDefPtr seclabel = NULL; if (VIR_ALLOC(seclabel) < 0 || - (model && !(seclabel->model = strdup(model)))) { + (model && VIR_STRDUP(seclabel->model, model) < 0)) { virReportOOMError(); virSecurityLabelDefFree(seclabel); seclabel = NULL; @@ -17440,7 +17399,7 @@ virDomainDiskDefGenSecurityLabelDef(const char *model) virSecurityDeviceLabelDefPtr seclabel = NULL; if (VIR_ALLOC(seclabel) < 0 || - (model && !(seclabel->model = strdup(model)))) { + (model && VIR_STRDUP(seclabel->model, model) < 0)) { virReportOOMError(); virSecurityDeviceLabelDefFree(seclabel); seclabel = NULL; diff --git a/src/conf/domain_event.c b/src/conf/domain_event.c index 825012a..ae55b82 100644 --- a/src/conf/domain_event.c +++ b/src/conf/domain_event.c @@ -28,6 +28,7 @@ #include "datatypes.h" #include "viralloc.h" #include "virerror.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_NONE @@ -385,8 +386,8 @@ virDomainEventCallbackListAddID(virConnectPtr conn, if (dom) { if (VIR_ALLOC(event->dom) < 0) goto no_memory; - if (!(event->dom->name = strdup(dom->name))) - goto no_memory; + if (VIR_STRDUP(event->dom->name, dom->name) < 0) + goto error; memcpy(event->dom->uuid, dom->uuid, VIR_UUID_BUFLEN); event->dom->id = dom->id; } @@ -416,7 +417,7 @@ virDomainEventCallbackListAddID(virConnectPtr conn, no_memory: virReportOOMError(); - +error: if (event) { if (event->dom) VIR_FREE(event->dom->name); @@ -668,8 +669,7 @@ static virDomainEventPtr virDomainEventNewInternal(int eventID, } event->eventID = eventID; - if (!(event->dom.name = strdup(name))) { - virReportOOMError(); + if (VIR_STRDUP(event->dom.name, name) < 0) { VIR_FREE(event); return NULL; } @@ -791,9 +791,9 @@ static virDomainEventPtr virDomainEventIOErrorNewFromDomImpl(int event, if (ev) { ev->data.ioError.action = action; - if (!(ev->data.ioError.srcPath = strdup(srcPath)) || - !(ev->data.ioError.devAlias = strdup(devAlias)) || - (reason && !(ev->data.ioError.reason = strdup(reason)))) { + if (VIR_STRDUP(ev->data.ioError.srcPath, srcPath) < 0 || + VIR_STRDUP(ev->data.ioError.devAlias, devAlias) < 0 || + (reason && VIR_STRDUP(ev->data.ioError.reason, reason) < 0)) { virDomainEventFree(ev); ev = NULL; } @@ -815,9 +815,9 @@ static virDomainEventPtr virDomainEventIOErrorNewFromObjImpl(int event, if (ev) { ev->data.ioError.action = action; - if (!(ev->data.ioError.srcPath = strdup(srcPath)) || - !(ev->data.ioError.devAlias = strdup(devAlias)) || - (reason && !(ev->data.ioError.reason = strdup(reason)))) { + if (VIR_STRDUP(ev->data.ioError.srcPath, srcPath) < 0 || + VIR_STRDUP(ev->data.ioError.devAlias, devAlias) < 0 || + (reason && VIR_STRDUP(ev->data.ioError.reason, reason) < 0)) { virDomainEventFree(ev); ev = NULL; } @@ -882,7 +882,7 @@ virDomainEventPtr virDomainEventGraphicsNewFromDom(virDomainPtr dom, if (ev) { ev->data.graphics.phase = phase; - if (!(ev->data.graphics.authScheme = strdup(authScheme))) { + if (VIR_STRDUP(ev->data.graphics.authScheme, authScheme) < 0) { virDomainEventFree(ev); return NULL; } @@ -907,7 +907,7 @@ virDomainEventPtr virDomainEventGraphicsNewFromObj(virDomainObjPtr obj, if (ev) { ev->data.graphics.phase = phase; - if (!(ev->data.graphics.authScheme = strdup(authScheme))) { + if (VIR_STRDUP(ev->data.graphics.authScheme, authScheme) < 0) { virDomainEventFree(ev); return NULL; } @@ -928,8 +928,7 @@ virDomainEventBlockJobNew(int id, const char *name, unsigned char *uuid, id, name, uuid); if (ev) { - if (!(ev->data.blockJob.path = strdup(path))) { - virReportOOMError(); + if (VIR_STRDUP(ev->data.blockJob.path, path) < 0) { virDomainEventFree(ev); return NULL; } @@ -987,15 +986,15 @@ virDomainEventDiskChangeNew(int id, const char *name, id, name, uuid); if (ev) { - if (!(ev->data.diskChange.devAlias = strdup(devAlias))) + if (VIR_STRDUP(ev->data.diskChange.devAlias, devAlias) < 0) goto error; if (oldSrcPath && - !(ev->data.diskChange.oldSrcPath = strdup(oldSrcPath))) + VIR_STRDUP(ev->data.diskChange.oldSrcPath, oldSrcPath) < 0) goto error; if (newSrcPath && - !(ev->data.diskChange.newSrcPath = strdup(newSrcPath))) + VIR_STRDUP(ev->data.diskChange.newSrcPath, newSrcPath) < 0) goto error; ev->data.diskChange.reason = reason; @@ -1004,7 +1003,6 @@ virDomainEventDiskChangeNew(int id, const char *name, return ev; error: - virReportOOMError(); virDomainEventFree(ev); return NULL; } @@ -1042,7 +1040,7 @@ virDomainEventTrayChangeNew(int id, const char *name, id, name, uuid); if (ev) { - if (!(ev->data.trayChange.devAlias = strdup(devAlias))) + if (VIR_STRDUP(ev->data.trayChange.devAlias, devAlias) < 0) goto error; ev->data.trayChange.reason = reason; @@ -1051,7 +1049,6 @@ virDomainEventTrayChangeNew(int id, const char *name, return ev; error: - virReportOOMError(); virDomainEventFree(ev); return NULL; } diff --git a/src/conf/node_device_conf.c b/src/conf/node_device_conf.c index f9303c1..40b886b 100644 --- a/src/conf/node_device_conf.c +++ b/src/conf/node_device_conf.c @@ -29,7 +29,7 @@ #include "virerror.h" #include "datatypes.h" #include "viralloc.h" - +#include "virstring.h" #include "node_device_conf.h" #include "virxml.h" #include "virbuffer.h" @@ -1164,12 +1164,8 @@ virNodeDeviceDefParseXML(xmlXPathContextPtr ctxt, goto error; } } else { - def->name = strdup("new device"); - - if (!def->name) { - virReportOOMError(); + if (VIR_STRDUP(def->name, "new device") < 0) goto error; - } } /* Extract device parent, if any */ @@ -1284,14 +1280,19 @@ virNodeDeviceGetWWNs(virNodeDeviceDefPtr def, char **wwpn) { virNodeDevCapsDefPtr cap = NULL; - int ret = 0; + int ret = -1; cap = def->caps; while (cap != NULL) { if (cap->type == VIR_NODE_DEV_CAP_SCSI_HOST && cap->data.scsi_host.flags & VIR_NODE_DEV_CAP_FLAG_HBA_FC_HOST) { - *wwnn = strdup(cap->data.scsi_host.wwnn); - *wwpn = strdup(cap->data.scsi_host.wwpn); + if (VIR_STRDUP(*wwnn, cap->data.scsi_host.wwnn) < 0 || + VIR_STRDUP(*wwpn, cap->data.scsi_host.wwpn) < 0) { + /* Free the other one, if allocated... */ + VIR_FREE(*wwnn); + VIR_FREE(*wwpn); + goto cleanup; + } break; } @@ -1301,15 +1302,11 @@ virNodeDeviceGetWWNs(virNodeDeviceDefPtr def, if (cap == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Device is not a fibre channel HBA")); - ret = -1; - } else if (*wwnn == NULL || *wwpn == NULL) { - /* Free the other one, if allocated... */ - VIR_FREE(*wwnn); - VIR_FREE(*wwpn); - ret = -1; - virReportOOMError(); + goto cleanup; } + ret = 0; +cleanup: return ret; } diff --git a/src/conf/nwfilter_conf.c b/src/conf/nwfilter_conf.c index 08222de..c0d32ea 100644 --- a/src/conf/nwfilter_conf.c +++ b/src/conf/nwfilter_conf.c @@ -400,12 +400,8 @@ virNWFilterRuleDefAddString(virNWFilterRuleDefPtr nwf, return NULL; } - nwf->strings[nwf->nstrings] = strndup(string, maxstrlen); - - if (!nwf->strings[nwf->nstrings]) { - virReportOOMError(); + if (VIR_STRNDUP(nwf->strings[nwf->nstrings], string, maxstrlen) < 0) return NULL; - } nwf->nstrings++; @@ -2556,12 +2552,9 @@ virNWFilterDefParseXML(xmlXPathContextPtr ctxt) { } chain = NULL; } else { - ret->chainsuffix = strdup(virNWFilterChainSuffixTypeToString( - VIR_NWFILTER_CHAINSUFFIX_ROOT)); - if (ret->chainsuffix == NULL) { - virReportOOMError(); + if (VIR_STRDUP(ret->chainsuffix, + virNWFilterChainSuffixTypeToString(VIR_NWFILTER_CHAINSUFFIX_ROOT)) < 0) goto cleanup; - } } uuid = virXPathString("string(./uuid)", ctxt); @@ -3094,9 +3087,7 @@ virNWFilterObjLoad(virConnectPtr conn, } VIR_FREE(nwfilter->configFile); /* for driver reload */ - nwfilter->configFile = strdup(path); - if (nwfilter->configFile == NULL) { - virReportOOMError(); + if (VIR_STRDUP(nwfilter->configFile, path) < 0) { virNWFilterDefFree(def); return NULL; } diff --git a/src/conf/nwfilter_params.c b/src/conf/nwfilter_params.c index 2509c0d..75f5cdf 100644 --- a/src/conf/nwfilter_params.c +++ b/src/conf/nwfilter_params.c @@ -80,8 +80,7 @@ virNWFilterVarValueCopy(const virNWFilterVarValuePtr val) switch (res->valType) { case NWFILTER_VALUE_TYPE_SIMPLE: if (val->u.simple.value) { - res->u.simple.value = strdup(val->u.simple.value); - if (!res->u.simple.value) + if (VIR_STRDUP(res->u.simple.value, val->u.simple.value) < 0) goto err_exit; } break; @@ -90,8 +89,7 @@ virNWFilterVarValueCopy(const virNWFilterVarValuePtr val) goto err_exit; res->u.array.nValues = val->u.array.nValues; for (i = 0; i < val->u.array.nValues; i++) { - str = strdup(val->u.array.values[i]); - if (!str) + if (VIR_STRDUP(str, val->u.array.values[i]) < 0) goto err_exit; res->u.array.values[i] = str; } @@ -133,12 +131,10 @@ virNWFilterVarValueCreateSimple(char *value) virNWFilterVarValuePtr virNWFilterVarValueCreateSimpleCopyValue(const char *value) { - char *val = strdup(value); + char *val; - if (!val) { - virReportOOMError(); + if (VIR_STRDUP(val, value) < 0) return NULL; - } return virNWFilterVarValueCreateSimple(val); } @@ -654,17 +650,15 @@ virNWFilterHashTablePut(virNWFilterHashTablePtr table, { if (!virHashLookup(table->hashTable, name)) { if (copyName) { - name = strdup(name); - if (!name) { - virReportOOMError(); + char *newName; + if (VIR_STRDUP(newName, name) < 0) return -1; - } if (VIR_REALLOC_N(table->names, table->nNames + 1) < 0) { VIR_FREE(name); return -1; } - table->names[table->nNames++] = (char *)name; + table->names[table->nNames++] = newName; } if (virHashAddEntry(table->hashTable, name, val) < 0) { @@ -1006,11 +1000,8 @@ virNWFilterVarAccessParse(const char *varAccess) if (input[idx] == '\0') { /* in the form 'IP', which is equivalent to IP[@0] */ - dest->varName = strndup(input, idx); - if (!dest->varName) { - virReportOOMError(); + if (VIR_STRNDUP(dest->varName, input, idx) < 0) goto err_exit; - } dest->accessType = VIR_NWFILTER_VAR_ACCESS_ITERATOR; dest->u.iterId = 0; return dest; @@ -1023,11 +1014,8 @@ virNWFilterVarAccessParse(const char *varAccess) varNameLen = idx; - dest->varName = strndup(input, varNameLen); - if (!dest->varName) { - virReportOOMError(); + if (VIR_STRNDUP(dest->varName, input, varNameLen) < 0) goto err_exit; - } input += idx + 1; virSkipSpaces(&input); diff --git a/src/conf/snapshot_conf.c b/src/conf/snapshot_conf.c index 5b54a28..c6b97d6 100644 --- a/src/conf/snapshot_conf.c +++ b/src/conf/snapshot_conf.c @@ -463,10 +463,8 @@ virDomainSnapshotAlignDisks(virDomainSnapshotDefPtr def, } if (STRNEQ(disk->name, def->dom->disks[idx]->dst)) { VIR_FREE(disk->name); - if (!(disk->name = strdup(def->dom->disks[idx]->dst))) { - virReportOOMError(); + if (VIR_STRDUP(disk->name, def->dom->disks[idx]->dst) < 0) goto cleanup; - } } } @@ -485,10 +483,8 @@ virDomainSnapshotAlignDisks(virDomainSnapshotDefPtr def, if (inuse) continue; disk = &def->disks[ndisks++]; - if (!(disk->name = strdup(def->dom->disks[i]->dst))) { - virReportOOMError(); + if (VIR_STRDUP(disk->name, def->dom->disks[i]->dst) < 0) goto cleanup; - } disk->index = i; disk->snapshot = def->dom->disks[i]->snapshot; if (!disk->snapshot) @@ -768,9 +764,8 @@ static void virDomainSnapshotObjListCopyNames(void *payload, return; if (data->names && data->count < data->maxnames && - !(data->names[data->count] = strdup(obj->def->name))) { + VIR_STRDUP(data->names[data->count], obj->def->name) < 0) { data->error = true; - virReportOOMError(); return; } data->count++; diff --git a/src/conf/storage_conf.c b/src/conf/storage_conf.c index 9f2012e..61a1fed 100644 --- a/src/conf/storage_conf.c +++ b/src/conf/storage_conf.c @@ -878,11 +878,8 @@ virStoragePoolDefParseXML(xmlXPathContextPtr ctxt) { if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME) { if (ret->source.name == NULL) { /* source name defaults to pool name */ - ret->source.name = strdup(ret->name); - if (ret->source.name == NULL) { - virReportOOMError(); + if (VIR_STRDUP(ret->source.name, ret->name) < 0) goto cleanup; - } } } @@ -1679,16 +1676,12 @@ virStoragePoolObjLoad(virStoragePoolObjListPtr pools, } VIR_FREE(pool->configFile); /* for driver reload */ - pool->configFile = strdup(path); - if (pool->configFile == NULL) { - virReportOOMError(); + if (VIR_STRDUP(pool->configFile, path) < 0) { virStoragePoolDefFree(def); return NULL; } VIR_FREE(pool->autostartLink); /* for driver reload */ - pool->autostartLink = strdup(autostartLink); - if (pool->autostartLink == NULL) { - virReportOOMError(); + if (VIR_STRDUP(pool->autostartLink, autostartLink) < 0) { virStoragePoolDefFree(def); return NULL; } diff --git a/src/conf/virchrdev.c b/src/conf/virchrdev.c index 025d4a8..d15d861 100644 --- a/src/conf/virchrdev.c +++ b/src/conf/virchrdev.c @@ -52,7 +52,7 @@ typedef struct _virChrdevStreamInfo virChrdevStreamInfo; typedef virChrdevStreamInfo *virChrdevStreamInfoPtr; struct _virChrdevStreamInfo { virChrdevsPtr devs; - const char *path; + char *path; }; #ifdef VIR_CHRDEV_LOCK_FILE_PATH @@ -73,10 +73,8 @@ static char *virChrdevLockFilePath(const char *dev) char *filename; char *p; - if (!(devCopy = strdup(dev))) { - virReportOOMError(); + if (VIR_STRDUP(devCopy, dev) < 0) goto cleanup; - } /* skip the leading "/dev/" */ filename = STRSKIP(devCopy, "/dev"); @@ -341,7 +339,7 @@ int virChrdevOpen(virChrdevsPtr devs, { virChrdevStreamInfoPtr cbdata = NULL; virStreamPtr savedStream; - const char *path; + char *path; int ret; switch (source->type) { @@ -401,10 +399,8 @@ int virChrdevOpen(virChrdevsPtr devs, goto error; cbdata->devs = devs; - if (!(cbdata->path = strdup(path))) { - virReportOOMError(); + if (VIR_STRDUP(cbdata->path, path) < 0) goto error; - } /* open the character device */ switch (source->type) { -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/conf/capabilities.c | 30 +++++-------- src/conf/cpu_conf.c | 19 ++++---- src/conf/domain_conf.c | 105 ++++++++++++++------------------------------ src/conf/domain_event.c | 39 ++++++++-------- src/conf/node_device_conf.c | 29 ++++++------ src/conf/nwfilter_conf.c | 17 ++----- src/conf/nwfilter_params.c | 30 ++++--------- src/conf/snapshot_conf.c | 11 ++--- src/conf/storage_conf.c | 13 ++---- src/conf/virchrdev.c | 12 ++--- 10 files changed, 107 insertions(+), 198 deletions(-)
@@ -228,7 +228,7 @@ virCapabilitiesAddHostFeature(virCapsPtr caps, caps->host.nfeatures, 1) < 0) return -1;
- if ((caps->host.features[caps->host.nfeatures] = strdup(name)) == NULL) + if (VIR_STRDUP(caps->host.features[caps->host.nfeatures], name) < 0) return -1;
This function was previously silent on error; which means its callers are now reporting an error where they used to be silent (probably GOOD in most cases) or reporting doubled errors (annoying, and worth fixing now while we are looking at it). I'd feel more comfortable if we: 1. fixed this function to report errors on ALL negative exit paths (although for this function, the only other error path is via VIR_ALLOC_N, and I already said I would tolerate delaying that fix that to a later pass, so that we aren't adding churn with virReportOOMError() in this patch just to pull it back out later) 2. check all callers as part of this patch to make sure they: a. are okay with the error being reported b. quit reporting double OOM on failure For this function, all callers in libxl_conf.c, test_driver.c, xen_hypervisor.c were reporting OOM, and need touchup. It's going to be easier to audit that we are avoiding double-error reports if we fix all call sites any time we change function semantics now, compared to blindly converting to VIR_STRDUP now then trying to audit who changed later.
@@ -250,7 +250,7 @@ virCapabilitiesAddHostMigrateTransport(virCapsPtr caps, caps->host.nmigrateTrans, 1) < 0) return -1;
- if ((caps->host.migrateTrans[caps->host.nmigrateTrans] = strdup(name)) == NULL) + if (VIR_STRDUP(caps->host.migrateTrans[caps->host.nmigrateTrans], name) < 0) return -1;
Same comments about changed semantics. I've done the audit; this time: esx_driver.c [hmm, that one wasn't even checking for errors, but we are okay letting it report errors, so no change needed], qemu_capabilities.c [another case of going from silent to error report being good], xen_hypervisor.c, vmx2xmltest.c [tests are less important to fix; it changed from silent to reporting, which is okay], xml2vmxtest.c [another test]. So, of the list of five files with callers, I'd expect at least xen_hypervisor.c to be patched.
@@ -334,7 +334,7 @@ virCapabilitiesAllocMachines(const char *const *names, int nnames)
for (i = 0; i < nnames; i++) { if (VIR_ALLOC(machines[i]) < 0 || - !(machines[i]->name = strdup(names[i]))) { + VIR_STRDUP(machines[i]->name, names[i]) < 0) { virCapabilitiesFreeMachines(machines, nnames); return NULL;
Another case of changing from silent to error-reporting. Callers: libxl_conf.c, xen_hypervisor.c, testutilsqemu.c [testsuite file, so less important; was previously silent but new reporting behavior is okay], testutilsxen.c [another test file] Looks like libxl_conf.c and xen_hypervisor.c are the two files needing a patch to avoid double-OOM
} @@ -392,17 +392,14 @@ virCapabilitiesAddGuest(virCapsPtr caps, if (VIR_ALLOC(guest) < 0) goto no_memory;
- if ((guest->ostype = strdup(ostype)) == NULL) + if (VIR_STRDUP(guest->ostype, ostype) < 0) goto no_memory;
The label is now incorrectly named. And looking at that label: no_memory: virCapabilitiesFreeGuest(guest); return NULL; this is another case of changing from silent to error-reporting. Of the callers, I determined that at least: esx_driver.c and lxc_conf.c switch from silent to reporting (good, no change needed), and at least openvz_conf.c and phyp_driver.c now have double-OOM (fix them); I stopped auditing callers here.
guest->arch.id = arch; guest->arch.wordsize = virArchGetWordSize(arch);
- if (emulator && - (guest->arch.defaultInfo.emulator = strdup(emulator)) == NULL) - goto no_memory; - if (loader && - (guest->arch.defaultInfo.loader = strdup(loader)) == NULL) + if ((emulator && VIR_STRDUP(guest->arch.defaultInfo.emulator, emulator) < 0) || + (loader && VIR_STRDUP(guest->arch.defaultInfo.loader, loader) < 0)) goto no_memory;
Ah, we really DO have a case where my proposal in 1/34 of allowing a NULL source would make sense. Again, no_memory is now labeled incorrectly
@@ -448,14 +445,9 @@ virCapabilitiesAddGuestDomain(virCapsGuestPtr guest, if (VIR_ALLOC(dom) < 0) goto no_memory;
- if ((dom->type = strdup(hvtype)) == NULL) - goto no_memory; - - if (emulator && - (dom->info.emulator = strdup(emulator)) == NULL) - goto no_memory; - if (loader && - (dom->info.loader = strdup(loader)) == NULL) + if (VIR_STRDUP(dom->type, hvtype) < 0 || + (emulator && VIR_STRDUP(dom->info.emulator, emulator) < 0) || + (loader && VIR_STRDUP(dom->info.loader, loader) < 0)) goto no_memory;
Label name is now wrong; and looking at the label, it is another case of silent->reporting conversion; all callers need audit.
@@ -497,7 +489,7 @@ virCapabilitiesAddGuestFeature(virCapsGuestPtr guest, if (VIR_ALLOC(feature) < 0) goto no_memory;
- if ((feature->name = strdup(name)) == NULL) + if (VIR_STRDUP(feature->name, name) < 0) goto no_memory;
wrong label name, another silent->reporting caller audit. Hmm, it might mean splitting this patch into smaller pieces, focusing on one file plus all its fallout, rather than doing one directory but not tracking any fallout. As such, I'm sending my email now in case it helps you start v4 of a split on just capabilities.c, while I review the rest of this patch in another email. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On 05/03/2013 03:22 PM, Eric Blake wrote:
@@ -250,7 +250,7 @@ virCapabilitiesAddHostMigrateTransport(virCapsPtr caps, caps->host.nmigrateTrans, 1) < 0) return -1;
- if ((caps->host.migrateTrans[caps->host.nmigrateTrans] = strdup(name)) == NULL) + if (VIR_STRDUP(caps->host.migrateTrans[caps->host.nmigrateTrans], name) < 0) return -1;
Same comments about changed semantics. I've done the audit; this time: esx_driver.c [hmm, that one wasn't even checking for errors, but we are okay letting it report errors, so no change needed], qemu_capabilities.c [another case of going from silent to error report being good], xen_hypervisor.c, vmx2xmltest.c [tests are less important to fix; it changed from silent to reporting, which is okay], xml2vmxtest.c [another test].
So, of the list of five files with callers, I'd expect at least xen_hypervisor.c to be patched.
Correction - since esx_driver.c and qemu_capabilities are flat out ignoring failure, they need to be patched to return failure (rather than returning success with bad state). But the test files can probably get away with ignoring failure. On the other hand, one of the easiest ways to indicate that you have switched from silent to reporting behavior is to mark the function as ATTRIBUTE_RETURN_CHECK, at which point, you would then need to fix ALL callers to keep the compiler happy.
@@ -392,17 +392,14 @@ virCapabilitiesAddGuest(virCapsPtr caps, if (VIR_ALLOC(guest) < 0) goto no_memory;
- if ((guest->ostype = strdup(ostype)) == NULL) + if (VIR_STRDUP(guest->ostype, ostype) < 0) goto no_memory;
The label is now incorrectly named. And looking at that label:
no_memory: virCapabilitiesFreeGuest(guest); return NULL;
this is another case of changing from silent to error-reporting. Of the callers, I determined that at least: esx_driver.c and lxc_conf.c switch from silent to reporting (good, no change needed), and at least openvz_conf.c and phyp_driver.c now have double-OOM (fix them); I stopped auditing callers here.
At least here, esx_driver.c was returning errors back to its caller (unlike the earlier case of *MigrateTransport where errors were silently dropped), so I stand by my analysis that no change is needed to esx_driver for this case. Moral of the story - anywhere we change from silent to noisy, we really do have to look at all callers on a case-by-case basis. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On 03.05.2013 23:22, Eric Blake wrote:
On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/conf/capabilities.c | 30 +++++-------- src/conf/cpu_conf.c | 19 ++++---- src/conf/domain_conf.c | 105 ++++++++++++++------------------------------ src/conf/domain_event.c | 39 ++++++++-------- src/conf/node_device_conf.c | 29 ++++++------ src/conf/nwfilter_conf.c | 17 ++----- src/conf/nwfilter_params.c | 30 ++++--------- src/conf/snapshot_conf.c | 11 ++--- src/conf/storage_conf.c | 13 ++---- src/conf/virchrdev.c | 12 ++--- 10 files changed, 107 insertions(+), 198 deletions(-)
@@ -228,7 +228,7 @@ virCapabilitiesAddHostFeature(virCapsPtr caps, caps->host.nfeatures, 1) < 0) return -1;
- if ((caps->host.features[caps->host.nfeatures] = strdup(name)) == NULL) + if (VIR_STRDUP(caps->host.features[caps->host.nfeatures], name) < 0) return -1;
This function was previously silent on error; which means its callers are now reporting an error where they used to be silent (probably GOOD in most cases) or reporting doubled errors (annoying, and worth fixing now while we are looking at it). I'd feel more comfortable if we:
1. fixed this function to report errors on ALL negative exit paths (although for this function, the only other error path is via VIR_ALLOC_N, and I already said I would tolerate delaying that fix that to a later pass, so that we aren't adding churn with virReportOOMError() in this patch just to pull it back out later)
2. check all callers as part of this patch to make sure they: a. are okay with the error being reported b. quit reporting double OOM on failure
For this function, all callers in libxl_conf.c, test_driver.c, xen_hypervisor.c were reporting OOM, and need touchup.
It's going to be easier to audit that we are avoiding double-error reports if we fix all call sites any time we change function semantics now, compared to blindly converting to VIR_STRDUP now then trying to audit who changed later.
I don't quite agree. In the next serie I will be: 1) turning VIR_ALLOC* and virAsprintf into OOM reporting 2) removing virReportOOMError from everywhere These two steps will effectively cut off double OOM error reporting and move the place where error is reported closer to it's actual origin. So in this concrete example, callers of virCapabilitiesAddHostFeature are: libxl_conf.c:80: libxlBuildCapabilities: does call virReportOOMError (in fact, its parent does) src/test/test_driver.c:175: testBuildCapabilities: does call virReportOOMError xen_hypervisor.c:2293: xenHypervisorBuildCapabilities does call virReportOOMError (in fact, its parent does) After my patches, these wouldn't call virReportOOMError at all. I agree, that the future patches I am talking about will require more inspection if callee reports OOM error on every path, but I would not bother with it for now. I mean, this chunk of code we have here will report OOM error at no cost - compared to your suggestion where I'd have to manually go through every possible callers. Twice. Moreover, I don't think moving from silent -> reporting is no bad at all. The worst case scenario is, users will see one more line in the libvirtd log. The best case scenario is - all forgotten places where we currently don't catch OOM errors, or do it in bad way (remember make_nonnull_domain?) will now report the correct error. Again, at no price. What I really fear about here is, that I don't change semantics. But that's what review is for, isn't it :) Michal

On 05/05/2013 05:01 AM, Michal Privoznik wrote:
@@ -228,7 +228,7 @@ virCapabilitiesAddHostFeature(virCapsPtr caps, caps->host.nfeatures, 1) < 0) return -1;
- if ((caps->host.features[caps->host.nfeatures] = strdup(name)) == NULL) + if (VIR_STRDUP(caps->host.features[caps->host.nfeatures], name) < 0) return -1;
This function was previously silent on error; which means its callers are now reporting an error where they used to be silent (probably GOOD in most cases) or reporting doubled errors (annoying, and worth fixing now while we are looking at it). I'd feel more comfortable if we:
I don't quite agree. In the next serie I will be: 1) turning VIR_ALLOC* and virAsprintf into OOM reporting 2) removing virReportOOMError from everywhere
Removing OOMError from everywhere will indeed clean up double OOM reporting. But what I'm worried about is cases where we had no error reporting, but now we do - and are there any cases where the new error reporting could lead to spurious problems? Or conversely, are there any callers that should have been reporting errors, but weren't, and where we won't notice that those callers are still buggy when we make our pass to clean up double OOM reporting?
These two steps will effectively cut off double OOM error reporting and move the place where error is reported closer to it's actual origin.
So in this concrete example, callers of virCapabilitiesAddHostFeature are:
libxl_conf.c:80: libxlBuildCapabilities: does call virReportOOMError (in fact, its parent does)
src/test/test_driver.c:175: testBuildCapabilities: does call virReportOOMError
xen_hypervisor.c:2293: xenHypervisorBuildCapabilities does call virReportOOMError (in fact, its parent does)
After my patches, these wouldn't call virReportOOMError at all. I agree, that the future patches I am talking about will require more inspection if callee reports OOM error on every path, but I would not bother with it for now. I mean, this chunk of code we have here will report OOM error at no cost - compared to your suggestion where I'd have to manually go through every possible callers. Twice.
Okay, on that front, you've convinced me that we want to minimize the effort to get your series in - both the effort for you to get to the final end goal, and the time I spend on reviewing it :)
Moreover, I don't think moving from silent -> reporting is no bad at all. The worst case scenario is, users will see one more line in the libvirtd log. The best case scenario is - all forgotten places where we currently don't catch OOM errors, or do it in bad way (remember make_nonnull_domain?) will now report the correct error. Again, at no price.
For the case of src/conf/capabilities.c, I think we are fine (those functions were always used synchronously, so the user will eventually see the error); for the case of src/conf/domain_event.c, I'm less convinced (the OOM happens while trying to send an async message, so where we are previously silent, we are now polluting the thread-local error object, and the next synchronous call that happens to use the same worker thread will now have an active but unrelated OOM error object in the way - if we are going to silently drop failed attempts to send an async event, then we should not be leaving an error behind in thread-local storage).
What I really fear about here is, that I don't change semantics. But that's what review is for, isn't it :)
Yep - which is why I've been flagging any call that changes from silent->reporting as a potential semantic change. The problem is that I don't know the best way to divide the task so that we aren't reviewing the same code through multiple revisions of churn, while still avoiding the problem of a semantic change that we will regret. If anyone else has ideas on what we should do here, speak up! I guess at this point, I'll continue reviewing the next couple of patches in the series, and see how many (or how few) instances of silent->reporting changes we really deal with. It may not be as bad as I'm worried about, in which case it may be easier to just note the problems, commit your series as is, and deal with the fallout manually at the end of your series, instead of making you rebase yet another round (after all, on patch 3/34, I only found 2 of the 10 files where I identified a silent->reporting change). -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/conf/capabilities.c | 30 +++++--------
Reviewed earlier.
src/conf/cpu_conf.c | 19 ++++---- src/conf/domain_conf.c | 105 ++++++++++++++------------------------------ src/conf/domain_event.c | 39 ++++++++-------- src/conf/node_device_conf.c | 29 ++++++------ src/conf/nwfilter_conf.c | 17 ++----- src/conf/nwfilter_params.c | 30 ++++--------- src/conf/snapshot_conf.c | 11 ++--- src/conf/storage_conf.c | 13 ++---- src/conf/virchrdev.c | 12 ++---
Part two of the review:
+++ b/src/conf/cpu_conf.c @@ -99,10 +99,10 @@ virCPUDefCopyModel(virCPUDefPtr dst, { unsigned int i;
- if ((src->model && !(dst->model = strdup(src->model))) - || (src->vendor && !(dst->vendor = strdup(src->vendor))) - || (src->vendor_id && !(dst->vendor_id = strdup(src->vendor_id))) - || VIR_ALLOC_N(dst->features, src->nfeatures) < 0) + if ((src->model && VIR_STRDUP(dst->model, src->model) < 0) || + (src->vendor && VIR_STRDUP(dst->vendor, src->vendor) < 0) || + (src->vendor_id && VIR_STRDUP(dst->vendor_id, src->vendor_id) < 0) || + VIR_ALLOC_N(dst->features, src->nfeatures) < 0) goto no_memory;
Double OOM, but you also have a VIR_ALLOC, so this will be cleaned up in a later pass.
dst->nfeatures_max = dst->nfeatures = src->nfeatures;
@@ -118,7 +118,7 @@ virCPUDefCopyModel(virCPUDefPtr dst, dst->features[i].policy = src->features[i].policy; }
- if (!(dst->features[i].name = strdup(src->features[i].name))) + if (VIR_STRDUP(dst->features[i].name, src->features[i].name) < 0) goto no_memory;
Double OOM reporting; I'd just inline 'return -1' here instead of using goto.
@@ -167,8 +167,8 @@ virCPUDefCopy(const virCPUDefPtr cpu) if (!copy->cells[i].cpumask) goto no_memory;
- if (!(copy->cells[i].cpustr = strdup(cpu->cells[i].cpustr))) - goto no_memory; + if (VIR_STRDUP(copy->cells[i].cpustr, cpu->cells[i].cpustr) < 0) + goto error;
Yay - clean conversion!
@@ -694,8 +694,8 @@ virCPUDefAddFeature(virCPUDefPtr def, if (def->type == VIR_CPU_TYPE_HOST) policy = -1;
- if (!(def->features[def->nfeatures].name = strdup(name))) - goto no_memory; + if (VIR_STRDUP(def->features[def->nfeatures].name, name) < 0) + goto error;
def->features[def->nfeatures].policy = policy; def->nfeatures++; @@ -704,6 +704,7 @@ virCPUDefAddFeature(virCPUDefPtr def,
no_memory: virReportOOMError(); +error: return -1;
You could drop the error label and just inline the return -1.
+++ b/src/conf/domain_conf.c @@ -1352,59 +1352,42 @@ virDomainChrSourceDefCopy(virDomainChrSourceDefPtr dest, case VIR_DOMAIN_CHR_TYPE_FILE: case VIR_DOMAIN_CHR_TYPE_PIPE: if (src->data.file.path && - !(dest->data.file.path = strdup(src->data.file.path))) { - virReportOOMError(); + VIR_STRDUP(dest->data.file.path, src->data.file.path) < 0) return -1;
More instances where allowing a NULL source would simplify callers.
@@ -6133,7 +6106,7 @@ virDomainNetDefParseXML(virDomainXMLOptionPtr xmlopt, addrtype = virXPathString("string(./source/address/@type)", ctxt); /* if not explicitly stated, source/vendor implies usb device */ if (!addrtype && virXPathNode("./source/vendor", ctxt) && - ((addrtype = strdup("usb")) == NULL)) { + VIR_STRDUP(addrtype, "usb") < 0) { virReportOOMError();
Drop this double OOM.
@@ -9679,9 +9648,7 @@ virDomainDefGetDefaultEmulator(virDomainDefPtr def, return NULL; }
- if (!(retemu = strdup(emulator))) - virReportOOMError(); - + ignore_value(VIR_STRDUP(retemu, emulator)); return retemu;
This one caught my eye, but it looks correct after all.
@@ -10857,8 +10821,8 @@ virDomainDefParseXML(xmlDocPtr xml, def->os.arch, virDomainVirtTypeToString(def->virtType)); if (defaultMachine != NULL) { - if (!(def->os.machine = strdup(defaultMachine))) { - goto no_memory; + if (VIR_STRDUP(def->os.machine, defaultMachine) < 0) { + goto error; }
Another case that could be simplified by taking a NULL source.
@@ -16490,7 +16455,7 @@ virDomainObjListCopyInactiveNames(void *payload,
virObjectLock(obj); if (!virDomainObjIsActive(obj) && data->numnames < data->maxnames) { - if (!(data->names[data->numnames] = strdup(obj->def->name))) + if (VIR_STRDUP(data->names[data->numnames], obj->def->name) < 0) data->oom = 1;
This change is fine, but incomplete. You need to fix virDomainObjListGetInactiveNames a few lines later to quit reporting OOM when it sees data->oom set.
@@ -17425,7 +17384,7 @@ virDomainDefGenSecurityLabelDef(const char *model) virSecurityLabelDefPtr seclabel = NULL;
if (VIR_ALLOC(seclabel) < 0 || - (model && !(seclabel->model = strdup(model)))) { + (model && VIR_STRDUP(seclabel->model, model) < 0)) { virReportOOMError();
double-oom is excusable because of VIR_ALLOC
@@ -17440,7 +17399,7 @@ virDomainDiskDefGenSecurityLabelDef(const char *model) virSecurityDeviceLabelDefPtr seclabel = NULL;
if (VIR_ALLOC(seclabel) < 0 || - (model && !(seclabel->model = strdup(model)))) { + (model && VIR_STRDUP(seclabel->model, model) < 0)) { virReportOOMError();
and again
+++ b/src/conf/domain_event.c
@@ -791,9 +791,9 @@ static virDomainEventPtr virDomainEventIOErrorNewFromDomImpl(int event,
if (ev) { ev->data.ioError.action = action; - if (!(ev->data.ioError.srcPath = strdup(srcPath)) || - !(ev->data.ioError.devAlias = strdup(devAlias)) || - (reason && !(ev->data.ioError.reason = strdup(reason)))) { + if (VIR_STRDUP(ev->data.ioError.srcPath, srcPath) < 0 || + VIR_STRDUP(ev->data.ioError.devAlias, devAlias) < 0 || + (reason && VIR_STRDUP(ev->data.ioError.reason, reason) < 0)) { virDomainEventFree(ev); ev = NULL;
Changed from silent to noisy. Only caller appears to be remote_driver.c:remoteDomainBuildEventIOError, where failure is ignored (the event is basically discarded). Ouch - that code has a pre-existing bug - a NULL return here is eventually passed on to virDomainEventQueuePush, which queues up a NULL, and later servicing of the queue will do a NULL deref in virDomainEventDispatchMatchCallback. Looks like we need to fix that, and now's as good a time as any, possibly by fixing virDomainEventStateQueue to ignore a NULL event push, or possibly by fixing remote_driver.c.
@@ -815,9 +815,9 @@ static virDomainEventPtr virDomainEventIOErrorNewFromObjImpl(int event,
if (ev) { ev->data.ioError.action = action; - if (!(ev->data.ioError.srcPath = strdup(srcPath)) || - !(ev->data.ioError.devAlias = strdup(devAlias)) || - (reason && !(ev->data.ioError.reason = strdup(reason)))) { + if (VIR_STRDUP(ev->data.ioError.srcPath, srcPath) < 0 || + VIR_STRDUP(ev->data.ioError.devAlias, devAlias) < 0 || + (reason && VIR_STRDUP(ev->data.ioError.reason, reason) < 0)) { virDomainEventFree(ev); ev = NULL;
Changed from silent to noisy. Only caller appears to be qemu_process.c:qemuProcessHandleIOError, but at least this one properly discards the error without trying to queue up NULL. I'm wondering if these two particular functions should use the _QUIET variant, so we aren't polluting the thread-local error object in a case where the caller is fine discarding the error if it could not be created.
@@ -882,7 +882,7 @@ virDomainEventPtr virDomainEventGraphicsNewFromDom(virDomainPtr dom,
if (ev) { ev->data.graphics.phase = phase; - if (!(ev->data.graphics.authScheme = strdup(authScheme))) { + if (VIR_STRDUP(ev->data.graphics.authScheme, authScheme) < 0) { virDomainEventFree(ev); return NULL;
silent->noisy. I did not audit this one for callers, but suspect it will be similar to IOError events: we probably have a bug in remote_driver.c for trying to queue NULL, and since all callers probably ignore an event object that could not be queued, using _QUIET here may be appropriate. Hmm, a bit more thinking: all events are asynchronous push, rather than synchronous replies to the client's request; which explains why we ignore OOM in creating an event - we aren't under obligation to send a reply. But I'm wondering if we should have code that tries to deliver an OOM event (of course, pre-created at the time the connection is first established, so that actually sending the OOM event doesn't involve any use of malloc), where hitting OOM and discarding any normal event then falls back to trying to fire the OOM event. Then again, OOM is such a rare corner case, and tends to be somewhat persistent as well; once we hit OOM trying to generate an error, we will probably also hit OOM on the next synchronous call from the client, so it won't be too much longer before they learn about it normally, without us having to worry about a special OOM event. So ignore this paragraph if you think I'm over-engineering things.
@@ -907,7 +907,7 @@ virDomainEventPtr virDomainEventGraphicsNewFromObj(virDomainObjPtr obj,
if (ev) { ev->data.graphics.phase = phase; - if (!(ev->data.graphics.authScheme = strdup(authScheme))) { + if (VIR_STRDUP(ev->data.graphics.authScheme, authScheme) < 0) { virDomainEventFree(ev); return NULL; } @@ -928,8 +928,7 @@ virDomainEventBlockJobNew(int id, const char *name, unsigned char *uuid, id, name, uuid);
if (ev) { - if (!(ev->data.blockJob.path = strdup(path))) { - virReportOOMError(); + if (VIR_STRDUP(ev->data.blockJob.path, path) < 0) { virDomainEventFree(ev); return NULL;
Hmm, we weren't very consistent on which events were already noisy on creation failure. I guess that argues that using _QUIET variants is overkill, because we already have cases where an OOM will set the thread-local error object even if it event is discarded.
+++ b/src/conf/node_device_conf.c
@@ -1284,14 +1280,19 @@ virNodeDeviceGetWWNs(virNodeDeviceDefPtr def, char **wwpn) { virNodeDevCapsDefPtr cap = NULL; - int ret = 0; + int ret = -1;
cap = def->caps; while (cap != NULL) { if (cap->type == VIR_NODE_DEV_CAP_SCSI_HOST && cap->data.scsi_host.flags & VIR_NODE_DEV_CAP_FLAG_HBA_FC_HOST) { - *wwnn = strdup(cap->data.scsi_host.wwnn); - *wwpn = strdup(cap->data.scsi_host.wwpn); + if (VIR_STRDUP(*wwnn, cap->data.scsi_host.wwnn) < 0 || + VIR_STRDUP(*wwpn, cap->data.scsi_host.wwpn) < 0) { + /* Free the other one, if allocated... */ + VIR_FREE(*wwnn); + VIR_FREE(*wwpn);
Technically, *wwpn is already NULL if we get here, so you can drop this second VIR_FREE.
+++ b/src/conf/nwfilter_params.c @@ -80,8 +80,7 @@ virNWFilterVarValueCopy(const virNWFilterVarValuePtr val) switch (res->valType) { case NWFILTER_VALUE_TYPE_SIMPLE: if (val->u.simple.value) { - res->u.simple.value = strdup(val->u.simple.value); - if (!res->u.simple.value) + if (VIR_STRDUP(res->u.simple.value, val->u.simple.value) < 0) goto err_exit;
double OOM here, but okay because VIR_ALLOC also uses the label.
@@ -90,8 +89,7 @@ virNWFilterVarValueCopy(const virNWFilterVarValuePtr val) goto err_exit; res->u.array.nValues = val->u.array.nValues; for (i = 0; i < val->u.array.nValues; i++) { - str = strdup(val->u.array.values[i]); - if (!str) + if (VIR_STRDUP(str, val->u.array.values[i]) < 0) goto err_exit;
Again, VIR_ALLOC cleanup will cover this case of double oom
@@ -654,17 +650,15 @@ virNWFilterHashTablePut(virNWFilterHashTablePtr table, { if (!virHashLookup(table->hashTable, name)) { if (copyName) { - name = strdup(name); - if (!name) { - virReportOOMError(); + char *newName; + if (VIR_STRDUP(newName, name) < 0) return -1; - }
if (VIR_REALLOC_N(table->names, table->nNames + 1) < 0) { VIR_FREE(name); return -1;
Hmm, this code was missing oom reporting; but we'll clean that up on the VIR_ALLOC pass.
+++ b/src/conf/virchrdev.c @@ -52,7 +52,7 @@ typedef struct _virChrdevStreamInfo virChrdevStreamInfo; typedef virChrdevStreamInfo *virChrdevStreamInfoPtr; struct _virChrdevStreamInfo { virChrdevsPtr devs; - const char *path; + char *path; };
Interesting. But looks correct. The majority of this patch looks reasonable. I already split capabilities.c into a separate review. domain_event.c is the only remaining file out of this lot that might warrant a split into its own patch, if you want to tackle making all event clients deal sanely with consistent semantics on what happens if you hit OOM when trying to report an event (and again, I'm not sure if the sanest is to clear the thread-local error, leave it polluted, or switch to _QUIET variants since we know that all events are best-effort only). -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/cpu/cpu_generic.c | 8 ++++---- src/cpu/cpu_map.c | 3 ++- src/cpu/cpu_powerpc.c | 13 ++++++------- src/cpu/cpu_x86.c | 10 +++++----- 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/cpu/cpu_generic.c b/src/cpu/cpu_generic.c index 9d5117f..7e3eda2 100644 --- a/src/cpu/cpu_generic.c +++ b/src/cpu/cpu_generic.c @@ -28,7 +28,7 @@ #include "virhash.h" #include "cpu.h" #include "cpu_generic.h" - +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_CPU @@ -131,7 +131,7 @@ genericBaseline(virCPUDefPtr *cpus, } if (VIR_ALLOC(cpu) < 0 || - !(cpu->model = strdup(cpus[0]->model)) || + VIR_STRDUP(cpu->model, cpus[0]->model) < 0 || VIR_ALLOC_N(features, cpus[0]->nfeatures) < 0) goto no_memory; @@ -183,8 +183,8 @@ genericBaseline(virCPUDefPtr *cpus, if (!features[i].name) continue; - if (!(cpu->features[j++].name = strdup(features[i].name))) - goto no_memory; + if (VIR_STRDUP(cpu->features[j++].name, features[i].name) < 0) + goto error; } cleanup: diff --git a/src/cpu/cpu_map.c b/src/cpu/cpu_map.c index 015be2e..7c2bdec 100644 --- a/src/cpu/cpu_map.c +++ b/src/cpu/cpu_map.c @@ -27,6 +27,7 @@ #include "cpu.h" #include "cpu_map.h" #include "configmake.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_CPU @@ -149,7 +150,7 @@ cpuMapOverride(const char *path) { char *map; - if (!(map = strdup(path))) + if (VIR_STRDUP(map, path) < 0) return -1; VIR_FREE(cpumap); diff --git a/src/cpu/cpu_powerpc.c b/src/cpu/cpu_powerpc.c index b253db2..d17f9ca 100644 --- a/src/cpu/cpu_powerpc.c +++ b/src/cpu/cpu_powerpc.c @@ -29,7 +29,7 @@ #include "virlog.h" #include "viralloc.h" #include "cpu.h" - +#include "virstring.h" #include "cpu_map.h" #include "virbuffer.h" @@ -333,9 +333,8 @@ ppcDecode(virCPUDefPtr cpu, goto cleanup; } - if (!(cpu->model = strdup(model->name)) || - (model->vendor && !(cpu->vendor = strdup(model->vendor->name)))) { - virReportOOMError(); + if (VIR_STRDUP(cpu->model, model->name) < 0 || + (model->vendor && VIR_STRDUP(cpu->vendor, model->vendor->name) < 0)) { goto cleanup; } @@ -449,11 +448,11 @@ ppcBaseline(virCPUDefPtr *cpus, } if (VIR_ALLOC(cpu) < 0 || - !(cpu->model = strdup(model->name))) + VIR_STRDUP(cpu->model, model->name) < 0) goto no_memory; - if (vendor && !(cpu->vendor = strdup(vendor->name))) - goto no_memory; + if (vendor && VIR_STRDUP(cpu->vendor, vendor->name) < 0) + goto error; cpu->type = VIR_CPU_TYPE_GUEST; cpu->match = VIR_CPU_MATCH_EXACT; diff --git a/src/cpu/cpu_x86.c b/src/cpu/cpu_x86.c index 14d525e..5d479c2 100644 --- a/src/cpu/cpu_x86.c +++ b/src/cpu/cpu_x86.c @@ -449,13 +449,13 @@ x86DataToCPU(const union cpuData *data, const struct x86_vendor *vendor; if (VIR_ALLOC(cpu) < 0 || - !(cpu->model = strdup(model->name)) || + VIR_STRDUP(cpu->model, model->name) < 0 || !(copy = x86DataCopy(data)) || !(modelData = x86DataCopy(model->data))) goto no_memory; if ((vendor = x86DataToVendor(copy, map)) && - !(cpu->vendor = strdup(vendor->name))) + VIR_STRDUP(cpu->vendor, vendor->name) < 0) goto no_memory; x86DataSubtract(copy, modelData); @@ -766,9 +766,9 @@ x86ModelCopy(const struct x86_model *model) { struct x86_model *copy; - if (VIR_ALLOC(copy) < 0 - || !(copy->name = strdup(model->name)) - || !(copy->data = x86DataCopy(model->data))) { + if (VIR_ALLOC(copy) < 0 || + VIR_STRDUP(copy->name, model->name) < 0 || + !(copy->data = x86DataCopy(model->data))) { x86ModelFree(copy); return NULL; } -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/cpu/cpu_generic.c | 8 ++++---- src/cpu/cpu_map.c | 3 ++- src/cpu/cpu_powerpc.c | 13 ++++++------- src/cpu/cpu_x86.c | 10 +++++----- 4 files changed, 17 insertions(+), 17 deletions(-)
@@ -131,7 +131,7 @@ genericBaseline(virCPUDefPtr *cpus, }
if (VIR_ALLOC(cpu) < 0 || - !(cpu->model = strdup(cpus[0]->model)) || + VIR_STRDUP(cpu->model, cpus[0]->model) < 0 || VIR_ALLOC_N(features, cpus[0]->nfeatures) < 0) goto no_memory;
double-oom reporting, will be cleaned up later, so not an issue for this patch.
@@ -183,8 +183,8 @@ genericBaseline(virCPUDefPtr *cpus, if (!features[i].name) continue;
- if (!(cpu->features[j++].name = strdup(features[i].name))) - goto no_memory; + if (VIR_STRDUP(cpu->features[j++].name, features[i].name) < 0) + goto error;
Another case of side effects (j++) inside the macro call. I think we are safe relying on exactly-once expansion of VIR_STRDUP macros, but we ought to push a followup patch that documents (in both HACKING and virstring.h) that the exactly-once semantics are guaranteed for this particular macro as an exception to the more general rule that any ALL_CAPS name is a macro that might mishandle side effects. (For that matter, VIR_ALLOC and VIR_INSERT_ELEMENT also have the same property of exactly-once semantics, and could also use the same documentation guarantee, but VIR_APPEND_ELEMENT double-evaluates its 'count' parameter, unless we rework virInsertElementsN() to take 'at==-1' to mean use '*countptr' as its initial 'at' value.)
+++ b/src/cpu/cpu_map.c @@ -27,6 +27,7 @@ #include "cpu.h" #include "cpu_map.h" #include "configmake.h" +#include "virstring.h"
#define VIR_FROM_THIS VIR_FROM_CPU
@@ -149,7 +150,7 @@ cpuMapOverride(const char *path) { char *map;
- if (!(map = strdup(path))) + if (VIR_STRDUP(map, path) < 0)
silent->noisy, but all callers are limited to tests/*, which just fail the test anyway, so no change needed.
+++ b/src/cpu/cpu_powerpc.c @@ -333,9 +333,8 @@ ppcDecode(virCPUDefPtr cpu, goto cleanup; }
- if (!(cpu->model = strdup(model->name)) || - (model->vendor && !(cpu->vendor = strdup(model->vendor->name)))) { - virReportOOMError(); + if (VIR_STRDUP(cpu->model, model->name) < 0 || + (model->vendor && VIR_STRDUP(cpu->vendor, model->vendor->name) < 0)) {
Another case where not requiring ATTRIBUTE_NONNNULL(2) on VIR_STRDUP would be handy. I think I've convinced myself we should go that route. Maybe it would help if I post a patch showing what I'm thinking?
goto cleanup; }
@@ -449,11 +448,11 @@ ppcBaseline(virCPUDefPtr *cpus, }
if (VIR_ALLOC(cpu) < 0 || - !(cpu->model = strdup(model->name))) + VIR_STRDUP(cpu->model, model->name) < 0) goto no_memory;
double-oom, but will be cleaned up later
+++ b/src/cpu/cpu_x86.c @@ -449,13 +449,13 @@ x86DataToCPU(const union cpuData *data, const struct x86_vendor *vendor;
if (VIR_ALLOC(cpu) < 0 || - !(cpu->model = strdup(model->name)) || + VIR_STRDUP(cpu->model, model->name) < 0 || !(copy = x86DataCopy(data)) || !(modelData = x86DataCopy(model->data))) goto no_memory;
double-oom, but will be cleaned up later
if ((vendor = x86DataToVendor(copy, map)) && - !(cpu->vendor = strdup(vendor->name))) + VIR_STRDUP(cpu->vendor, vendor->name) < 0) goto no_memory;
x86DataSubtract(copy, modelData); @@ -766,9 +766,9 @@ x86ModelCopy(const struct x86_model *model) { struct x86_model *copy;
- if (VIR_ALLOC(copy) < 0 - || !(copy->name = strdup(model->name)) - || !(copy->data = x86DataCopy(model->data))) { + if (VIR_ALLOC(copy) < 0 || + VIR_STRDUP(copy->name, model->name) < 0 || + !(copy->data = x86DataCopy(model->data))) { x86ModelFree(copy); return NULL;
silent->reporting, but function is static, and all callers already did 'goto no_memory', so this is merely another double-oom that will be cleaned up in your later pass ACK. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On 07.05.2013 00:00, Eric Blake wrote:
On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/cpu/cpu_generic.c | 8 ++++---- src/cpu/cpu_map.c | 3 ++- src/cpu/cpu_powerpc.c | 13 ++++++------- src/cpu/cpu_x86.c | 10 +++++----- 4 files changed, 17 insertions(+), 17 deletions(-)
+++ b/src/cpu/cpu_powerpc.c @@ -333,9 +333,8 @@ ppcDecode(virCPUDefPtr cpu, goto cleanup; }
- if (!(cpu->model = strdup(model->name)) || - (model->vendor && !(cpu->vendor = strdup(model->vendor->name)))) { - virReportOOMError(); + if (VIR_STRDUP(cpu->model, model->name) < 0 || + (model->vendor && VIR_STRDUP(cpu->vendor, model->vendor->name) < 0)) {
Another case where not requiring ATTRIBUTE_NONNNULL(2) on VIR_STRDUP would be handy. I think I've convinced myself we should go that route. Maybe it would help if I post a patch showing what I'm thinking?
Yep. you're completely right. However, the 1st patch is already pushed with ATTRIBUTE_NONNULL(2). So do you want me to post a fix dropping the useless attribute and pushing this without it, or ..,?
ACK.

On 07.05.2013 11:15, Michal Privoznik wrote:
On 07.05.2013 00:00, Eric Blake wrote:
On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/cpu/cpu_generic.c | 8 ++++---- src/cpu/cpu_map.c | 3 ++- src/cpu/cpu_powerpc.c | 13 ++++++------- src/cpu/cpu_x86.c | 10 +++++----- 4 files changed, 17 insertions(+), 17 deletions(-)
+++ b/src/cpu/cpu_powerpc.c @@ -333,9 +333,8 @@ ppcDecode(virCPUDefPtr cpu, goto cleanup; }
- if (!(cpu->model = strdup(model->name)) || - (model->vendor && !(cpu->vendor = strdup(model->vendor->name)))) { - virReportOOMError(); + if (VIR_STRDUP(cpu->model, model->name) < 0 || + (model->vendor && VIR_STRDUP(cpu->vendor, model->vendor->name) < 0)) {
Another case where not requiring ATTRIBUTE_NONNNULL(2) on VIR_STRDUP would be handy. I think I've convinced myself we should go that route. Maybe it would help if I post a patch showing what I'm thinking?
Yep. you're completely right. However, the 1st patch is already pushed with ATTRIBUTE_NONNULL(2). So do you want me to post a fix dropping the useless attribute and pushing this without it, or ..,?
AAh, I've just noticed (and ACKed) your cleanup patch set. So I'll wait until you push it after which I'll push this one. Michal

--- src/esx/esx_driver.c | 43 ++++++-------------- src/esx/esx_interface_driver.c | 7 +--- src/esx/esx_network_driver.c | 28 ++++--------- src/esx/esx_storage_backend_iscsi.c | 21 +++------- src/esx/esx_storage_backend_vmfs.c | 16 ++------ src/esx/esx_util.c | 45 +++++---------------- src/esx/esx_vi.c | 79 +++++++------------------------------ src/esx/esx_vi_types.c | 36 +++-------------- 8 files changed, 58 insertions(+), 217 deletions(-) diff --git a/src/esx/esx_driver.c b/src/esx/esx_driver.c index dcf64b8..714a218 100644 --- a/src/esx/esx_driver.c +++ b/src/esx/esx_driver.c @@ -669,12 +669,8 @@ esxConnectToHost(esxPrivate *priv, } if (conn->uri->user != NULL) { - username = strdup(conn->uri->user); - - if (username == NULL) { - virReportOOMError(); + if (VIR_STRDUP(username, conn->uri->user) < 0) goto cleanup; - } } else { username = virAuthGetUsername(conn, auth, "esx", "root", conn->uri->server); @@ -751,14 +747,9 @@ esxConnectToHost(esxPrivate *priv, VIR_WARN("The server is in maintenance mode"); } - if (*vCenterIpAddress != NULL) { - *vCenterIpAddress = strdup(*vCenterIpAddress); - - if (*vCenterIpAddress == NULL) { - virReportOOMError(); - goto cleanup; - } - } + if (!*vCenterIpAddress && + VIR_STRDUP(*vCenterIpAddress, *vCenterIpAddress) < 0) + goto cleanup; result = 0; @@ -801,9 +792,7 @@ esxConnectToVCenter(esxPrivate *priv, } if (conn->uri->user != NULL) { - username = strdup(conn->uri->user); - - if (username == NULL) { + if (VIR_STRDUP(username, conn->uri->user) < 0) { virReportOOMError(); goto cleanup; } @@ -1278,12 +1267,8 @@ esxConnectGetHostname(virConnectPtr conn) } if (domainName == NULL || strlen(domainName) < 1) { - complete = strdup(hostName); - - if (complete == NULL) { - virReportOOMError(); + if (VIR_STRDUP(complete, hostName) < 0) goto cleanup; - } } else { if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0) { virReportOOMError(); @@ -1294,7 +1279,7 @@ esxConnectGetHostname(virConnectPtr conn) cleanup: /* * If we goto cleanup in case of an error then complete is still NULL, - * either strdup returned NULL or virAsprintf failed. When virAsprintf + * either VIR_STRDUP returned NULL or virAsprintf failed. When virAsprintf * fails it guarantees setting complete to NULL */ esxVI_String_Free(&propertyNameList); @@ -2016,13 +2001,9 @@ esxDomainDestroy(virDomainPtr dom) static char * esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED) { - char *osType = strdup("hvm"); - - if (osType == NULL) { - virReportOOMError(); - return NULL; - } + char *osType; + ignore_value(VIR_STRDUP(osType, "hvm")); return osType; } @@ -3577,12 +3558,10 @@ esxDomainSetAutostart(virDomainPtr domain, int autostart) static char * esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams) { - char *type = strdup("allocation"); + char *type; - if (type == NULL) { - virReportOOMError(); + if (VIR_STRDUP(type, "allocation") < 0) return NULL; - } if (nparams != NULL) { *nparams = 3; /* reservation, limit, shares */ diff --git a/src/esx/esx_interface_driver.c b/src/esx/esx_interface_driver.c index fe5194c..7875ccf 100644 --- a/src/esx/esx_interface_driver.c +++ b/src/esx/esx_interface_driver.c @@ -35,6 +35,7 @@ #include "esx_vi.h" #include "esx_vi_methods.h" #include "esx_util.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_ESX @@ -114,12 +115,8 @@ esxConnectListInterfaces(virConnectPtr conn, char **const names, int maxnames) for (physicalNic = physicalNicList; physicalNic != NULL; physicalNic = physicalNic->_next) { - names[count] = strdup(physicalNic->device); - - if (names[count] == NULL) { - virReportOOMError(); + if (VIR_STRDUP(names[count], physicalNic->device) < 0) goto cleanup; - } ++count; } diff --git a/src/esx/esx_network_driver.c b/src/esx/esx_network_driver.c index fd57b61..a4842da 100644 --- a/src/esx/esx_network_driver.c +++ b/src/esx/esx_network_driver.c @@ -35,6 +35,7 @@ #include "esx_vi.h" #include "esx_vi_methods.h" #include "esx_util.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_ESX @@ -122,12 +123,8 @@ esxConnectListNetworks(virConnectPtr conn, char **const names, int maxnames) for (hostVirtualSwitch = hostVirtualSwitchList; hostVirtualSwitch != NULL; hostVirtualSwitch = hostVirtualSwitch->_next) { - names[count] = strdup(hostVirtualSwitch->name); - - if (names[count] == NULL) { - virReportOOMError(); + if (VIR_STRDUP(names[count], hostVirtualSwitch->name) < 0) goto cleanup; - } ++count; } @@ -713,12 +710,8 @@ esxNetworkGetXMLDesc(virNetworkPtr network_, unsigned int flags) md5_buffer(hostVirtualSwitch->key, strlen(hostVirtualSwitch->key), def->uuid); - def->name = strdup(hostVirtualSwitch->name); - - if (def->name == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->name, hostVirtualSwitch->name) < 0) goto cleanup; - } def->forward.type = VIR_NETWORK_FORWARD_NONE; @@ -752,13 +745,9 @@ esxNetworkGetXMLDesc(virNetworkPtr network_, unsigned int flags) if (STREQ(physicalNicKey->value, physicalNic->key)) { def->forward.ifs[def->forward.nifs].type = VIR_NETWORK_FORWARD_HOSTDEV_DEVICE_NETDEV; - def->forward.ifs[def->forward.nifs].device.dev - = strdup(physicalNic->device); - - if (def->forward.ifs[def->forward.nifs].device.dev == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->forward.ifs[def->forward.nifs].device.dev, + physicalNic->device) < 0) goto cleanup; - } ++def->forward.nifs; @@ -823,12 +812,9 @@ esxNetworkGetXMLDesc(virNetworkPtr network_, unsigned int flags) for (networkName = networkNameList; networkName != NULL; networkName = networkName->_next) { if (STREQ(networkName->value, hostPortGroup->spec->name)) { - def->portGroups[def->nPortGroups].name = strdup(networkName->value); - - if (def->portGroups[def->nPortGroups].name == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->portGroups[def->nPortGroups].name, + networkName->value) < 0) goto cleanup; - } if (hostPortGroup->spec->policy != NULL) { if (esxShapingPolicyToBandwidth diff --git a/src/esx/esx_storage_backend_iscsi.c b/src/esx/esx_storage_backend_iscsi.c index 941e800..a22adb4 100644 --- a/src/esx/esx_storage_backend_iscsi.c +++ b/src/esx/esx_storage_backend_iscsi.c @@ -38,6 +38,7 @@ #include "esx_vi.h" #include "esx_vi_methods.h" #include "esx_util.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_ESX @@ -130,12 +131,8 @@ esxStorageBackendISCSIListPools(virConnectPtr conn, char **const names, */ for (target = hostInternetScsiHba->configuredStaticTarget; target != NULL && count < maxnames; target = target->_next) { - names[count] = strdup(target->iScsiName); - - if (names[count] == NULL) { - virReportOOMError(); + if (VIR_STRDUP(names[count], target->iScsiName) < 0) goto cleanup; - } ++count; } @@ -419,12 +416,8 @@ esxStorageBackendISCSIPoolListVolumes(virStoragePoolPtr pool, char **const names hostScsiTopologyLun != NULL && count < maxnames; hostScsiTopologyLun = hostScsiTopologyLun->_next) { if (STREQ(hostScsiTopologyLun->scsiLun, scsiLun->key)) { - names[count] = strdup(scsiLun->deviceName); - - if (names[count] == NULL) { - virReportOOMError(); + if (VIR_STRDUP(names[count], scsiLun->deviceName) < 0) goto cleanup; - } ++count; } @@ -739,13 +732,9 @@ esxStorageBackendISCSIVolumeWipe(virStorageVolPtr volume ATTRIBUTE_UNUSED, static char * esxStorageBackendISCSIVolumeGetPath(virStorageVolPtr volume) { - char *path = strdup(volume->name); - - if (path == NULL) { - virReportOOMError(); - return NULL; - } + char *path; + ignore_value(VIR_STRDUP(path, volume->name)); return path; } diff --git a/src/esx/esx_storage_backend_vmfs.c b/src/esx/esx_storage_backend_vmfs.c index 5d6f183..dd638ad 100644 --- a/src/esx/esx_storage_backend_vmfs.c +++ b/src/esx/esx_storage_backend_vmfs.c @@ -168,12 +168,8 @@ esxStorageBackendVMFSListPools(virConnectPtr conn, char **const names, goto cleanup; } - names[count] = strdup(dynamicProperty->val->string); - - if (names[count] == NULL) { - virReportOOMError(); + if (VIR_STRDUP(names[count], dynamicProperty->val->string) < 0) goto cleanup; - } ++count; break; @@ -614,12 +610,8 @@ esxStorageBackendVMFSPoolListVolumes(virStoragePoolPtr pool, char **const names, for (fileInfo = searchResults->file; fileInfo != NULL; fileInfo = fileInfo->_next) { if (length < 1) { - names[count] = strdup(fileInfo->path); - - if (names[count] == NULL) { - virReportOOMError(); + if (VIR_STRDUP(names[count], fileInfo->path) < 0) goto cleanup; - } } else if (virAsprintf(&names[count], "%s/%s", directoryAndFileName, fileInfo->path) < 0) { virReportOOMError(); @@ -791,10 +783,8 @@ esxStorageBackendVMFSVolumeLookupByKey(virConnectPtr conn, const char *key) VIR_FREE(datastorePath); if (length < 1) { - if (!(volumeName = strdup(fileInfo->path))) { - virReportOOMError(); + if (VIR_STRDUP(volumeName, fileInfo->path) < 0) goto cleanup; - } } else if (virAsprintf(&volumeName, "%s/%s", directoryAndFileName, fileInfo->path) < 0) { diff --git a/src/esx/esx_util.c b/src/esx/esx_util.c index 4566fec..62268aa 100644 --- a/src/esx/esx_util.c +++ b/src/esx/esx_util.c @@ -65,12 +65,8 @@ esxUtil_ParseUri(esxUtil_ParsedUri **parsedUri, virURIPtr uri) if (STRCASEEQ(queryParam->name, "transport")) { VIR_FREE((*parsedUri)->transport); - (*parsedUri)->transport = strdup(queryParam->value); - - if ((*parsedUri)->transport == NULL) { - virReportOOMError(); + if (VIR_STRDUP((*parsedUri)->transport, queryParam->value) < 0) goto cleanup; - } if (STRNEQ((*parsedUri)->transport, "http") && STRNEQ((*parsedUri)->transport, "https")) { @@ -83,12 +79,8 @@ esxUtil_ParseUri(esxUtil_ParsedUri **parsedUri, virURIPtr uri) } else if (STRCASEEQ(queryParam->name, "vcenter")) { VIR_FREE((*parsedUri)->vCenter); - (*parsedUri)->vCenter = strdup(queryParam->value); - - if ((*parsedUri)->vCenter == NULL) { - virReportOOMError(); + if (VIR_STRDUP((*parsedUri)->vCenter, queryParam->value) < 0) goto cleanup; - } } else if (STRCASEEQ(queryParam->name, "no_verify")) { if (virStrToLong_i(queryParam->value, NULL, 10, &noVerify) < 0 || (noVerify != 0 && noVerify != 1)) { @@ -137,12 +129,8 @@ esxUtil_ParseUri(esxUtil_ParsedUri **parsedUri, virURIPtr uri) tmp = queryParam->value; } - (*parsedUri)->proxy_hostname = strdup(tmp); - - if ((*parsedUri)->proxy_hostname == NULL) { - virReportOOMError(); + if (VIR_STRDUP((*parsedUri)->proxy_hostname, tmp) < 0) goto cleanup; - } if ((tmp = strchr((*parsedUri)->proxy_hostname, ':')) != NULL) { if (tmp == (*parsedUri)->proxy_hostname) { @@ -171,23 +159,12 @@ esxUtil_ParseUri(esxUtil_ParsedUri **parsedUri, virURIPtr uri) } } - if (uri->path != NULL) { - (*parsedUri)->path = strdup(uri->path); - - if ((*parsedUri)->path == NULL) { - virReportOOMError(); - goto cleanup; - } - } - - if ((*parsedUri)->transport == NULL) { - (*parsedUri)->transport = strdup("https"); + if (uri->path && VIR_STRDUP((*parsedUri)->path, uri->path) < 0) + goto cleanup; - if ((*parsedUri)->transport == NULL) { - virReportOOMError(); - goto cleanup; - } - } + if (!(*parsedUri)->transport && + VIR_STRDUP((*parsedUri)->transport, "https") < 0) + goto cleanup; result = 0; @@ -494,14 +471,12 @@ esxUtil_ReplaceSpecialWindowsPathChars(char *string) char * esxUtil_EscapeDatastoreItem(const char *string) { - char *replaced = strdup(string); + char *replaced; char *escaped1; char *escaped2 = NULL; - if (replaced == NULL) { - virReportOOMError(); + if (VIR_STRDUP(replaced, string) < 0) return NULL; - } esxUtil_ReplaceSpecialWindowsPathChars(replaced); diff --git a/src/esx/esx_vi.c b/src/esx/esx_vi.c index ee48159..5fd0693 100644 --- a/src/esx/esx_vi.c +++ b/src/esx/esx_vi.c @@ -947,12 +947,8 @@ esxVI_Context_LookupManagedObjects(esxVI_Context *ctx) return -1; } - ctx->datacenterPath = strdup(ctx->datacenter->name); - - if (ctx->datacenterPath == NULL) { - virReportOOMError(); + if (VIR_STRDUP(ctx->datacenterPath, ctx->datacenter->name) < 0) return -1; - } /* Lookup (Cluster)ComputeResource */ if (esxVI_LookupComputeResource(ctx, NULL, ctx->datacenter->hostFolder, @@ -967,12 +963,8 @@ esxVI_Context_LookupManagedObjects(esxVI_Context *ctx) return -1; } - ctx->computeResourcePath = strdup(ctx->computeResource->name); - - if (ctx->computeResourcePath == NULL) { - virReportOOMError(); + if (VIR_STRDUP(ctx->computeResourcePath, ctx->computeResource->name) < 0) return -1; - } /* Lookup HostSystem */ if (esxVI_LookupHostSystem(ctx, NULL, ctx->computeResource->_reference, @@ -981,12 +973,8 @@ esxVI_Context_LookupManagedObjects(esxVI_Context *ctx) return -1; } - ctx->hostSystemName = strdup(ctx->hostSystem->name); - - if (ctx->hostSystemName == NULL) { - virReportOOMError(); + if (VIR_STRDUP(ctx->hostSystemName, ctx->hostSystem->name) < 0) return -1; - } return 0; } @@ -1003,12 +991,8 @@ esxVI_Context_LookupManagedObjectsByPath(esxVI_Context *ctx, const char *path) esxVI_ManagedObjectReference *root = NULL; esxVI_Folder *folder = NULL; - tmp = strdup(path); - - if (tmp == NULL) { - virReportOOMError(); + if (VIR_STRDUP(tmp, path) < 0) goto cleanup; - } /* Lookup Datacenter */ item = strtok_r(tmp, "/", &saveptr); @@ -1160,12 +1144,8 @@ esxVI_Context_LookupManagedObjectsByPath(esxVI_Context *ctx, const char *path) goto cleanup; } - ctx->hostSystemName = strdup(previousItem); - - if (ctx->hostSystemName == NULL) { - virReportOOMError(); + if (VIR_STRDUP(ctx->hostSystemName, previousItem) < 0) goto cleanup; - } if (esxVI_LookupHostSystem(ctx, ctx->hostSystemName, ctx->computeResource->_reference, NULL, @@ -2498,12 +2478,8 @@ esxVI_GetVirtualMachineIdentity(esxVI_ObjectContent *virtualMachine, goto failure; } - *name = strdup(dynamicProperty->val->string); - - if (*name == NULL) { - virReportOOMError(); + if (VIR_STRDUP(*name, dynamicProperty->val->string) < 0) goto failure; - } if (virVMXUnescapeHexPercent(*name) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", @@ -2611,12 +2587,8 @@ esxVI_GetSnapshotTreeNames(esxVI_VirtualMachineSnapshotTree *snapshotTreeList, snapshotTree != NULL && count < nameslen; snapshotTree = snapshotTree->_next) { if (!(leaves && snapshotTree->childSnapshotList)) { - names[count] = strdup(snapshotTree->name); - - if (names[count] == NULL) { - virReportOOMError(); + if (VIR_STRDUP(names[count], snapshotTree->name) < 0) goto failure; - } count++; } @@ -4388,12 +4360,8 @@ esxVI_WaitForTaskCompletion(esxVI_Context *ctx, return -1; } - version = strdup(""); - - if (version == NULL) { - virReportOOMError(); + if (VIR_STRDUP(version, "") < 0) return -1; - } if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) { goto cleanup; @@ -4469,12 +4437,8 @@ esxVI_WaitForTaskCompletion(esxVI_Context *ctx, } VIR_FREE(version); - version = strdup(updateSet->version); - - if (version == NULL) { - virReportOOMError(); + if (VIR_STRDUP(version, updateSet->version) < 0) goto cleanup; - } if (updateSet->filterSet == NULL) { continue; @@ -4523,19 +4487,11 @@ esxVI_WaitForTaskCompletion(esxVI_Context *ctx, } if (taskInfo->error == NULL) { - *errorMessage = strdup(_("Unknown error")); - - if (*errorMessage == NULL) { - virReportOOMError(); + if (VIR_STRDUP(*errorMessage, _("Unknown error")) < 0) goto cleanup; - } } else if (taskInfo->error->localizedMessage == NULL) { - *errorMessage = strdup(taskInfo->error->fault->_actualType); - - if (*errorMessage == NULL) { - virReportOOMError(); + if (VIR_STRDUP(*errorMessage, taskInfo->error->fault->_actualType) < 0) goto cleanup; - } } else { if (virAsprintf(errorMessage, "%s - %s", taskInfo->error->fault->_actualType, @@ -4976,21 +4932,16 @@ esxVI_LookupStoragePoolNameByScsiLunKey(esxVI_Context *ctx, hostScsiTopologyTarget != NULL; hostScsiTopologyTarget = hostScsiTopologyTarget->_next) { candidate = esxVI_HostInternetScsiTargetTransport_DynamicCast - (hostScsiTopologyTarget->transport); + (hostScsiTopologyTarget->transport); if (candidate != NULL) { /* iterate hostScsiTopologyLun list to find matching key */ for (hostScsiTopologyLun = hostScsiTopologyTarget->lun; hostScsiTopologyLun != NULL; hostScsiTopologyLun = hostScsiTopologyLun->_next) { - if (STREQ(hostScsiTopologyLun->scsiLun, key)) { - *poolName = strdup(candidate->iScsiName); - - if (*poolName == NULL) { - virReportOOMError(); - goto cleanup; - } - } + if (STREQ(hostScsiTopologyLun->scsiLun, key) && + VIR_STRDUP(*poolName, candidate->iScsiName) < 0) + goto cleanup; } /* hostScsiTopologyLun iteration done, terminate loop */ diff --git a/src/esx/esx_vi_types.c b/src/esx/esx_vi_types.c index 7f40308..4596520 100644 --- a/src/esx/esx_vi_types.c +++ b/src/esx/esx_vi_types.c @@ -1050,14 +1050,8 @@ esxVI_AnyType_Deserialize(xmlNodePtr node, esxVI_AnyType **anyType) (*anyType)->value = (char *)xmlNodeListGetString(node->doc, node->children, 1); - if ((*anyType)->value == NULL) { - (*anyType)->value = strdup(""); - - if ((*anyType)->value == NULL) { - virReportOOMError(); - goto failure; - } - } + if (!(*anyType)->value && VIR_STRDUP((*anyType)->value, "") < 0) + goto failure; #define _DESERIALIZE_NUMBER(_type, _xsdType, _name, _min, _max) \ do { \ @@ -1177,12 +1171,8 @@ esxVI_String_AppendValueToList(esxVI_String **stringList, const char *value) return -1; } - string->value = strdup(value); - - if (string->value == NULL) { - virReportOOMError(); + if (VIR_STRDUP(string->value, value) < 0) goto failure; - } if (esxVI_String_AppendToList(stringList, string) < 0) { goto failure; @@ -1244,14 +1234,7 @@ esxVI_String_DeepCopyValue(char **dest, const char *src) return 0; } - *dest = strdup(src); - - if (*dest == NULL) { - virReportOOMError(); - return -1; - } - - return 0; + return VIR_STRDUP(*dest, src); } /* esxVI_String_CastFromAnyType */ @@ -1327,16 +1310,7 @@ esxVI_String_DeserializeValue(xmlNodePtr node, char **value) *value = (char *)xmlNodeListGetString(node->doc, node->children, 1); - if (*value == NULL) { - *value = strdup(""); - - if (*value == NULL) { - virReportOOMError(); - return -1; - } - } - - return 0; + return value ? 0 : VIR_STRDUP(*value, ""); } -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/esx/esx_driver.c | 43 ++++++-------------- src/esx/esx_interface_driver.c | 7 +--- src/esx/esx_network_driver.c | 28 ++++--------- src/esx/esx_storage_backend_iscsi.c | 21 +++------- src/esx/esx_storage_backend_vmfs.c | 16 ++------ src/esx/esx_util.c | 45 +++++---------------- src/esx/esx_vi.c | 79 +++++++------------------------------ src/esx/esx_vi_types.c | 36 +++-------------- 8 files changed, 58 insertions(+), 217 deletions(-)
@@ -751,14 +747,9 @@ esxConnectToHost(esxPrivate *priv, VIR_WARN("The server is in maintenance mode"); }
- if (*vCenterIpAddress != NULL) { - *vCenterIpAddress = strdup(*vCenterIpAddress);
Old code: if string is not NULL, replace it with a copy from the heap...
- - if (*vCenterIpAddress == NULL) { - virReportOOMError(); - goto cleanup; - } - } + if (!*vCenterIpAddress && + VIR_STRDUP(*vCenterIpAddress, *vCenterIpAddress) < 0)
New code: if string is NULL, copy NULL to the heap. Oops. Drop the !
@@ -801,9 +792,7 @@ esxConnectToVCenter(esxPrivate *priv, }
if (conn->uri->user != NULL) { - username = strdup(conn->uri->user); - - if (username == NULL) { + if (VIR_STRDUP(username, conn->uri->user) < 0) { virReportOOMError();
Drop the oom error here.
@@ -1278,12 +1267,8 @@ esxConnectGetHostname(virConnectPtr conn) }
if (domainName == NULL || strlen(domainName) < 1) {
Pre-existing, but I'd have written the second condition as '!*domainName' (which is O(1) regardless of the length of domainName, whereas strlen()<1 is O(n) if the compiler doesn't optimize well)
@@ -1294,7 +1279,7 @@ esxConnectGetHostname(virConnectPtr conn) cleanup: /* * If we goto cleanup in case of an error then complete is still NULL, - * either strdup returned NULL or virAsprintf failed. When virAsprintf + * either VIR_STRDUP returned NULL or virAsprintf failed. When virAsprintf
Technically VIR_STRDUP returns -1, not NULL, if you want to touch up this comment.
+++ b/src/esx/esx_util.c @@ -171,23 +159,12 @@ esxUtil_ParseUri(esxUtil_ParsedUri **parsedUri, virURIPtr uri) } }
- if (uri->path != NULL) { - (*parsedUri)->path = strdup(uri->path); - - if ((*parsedUri)->path == NULL) { - virReportOOMError(); - goto cleanup; - } - } - - if ((*parsedUri)->transport == NULL) { - (*parsedUri)->transport = strdup("https"); + if (uri->path && VIR_STRDUP((*parsedUri)->path, uri->path) < 0) + goto cleanup;
Another argument in favor of allowing a NULL source argument.
+++ b/src/esx/esx_vi_types.c @@ -1327,16 +1310,7 @@ esxVI_String_DeserializeValue(xmlNodePtr node, char **value)
*value = (char *)xmlNodeListGetString(node->doc, node->children, 1);
- if (*value == NULL) { - *value = strdup("");
Old code: if xmlNodeListGetString found nothing, set *value to an empty string...
- - if (*value == NULL) { - virReportOOMError(); - return -1; - } - } - - return 0; + return value ? 0 : VIR_STRDUP(*value, "");
New code: since 'value' is non-NULL, unconditionally return 0 even if *value is still NULL. Oops. Missing a * ACK if you fix the bugs I called out. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/hyperv/hyperv_driver.c | 50 ++++++++++------------------------------------ src/hyperv/hyperv_util.c | 18 +++++------------ 2 files changed, 15 insertions(+), 53 deletions(-) diff --git a/src/hyperv/hyperv_driver.c b/src/hyperv/hyperv_driver.c index 7031fdb..2c18cb8 100644 --- a/src/hyperv/hyperv_driver.c +++ b/src/hyperv/hyperv_driver.c @@ -140,12 +140,8 @@ hypervConnectOpen(virConnectPtr conn, virConnectAuthPtr auth, unsigned int flags /* Request credentials */ if (conn->uri->user != NULL) { - username = strdup(conn->uri->user); - - if (username == NULL) { - virReportOOMError(); + if (VIR_STRDUP(username, conn->uri->user) < 0) goto cleanup; - } } else { username = virAuthGetUsername(conn, auth, "hyperv", "administrator", conn->uri->server); @@ -257,12 +253,7 @@ hypervConnectGetHostname(virConnectPtr conn) goto cleanup; } - hostname = strdup(computerSystem->data->DNSHostName); - - if (hostname == NULL) { - virReportOOMError(); - goto cleanup; - } + ignore_value(VIR_STRDUP(hostname, computerSystem->data->DNSHostName)); cleanup: hypervFreeObject(priv, (hypervObject *)computerSystem); @@ -652,13 +643,9 @@ hypervDomainDestroy(virDomainPtr domain) static char * hypervDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED) { - char *osType = strdup("hvm"); - - if (osType == NULL) { - virReportOOMError(); - return NULL; - } + char *osType; + ignore_value(VIR_STRDUP(osType, "hvm")); return osType; } @@ -908,21 +895,12 @@ hypervDomainGetXMLDesc(virDomainPtr domain, unsigned int flags) return NULL; } - def->name = strdup(computerSystem->data->ElementName); - - if (def->name == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->name, computerSystem->data->ElementName) < 0) goto cleanup; - } - - if (virtualSystemSettingData->data->Notes != NULL) { - def->description = strdup(virtualSystemSettingData->data->Notes); - if (def->description == NULL) { - virReportOOMError(); - goto cleanup; - } - } + if (virtualSystemSettingData->data->Notes && + VIR_STRDUP(def->description, virtualSystemSettingData->data->Notes) < 0) + goto cleanup; def->mem.max_balloon = memorySettingData->data->Limit * 1024; /* megabyte to kilobyte */ def->mem.cur_balloon = memorySettingData->data->VirtualQuantity * 1024; /* megabyte to kilobyte */ @@ -930,12 +908,8 @@ hypervDomainGetXMLDesc(virDomainPtr domain, unsigned int flags) def->vcpus = processorSettingData->data->VirtualQuantity; def->maxvcpus = processorSettingData->data->VirtualQuantity; - def->os.type = strdup("hvm"); - - if (def->os.type == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->os.type, "hvm") < 0) goto cleanup; - } /* FIXME: devices section is totally missing */ @@ -981,12 +955,8 @@ hypervConnectListDefinedDomains(virConnectPtr conn, char **const names, int maxn for (computerSystem = computerSystemList; computerSystem != NULL; computerSystem = computerSystem->next) { - names[count] = strdup(computerSystem->data->ElementName); - - if (names[count] == NULL) { - virReportOOMError(); + if (VIR_STRDUP(names[count], computerSystem->data->ElementName) < 0) goto cleanup; - } ++count; diff --git a/src/hyperv/hyperv_util.c b/src/hyperv/hyperv_util.c index a55b939..b7c2a17 100644 --- a/src/hyperv/hyperv_util.c +++ b/src/hyperv/hyperv_util.c @@ -29,6 +29,7 @@ #include "viruuid.h" #include "hyperv_private.h" #include "hyperv_util.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_HYPERV @@ -56,12 +57,8 @@ hypervParseUri(hypervParsedUri **parsedUri, virURIPtr uri) if (STRCASEEQ(queryParam->name, "transport")) { VIR_FREE((*parsedUri)->transport); - (*parsedUri)->transport = strdup(queryParam->value); - - if ((*parsedUri)->transport == NULL) { - virReportOOMError(); + if (VIR_STRDUP((*parsedUri)->transport, queryParam->value) < 0) goto cleanup; - } if (STRNEQ((*parsedUri)->transport, "http") && STRNEQ((*parsedUri)->transport, "https")) { @@ -77,14 +74,9 @@ hypervParseUri(hypervParsedUri **parsedUri, virURIPtr uri) } } - if ((*parsedUri)->transport == NULL) { - (*parsedUri)->transport = strdup("https"); - - if ((*parsedUri)->transport == NULL) { - virReportOOMError(); - goto cleanup; - } - } + if (!(*parsedUri)->transport && + VIR_STRDUP((*parsedUri)->transport, "https") < 0) + goto cleanup; result = 0; -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/hyperv/hyperv_driver.c | 50 ++++++++++------------------------------------ src/hyperv/hyperv_util.c | 18 +++++------------ 2 files changed, 15 insertions(+), 53 deletions(-)
@@ -908,21 +895,12 @@ hypervDomainGetXMLDesc(virDomainPtr domain, unsigned int flags) return NULL; }
- def->name = strdup(computerSystem->data->ElementName); - - if (def->name == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->name, computerSystem->data->ElementName) < 0) goto cleanup; - } - - if (virtualSystemSettingData->data->Notes != NULL) { - def->description = strdup(virtualSystemSettingData->data->Notes);
- if (def->description == NULL) { - virReportOOMError(); - goto cleanup; - } - } + if (virtualSystemSettingData->data->Notes && + VIR_STRDUP(def->description, virtualSystemSettingData->data->Notes) < 0)
Could be simplified by allowing a NULL source (and this time, I actually posted that proposal: https://www.redhat.com/archives/libvir-list/2013-May/msg00458.html) ACK. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/libxl/libxl_conf.c | 86 ++++++++++++++---------------------------------- src/libxl/libxl_driver.c | 14 +++----- 2 files changed, 29 insertions(+), 71 deletions(-) diff --git a/src/libxl/libxl_conf.c b/src/libxl/libxl_conf.c index 3de642b..be7ccaa 100644 --- a/src/libxl/libxl_conf.c +++ b/src/libxl/libxl_conf.c @@ -302,10 +302,8 @@ libxlMakeDomCreateInfo(libxlDriverPrivatePtr driver, else c_info->type = LIBXL_DOMAIN_TYPE_PV; - if ((c_info->name = strdup(def->name)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(c_info->name, def->name) < 0) goto error; - } if (def->nseclabels && def->seclabels[0]->type == VIR_DOMAIN_SECLABEL_STATIC) { @@ -403,10 +401,8 @@ libxlMakeDomBuildInfo(virDomainDefPtr def, libxl_domain_config *d_config) else { bootorder[def->os.nBootDevs] = '\0'; } - if ((b_info->u.hvm.boot = strdup(bootorder)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(b_info->u.hvm.boot, bootorder) < 0) goto error; - } /* * The following comment and calculation were taken directly from @@ -418,37 +414,26 @@ libxlMakeDomBuildInfo(virDomainDefPtr def, libxl_domain_config *d_config) b_info->shadow_memkb = 4 * (256 * libxl_bitmap_count_set(&b_info->avail_vcpus) + 2 * (b_info->max_memkb / 1024)); } else { - if (def->os.bootloader) { - if ((b_info->u.pv.bootloader = strdup(def->os.bootloader)) == NULL) { - virReportOOMError(); - goto error; - } - } + if (def->os.bootloader && + VIR_STRDUP(b_info->u.pv.bootloader, def->os.bootloader) < 0) + goto error; if (def->os.bootloaderArgs) { if (!(b_info->u.pv.bootloader_args = virStringSplit(def->os.bootloaderArgs, " \t\n", 0))) goto error; } - if (def->os.cmdline) { - if ((b_info->u.pv.cmdline = strdup(def->os.cmdline)) == NULL) { - virReportOOMError(); - goto error; - } - } + if (def->os.cmdline && + VIR_STRDUP(b_info->u.pv.cmdline, def->os.cmdline) < 0) + goto error; if (def->os.kernel) { - /* libxl_init_build_info() sets kernel.path = strdup("hvmloader") */ + /* libxl_init_build_info() sets VIR_STRDUP(kernel.path, "hvmloader") */ VIR_FREE(b_info->u.pv.kernel); - if ((b_info->u.pv.kernel = strdup(def->os.kernel)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(b_info->u.pv.kernel, def->os.kernel) < 0) goto error; - } - } - if (def->os.initrd) { - if ((b_info->u.pv.ramdisk = strdup(def->os.initrd)) == NULL) { - virReportOOMError(); - goto error; - } } + if (def->os.initrd && + VIR_STRDUP(b_info->u.pv.ramdisk, def->os.initrd) < 0) + goto error; } return 0; @@ -461,15 +446,11 @@ error: int libxlMakeDisk(virDomainDiskDefPtr l_disk, libxl_device_disk *x_disk) { - if (l_disk->src && (x_disk->pdev_path = strdup(l_disk->src)) == NULL) { - virReportOOMError(); + if (l_disk->src && VIR_STRDUP(x_disk->pdev_path, l_disk->src) < 0) return -1; - } - if (l_disk->dst && (x_disk->vdev = strdup(l_disk->dst)) == NULL) { - virReportOOMError(); + if (l_disk->dst && VIR_STRDUP(x_disk->vdev, l_disk->dst) < 0) return -1; - } if (l_disk->driverName) { if (STREQ(l_disk->driverName, "tap") || @@ -575,31 +556,22 @@ libxlMakeNic(virDomainNetDefPtr l_nic, libxl_device_nic *x_nic) virMacAddrGetRaw(&l_nic->mac, x_nic->mac); if (l_nic->model && !STREQ(l_nic->model, "netfront")) { - if ((x_nic->model = strdup(l_nic->model)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(x_nic->model, l_nic->model) < 0) return -1; - } x_nic->nictype = LIBXL_NIC_TYPE_VIF_IOEMU; } else { x_nic->nictype = LIBXL_NIC_TYPE_VIF; } - if (l_nic->ifname && (x_nic->ifname = strdup(l_nic->ifname)) == NULL) { - virReportOOMError(); + if (l_nic->ifname && VIR_STRDUP(x_nic->ifname, l_nic->ifname) < 0) return -1; - } if (l_nic->type == VIR_DOMAIN_NET_TYPE_BRIDGE) { if (l_nic->data.bridge.brname && - (x_nic->bridge = strdup(l_nic->data.bridge.brname)) == NULL) { - virReportOOMError(); + VIR_STRDUP(x_nic->bridge, l_nic->data.bridge.brname) < 0) return -1; - } - if (l_nic->script && - (x_nic->script = strdup(l_nic->script)) == NULL) { - virReportOOMError(); + if (l_nic->script && VIR_STRDUP(x_nic->script, l_nic->script) < 0) return -1; - } } else { if (l_nic->script) { virReportError(VIR_ERR_CONFIG_UNSUPPORTED, @@ -656,16 +628,11 @@ libxlMakeVfb(libxlDriverPrivatePtr driver, case VIR_DOMAIN_GRAPHICS_TYPE_SDL: libxl_defbool_set(&x_vfb->sdl.enable, 1); if (l_vfb->data.sdl.display && - (x_vfb->sdl.display = strdup(l_vfb->data.sdl.display)) == NULL) { - virReportOOMError(); + VIR_STRDUP(x_vfb->sdl.display, l_vfb->data.sdl.display) < 0) return -1; - } if (l_vfb->data.sdl.xauth && - (x_vfb->sdl.xauthority = - strdup(l_vfb->data.sdl.xauth)) == NULL) { - virReportOOMError(); + VIR_STRDUP(x_vfb->sdl.xauthority, l_vfb->data.sdl.xauth) < 0) return -1; - } break; case VIR_DOMAIN_GRAPHICS_TYPE_VNC: libxl_defbool_set(&x_vfb->vnc.enable, 1); @@ -686,19 +653,14 @@ libxlMakeVfb(libxlDriverPrivatePtr driver, listenAddr = virDomainGraphicsListenGetAddress(l_vfb, 0); if (listenAddr) { - /* libxl_device_vfb_init() does strdup("127.0.0.1") */ + /* libxl_device_vfb_init() does VIR_STRDUP("127.0.0.1") */ VIR_FREE(x_vfb->vnc.listen); - if ((x_vfb->vnc.listen = strdup(listenAddr)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(x_vfb->vnc.listen, listenAddr) < 0) return -1; - } } if (l_vfb->data.vnc.keymap && - (x_vfb->keymap = - strdup(l_vfb->data.vnc.keymap)) == NULL) { - virReportOOMError(); + VIR_STRDUP(x_vfb->keymap, l_vfb->data.vnc.keymap) < 0) return -1; - } break; } diff --git a/src/libxl/libxl_driver.c b/src/libxl/libxl_driver.c index 7361743..be01a4b 100644 --- a/src/libxl/libxl_driver.c +++ b/src/libxl/libxl_driver.c @@ -1881,8 +1881,7 @@ libxlDomainGetOSType(virDomainPtr dom) goto cleanup; } - if (!(type = strdup(vm->def->os.type))) - virReportOOMError(); + ignore_value(VIR_STRDUP(type, vm->def->os.type)); cleanup: if (vm) @@ -3879,18 +3878,18 @@ libxlDomainGetSchedulerType(virDomainPtr dom, int *nparams) *nparams = 0; switch (sched_id) { case LIBXL_SCHEDULER_SEDF: - ret = strdup("sedf"); + ignore_value(VIR_STRDUP(ret, "sedf")); break; case LIBXL_SCHEDULER_CREDIT: - ret = strdup("credit"); + ignore_value(VIR_STRDUP(ret, "credit")); if (nparams) *nparams = XEN_SCHED_CREDIT_NPARAM; break; case LIBXL_SCHEDULER_CREDIT2: - ret = strdup("credit2"); + ignore_value(VIR_STRDUP(ret, "credit2")); break; case LIBXL_SCHEDULER_ARINC653: - ret = strdup("arinc653"); + ignore_value(VIR_STRDUP(ret, "arinc653")); break; default: virReportError(VIR_ERR_INTERNAL_ERROR, @@ -3899,9 +3898,6 @@ libxlDomainGetSchedulerType(virDomainPtr dom, int *nparams) goto cleanup; } - if (!ret) - virReportOOMError(); - cleanup: if (vm) virObjectUnlock(vm); -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/libxl/libxl_conf.c | 86 ++++++++++++++---------------------------------- src/libxl/libxl_driver.c | 14 +++----- 2 files changed, 29 insertions(+), 71 deletions(-)
diff --git a/src/libxl/libxl_conf.c b/src/libxl/libxl_conf.c @@ -418,37 +414,26 @@ libxlMakeDomBuildInfo(virDomainDefPtr def, libxl_domain_config *d_config) b_info->shadow_memkb = 4 * (256 * libxl_bitmap_count_set(&b_info->avail_vcpus) + 2 * (b_info->max_memkb / 1024)); } else { - if (def->os.bootloader) { - if ((b_info->u.pv.bootloader = strdup(def->os.bootloader)) == NULL) { - virReportOOMError(); - goto error; - } - } + if (def->os.bootloader && + VIR_STRDUP(b_info->u.pv.bootloader, def->os.bootloader) < 0)
You can pass NULL source arg now :)
+ goto error; if (def->os.bootloaderArgs) { if (!(b_info->u.pv.bootloader_args = virStringSplit(def->os.bootloaderArgs, " \t\n", 0))) goto error; } - if (def->os.cmdline) { - if ((b_info->u.pv.cmdline = strdup(def->os.cmdline)) == NULL) { - virReportOOMError(); - goto error; - } - } + if (def->os.cmdline && + VIR_STRDUP(b_info->u.pv.cmdline, def->os.cmdline) < 0) + goto error;
and again...
if (def->os.kernel) { - /* libxl_init_build_info() sets kernel.path = strdup("hvmloader") */ + /* libxl_init_build_info() sets VIR_STRDUP(kernel.path, "hvmloader") */ VIR_FREE(b_info->u.pv.kernel); - if ((b_info->u.pv.kernel = strdup(def->os.kernel)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(b_info->u.pv.kernel, def->os.kernel) < 0) goto error;
[Not here, of course]
- } - } - if (def->os.initrd) { - if ((b_info->u.pv.ramdisk = strdup(def->os.initrd)) == NULL) { - virReportOOMError(); - goto error; - } } + if (def->os.initrd && + VIR_STRDUP(b_info->u.pv.ramdisk, def->os.initrd) < 0) + goto error; }
...and a third time.
@@ -461,15 +446,11 @@ error: int libxlMakeDisk(virDomainDiskDefPtr l_disk, libxl_device_disk *x_disk) { - if (l_disk->src && (x_disk->pdev_path = strdup(l_disk->src)) == NULL) { - virReportOOMError(); + if (l_disk->src && VIR_STRDUP(x_disk->pdev_path, l_disk->src) < 0) return -1; - }
- if (l_disk->dst && (x_disk->vdev = strdup(l_disk->dst)) == NULL) { - virReportOOMError(); + if (l_disk->dst && VIR_STRDUP(x_disk->vdev, l_disk->dst) < 0) return -1; - }
These can be simplified as well.
@@ -575,31 +556,22 @@ libxlMakeNic(virDomainNetDefPtr l_nic, libxl_device_nic *x_nic) virMacAddrGetRaw(&l_nic->mac, x_nic->mac);
if (l_nic->model && !STREQ(l_nic->model, "netfront")) { - if ((x_nic->model = strdup(l_nic->model)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(x_nic->model, l_nic->model) < 0) return -1; - } x_nic->nictype = LIBXL_NIC_TYPE_VIF_IOEMU; } else { x_nic->nictype = LIBXL_NIC_TYPE_VIF; }
- if (l_nic->ifname && (x_nic->ifname = strdup(l_nic->ifname)) == NULL) { - virReportOOMError(); + if (l_nic->ifname && VIR_STRDUP(x_nic->ifname, l_nic->ifname) < 0) return -1; - }
And this one.
if (l_nic->type == VIR_DOMAIN_NET_TYPE_BRIDGE) { if (l_nic->data.bridge.brname && - (x_nic->bridge = strdup(l_nic->data.bridge.brname)) == NULL) { - virReportOOMError(); + VIR_STRDUP(x_nic->bridge, l_nic->data.bridge.brname) < 0) return -1; - } - if (l_nic->script && - (x_nic->script = strdup(l_nic->script)) == NULL) { - virReportOOMError(); + if (l_nic->script && VIR_STRDUP(x_nic->script, l_nic->script) < 0) return -1;
And these two.
@@ -656,16 +628,11 @@ libxlMakeVfb(libxlDriverPrivatePtr driver, case VIR_DOMAIN_GRAPHICS_TYPE_SDL: libxl_defbool_set(&x_vfb->sdl.enable, 1); if (l_vfb->data.sdl.display && - (x_vfb->sdl.display = strdup(l_vfb->data.sdl.display)) == NULL) { - virReportOOMError(); + VIR_STRDUP(x_vfb->sdl.display, l_vfb->data.sdl.display) < 0) return -1; - } if (l_vfb->data.sdl.xauth && - (x_vfb->sdl.xauthority = - strdup(l_vfb->data.sdl.xauth)) == NULL) { - virReportOOMError(); + VIR_STRDUP(x_vfb->sdl.xauthority, l_vfb->data.sdl.xauth) < 0) return -1; - }
And some more.
@@ -686,19 +653,14 @@ libxlMakeVfb(libxlDriverPrivatePtr driver,
listenAddr = virDomainGraphicsListenGetAddress(l_vfb, 0); if (listenAddr) { - /* libxl_device_vfb_init() does strdup("127.0.0.1") */ + /* libxl_device_vfb_init() does VIR_STRDUP("127.0.0.1") */ VIR_FREE(x_vfb->vnc.listen); - if ((x_vfb->vnc.listen = strdup(listenAddr)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(x_vfb->vnc.listen, listenAddr) < 0) return -1; - }
[this one can't be simplified]
} if (l_vfb->data.vnc.keymap && - (x_vfb->keymap = - strdup(l_vfb->data.vnc.keymap)) == NULL) { - virReportOOMError(); + VIR_STRDUP(x_vfb->keymap, l_vfb->data.vnc.keymap) < 0) return -1; - }
Another case for simplification.
+++ b/src/libxl/libxl_driver.c @@ -3879,18 +3878,18 @@ libxlDomainGetSchedulerType(virDomainPtr dom, int *nparams) *nparams = 0; switch (sched_id) { case LIBXL_SCHEDULER_SEDF: - ret = strdup("sedf"); + ignore_value(VIR_STRDUP(ret, "sedf")); break; case LIBXL_SCHEDULER_CREDIT: - ret = strdup("credit"); + ignore_value(VIR_STRDUP(ret, "credit")); if (nparams) *nparams = XEN_SCHED_CREDIT_NPARAM; break; case LIBXL_SCHEDULER_CREDIT2: - ret = strdup("credit2"); + ignore_value(VIR_STRDUP(ret, "credit2")); break; case LIBXL_SCHEDULER_ARINC653: - ret = strdup("arinc653"); + ignore_value(VIR_STRDUP(ret, "arinc653")); break;
This is correct, but I wonder if looks any better with fewer ignore_value calls as follows: const char *name; switch (sched_id) { case LIBXL_SCHEDULER_SEDF: name = "sedf"; break; case LIBXL_SCHEDULER_CREDIT: name = "credit"; if (nparams) *nparams = XEN_SCHED_CREDIT_NPARAM; break; ... } ignore_value(VIR_STRDUP(ret, name)); ACK. I'm okay whether you make the simplifications possible for a NULL source argument now or as a followup patch, and didn't spot anything wrong with this patch as-is. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/locking/lock_daemon.c | 30 +++++++++++----------------- src/locking/lock_daemon_config.c | 12 +++++------ src/locking/lock_daemon_dispatch.c | 6 ++---- src/locking/lock_driver_lockd.c | 41 ++++++++++++++++---------------------- src/locking/lock_driver_sanlock.c | 12 ++++------- src/locking/lock_manager.c | 4 +--- 6 files changed, 41 insertions(+), 64 deletions(-) diff --git a/src/locking/lock_daemon.c b/src/locking/lock_daemon.c index 0d8ef39..bb1626e 100644 --- a/src/locking/lock_daemon.c +++ b/src/locking/lock_daemon.c @@ -370,8 +370,8 @@ virLockDaemonPidFilePath(bool privileged, char **pidfile) { if (privileged) { - if (!(*pidfile = strdup(LOCALSTATEDIR "/run/virtlockd.pid"))) - goto no_memory; + if (VIR_STRDUP(*pidfile, LOCALSTATEDIR "/run/virtlockd.pid") < 0) + goto error; } else { char *rundir = NULL; mode_t old_umask; @@ -388,7 +388,8 @@ virLockDaemonPidFilePath(bool privileged, if (virAsprintf(pidfile, "%s/virtlockd.pid", rundir) < 0) { VIR_FREE(rundir); - goto no_memory; + virReportOOMError(); + goto error; } VIR_FREE(rundir); @@ -396,8 +397,6 @@ virLockDaemonPidFilePath(bool privileged, return 0; -no_memory: - virReportOOMError(); error: return -1; } @@ -408,8 +407,8 @@ virLockDaemonUnixSocketPaths(bool privileged, char **sockfile) { if (privileged) { - if (!(*sockfile = strdup(LOCALSTATEDIR "/run/libvirt/virtlockd-sock"))) - goto no_memory; + if (VIR_STRDUP(*sockfile, LOCALSTATEDIR "/run/libvirt/virtlockd-sock") < 0) + goto error; } else { char *rundir = NULL; mode_t old_umask; @@ -426,15 +425,14 @@ virLockDaemonUnixSocketPaths(bool privileged, if (virAsprintf(sockfile, "%s/virtlockd-sock", rundir) < 0) { VIR_FREE(rundir); - goto no_memory; + virReportOOMError(); + goto error; } VIR_FREE(rundir); } return 0; -no_memory: - virReportOOMError(); error: return -1; } @@ -867,10 +865,8 @@ virLockDaemonClientNewPostExecRestart(virNetServerClientPtr client, _("Missing ownerName data in JSON document")); goto error; } - if (!(priv->ownerName = strdup(ownerName))) { - virReportOOMError(); + if (VIR_STRDUP(priv->ownerName, ownerName) < 0) goto error; - } if (!(ownerUUID = virJSONValueObjectGetString(object, "ownerUUID"))) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Missing ownerUUID data in JSON document")); @@ -1221,13 +1217,13 @@ int main(int argc, char **argv) { case 'p': VIR_FREE(pid_file); - if (!(pid_file = strdup(optarg))) + if (VIR_STRDUP(pid_file, optarg) < 0) exit(EXIT_FAILURE); break; case 'f': VIR_FREE(remote_config_file); - if (!(remote_config_file = strdup(optarg))) + if (VIR_STRDUP(remote_config_file, optarg) < 0) exit(EXIT_FAILURE); break; @@ -1312,10 +1308,8 @@ int main(int argc, char **argv) { /* Ensure the rundir exists (on tmpfs on some systems) */ if (privileged) { - if (!(run_dir = strdup(LOCALSTATEDIR "/run/libvirt"))) { - virReportOOMError(); + if (VIR_STRDUP(run_dir, LOCALSTATEDIR "/run/libvirt") < 0) goto cleanup; - } } else { if (!(run_dir = virGetUserRuntimeDirectory())) { VIR_ERROR(_("Can't determine user directory")); diff --git a/src/locking/lock_daemon_config.c b/src/locking/lock_daemon_config.c index c3d59bd..4d7fe7d 100644 --- a/src/locking/lock_daemon_config.c +++ b/src/locking/lock_daemon_config.c @@ -53,8 +53,8 @@ checkType(virConfValuePtr p, const char *filename, } /* If there is no config data for the key, #var_name, then do nothing. - If there is valid data of type VIR_CONF_STRING, and strdup succeeds, - store the result in var_name. Otherwise, (i.e. invalid type, or strdup + If there is valid data of type VIR_CONF_STRING, and VIR_STRDUP succeeds, + store the result in var_name. Otherwise, (i.e. invalid type, or VIR_STRDUP failure), give a diagnostic and "goto" the cleanup-and-fail label. */ #define GET_CONF_STR(conf, filename, var_name) \ do { \ @@ -63,10 +63,8 @@ checkType(virConfValuePtr p, const char *filename, if (checkType(p, filename, #var_name, VIR_CONF_STRING) < 0) \ goto error; \ VIR_FREE(data->var_name); \ - if (!(data->var_name = strdup(p->str))) { \ - virReportOOMError(); \ + if (VIR_STRDUP(data->var_name, p->str) < 0) \ goto error; \ - } \ } \ } while (0) @@ -85,8 +83,8 @@ int virLockDaemonConfigFilePath(bool privileged, char **configfile) { if (privileged) { - if (!(*configfile = strdup(SYSCONFDIR "/libvirt/virtlockd.conf"))) - goto no_memory; + if (VIR_STRDUP(*configfile, SYSCONFDIR "/libvirt/virtlockd.conf") < 0) + goto error; } else { char *configdir = NULL; diff --git a/src/locking/lock_daemon_dispatch.c b/src/locking/lock_daemon_dispatch.c index 8a92802..c2e1000 100644 --- a/src/locking/lock_daemon_dispatch.c +++ b/src/locking/lock_daemon_dispatch.c @@ -25,7 +25,7 @@ #include "rpc/virnetserver.h" #include "rpc/virnetserverclient.h" #include "virlog.h" - +#include "virstring.h" #include "lock_daemon.h" #include "lock_protocol.h" #include "lock_daemon_dispatch_stubs.h" @@ -275,10 +275,8 @@ virLockSpaceProtocolDispatchRegister(virNetServerPtr server ATTRIBUTE_UNUSED, goto cleanup; } - if (!(priv->ownerName = strdup(args->owner.name))) { - virReportOOMError(); + if (VIR_STRDUP(priv->ownerName, args->owner.name) < 0) goto cleanup; - } memcpy(priv->ownerUUID, args->owner.uuid, VIR_UUID_BUFLEN); priv->ownerId = args->owner.id; priv->ownerPid = args->owner.pid; diff --git a/src/locking/lock_driver_lockd.c b/src/locking/lock_driver_lockd.c index 28a4f15..70d8f1d 100644 --- a/src/locking/lock_driver_lockd.c +++ b/src/locking/lock_driver_lockd.c @@ -129,8 +129,7 @@ static int virLockManagerLockDaemonLoadConfig(const char *configFile) CHECK_TYPE("file_lockspace_dir", VIR_CONF_STRING); if (p && p->str) { VIR_FREE(driver->fileLockSpaceDir); - if (!(driver->fileLockSpaceDir = strdup(p->str))) { - virReportOOMError(); + if (VIR_STRDUP(driver->fileLockSpaceDir, p->str) < 0) { virConfFree(conf); return -1; } @@ -140,8 +139,7 @@ static int virLockManagerLockDaemonLoadConfig(const char *configFile) CHECK_TYPE("lvm_lockspace_dir", VIR_CONF_STRING); if (p && p->str) { VIR_FREE(driver->lvmLockSpaceDir); - if (!(driver->lvmLockSpaceDir = strdup(p->str))) { - virReportOOMError(); + if (VIR_STRDUP(driver->lvmLockSpaceDir, p->str) < 0) { virConfFree(conf); return -1; } @@ -151,8 +149,7 @@ static int virLockManagerLockDaemonLoadConfig(const char *configFile) CHECK_TYPE("scsi_lockspace_dir", VIR_CONF_STRING); if (p && p->str) { VIR_FREE(driver->scsiLockSpaceDir); - if (!(driver->scsiLockSpaceDir = strdup(p->str))) { - virReportOOMError(); + if (VIR_STRDUP(driver->scsiLockSpaceDir, p->str) < 0) { virConfFree(conf); return -1; } @@ -174,10 +171,8 @@ static char *virLockManagerLockDaemonPath(bool privileged) { char *path; if (privileged) { - if (!(path = strdup(LOCALSTATEDIR "/run/libvirt/virtlockd-sock"))) { - virReportOOMError(); + if (VIR_STRDUP(path, LOCALSTATEDIR "/run/libvirt/virtlockd-sock") < 0) return NULL; - } } else { char *rundir = NULL; @@ -468,10 +463,8 @@ static int virLockManagerLockDaemonNew(virLockManagerPtr lock, if (STREQ(params[i].key, "uuid")) { memcpy(priv->uuid, params[i].value.uuid, VIR_UUID_BUFLEN); } else if (STREQ(params[i].key, "name")) { - if (!(priv->name = strdup(params[i].value.str))) { - virReportOOMError(); + if (VIR_STRDUP(priv->name, params[i].value.str) < 0) return -1; - } } else if (STREQ(params[i].key, "id")) { priv->id = params[i].value.i; } else if (STREQ(params[i].key, "pid")) { @@ -588,8 +581,8 @@ static int virLockManagerLockDaemonAddResource(virLockManagerPtr lock, if (newName) { VIR_DEBUG("Got an LVM UUID %s for %s", newName, name); - if (!(newLockspace = strdup(driver->lvmLockSpaceDir))) - goto no_memory; + if (VIR_STRDUP(newLockspace, driver->lvmLockSpaceDir) < 0) + goto error; autoCreate = true; break; } @@ -605,8 +598,8 @@ static int virLockManagerLockDaemonAddResource(virLockManagerPtr lock, if (newName) { VIR_DEBUG("Got an SCSI ID %s for %s", newName, name); - if (!(newLockspace = strdup(driver->scsiLockSpaceDir))) - goto no_memory; + if (VIR_STRDUP(newLockspace, driver->scsiLockSpaceDir) < 0) + goto error; autoCreate = true; break; } @@ -615,17 +608,17 @@ static int virLockManagerLockDaemonAddResource(virLockManagerPtr lock, } if (driver->fileLockSpaceDir) { - if (!(newLockspace = strdup(driver->fileLockSpaceDir))) - goto no_memory; + if (VIR_STRDUP(newLockspace, driver->fileLockSpaceDir) < 0) + goto error; if (!(newName = virLockManagerLockDaemonDiskLeaseName(name))) goto no_memory; autoCreate = true; VIR_DEBUG("Using indirect lease %s for %s", newName, name); } else { - if (!(newLockspace = strdup(""))) - goto no_memory; - if (!(newName = strdup(name))) - goto no_memory; + if (VIR_STRDUP(newLockspace, "") < 0) + goto error; + if (VIR_STRDUP(newName, name) < 0) + goto error; VIR_DEBUG("Using direct lease for %s", name); } @@ -662,8 +655,8 @@ static int virLockManagerLockDaemonAddResource(virLockManagerPtr lock, virReportOOMError(); return -1; } - if (!(newName = strdup(name))) - goto no_memory; + if (VIR_STRDUP(newName, name) < 0) + goto error; } break; default: diff --git a/src/locking/lock_driver_sanlock.c b/src/locking/lock_driver_sanlock.c index 4b48868..eb15e29 100644 --- a/src/locking/lock_driver_sanlock.c +++ b/src/locking/lock_driver_sanlock.c @@ -129,8 +129,7 @@ static int virLockManagerSanlockLoadConfig(const char *configFile) CHECK_TYPE("disk_lease_dir", VIR_CONF_STRING); if (p && p->str) { VIR_FREE(driver->autoDiskLeasePath); - if (!(driver->autoDiskLeasePath = strdup(p->str))) { - virReportOOMError(); + if (VIR_STRDUP(driver->autoDiskLeasePath, p->str) < 0) { virConfFree(conf); return -1; } @@ -150,8 +149,7 @@ static int virLockManagerSanlockLoadConfig(const char *configFile) p = virConfGetValue(conf, "user"); CHECK_TYPE("user", VIR_CONF_STRING); if (p) { - if (!(tmp = strdup(p->str))) { - virReportOOMError(); + if (VIR_STRDUP(tmp, p->str) < 0) { virConfFree(conf); return -1; } @@ -167,8 +165,7 @@ static int virLockManagerSanlockLoadConfig(const char *configFile) p = virConfGetValue(conf, "group"); CHECK_TYPE("group", VIR_CONF_STRING); if (p) { - if (!(tmp = strdup(p->str))) { - virReportOOMError(); + if (VIR_STRDUP(tmp, p->str) < 0) { virConfFree(conf); return -1; } @@ -408,9 +405,8 @@ static int virLockManagerSanlockInit(unsigned int version, driver->autoDiskLease = false; driver->user = (uid_t) -1; driver->group = (gid_t) -1; - if (!(driver->autoDiskLeasePath = strdup(LOCALSTATEDIR "/lib/libvirt/sanlock"))) { + if (VIR_STRDUP(driver->autoDiskLeasePath, LOCALSTATEDIR "/lib/libvirt/sanlock") < 0) { VIR_FREE(driver); - virReportOOMError(); goto error; } diff --git a/src/locking/lock_manager.c b/src/locking/lock_manager.c index 82bbe6b..4cffc3f 100644 --- a/src/locking/lock_manager.c +++ b/src/locking/lock_manager.c @@ -194,10 +194,8 @@ virLockManagerPluginPtr virLockManagerPluginNew(const char *name, plugin->driver = driver; plugin->handle = handle; plugin->refs = 1; - if (!(plugin->name = strdup(name))) { - virReportOOMError(); + if (VIR_STRDUP(plugin->name, name) < 0) goto cleanup; - } VIR_FREE(configFile); VIR_FREE(modfile); -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/locking/lock_daemon.c | 30 +++++++++++----------------- src/locking/lock_daemon_config.c | 12 +++++------ src/locking/lock_daemon_dispatch.c | 6 ++---- src/locking/lock_driver_lockd.c | 41 ++++++++++++++++---------------------- src/locking/lock_driver_sanlock.c | 12 ++++------- src/locking/lock_manager.c | 4 +--- 6 files changed, 41 insertions(+), 64 deletions(-)
diff --git a/src/locking/lock_daemon.c b/src/locking/lock_daemon.c
@@ -1221,13 +1217,13 @@ int main(int argc, char **argv) {
case 'p': VIR_FREE(pid_file); - if (!(pid_file = strdup(optarg))) + if (VIR_STRDUP(pid_file, optarg) < 0) exit(EXIT_FAILURE);
Hmm, for the similar patch to libvirtd earlier in the series, you used VIR_STRDUP_QUIET and an explicit VIR_WARN when inside main() on the grounds that it's too early to rely on normal error handling being up. Do we need to do that here as well?
break;
case 'f': VIR_FREE(remote_config_file); - if (!(remote_config_file = strdup(optarg))) + if (VIR_STRDUP(remote_config_file, optarg) < 0) exit(EXIT_FAILURE);
Again, a case where immediately calling exit() may eat the error message, compared to VIR_STRDUP_QUIET/VIR_WARN. ACK once you consider that point. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/lxc/lxc_cgroup.c | 3 +-- src/lxc/lxc_conf.c | 36 +++++++++++++++++------------------- src/lxc/lxc_container.c | 18 ++++-------------- src/lxc/lxc_controller.c | 20 ++++++++------------ src/lxc/lxc_driver.c | 9 ++------- src/lxc/lxc_process.c | 7 ++++--- 6 files changed, 36 insertions(+), 57 deletions(-) diff --git a/src/lxc/lxc_cgroup.c b/src/lxc/lxc_cgroup.c index bc3b0d1..de6b53b 100644 --- a/src/lxc/lxc_cgroup.c +++ b/src/lxc/lxc_cgroup.c @@ -538,8 +538,7 @@ virCgroupPtr virLXCCgroupCreate(virDomainDefPtr def, bool startup) goto cleanup; } - if (!(res->partition = strdup("/machine"))) { - virReportOOMError(); + if (VIR_STRDUP(res->partition, "/machine") < 0) { VIR_FREE(res); goto cleanup; } diff --git a/src/lxc/lxc_conf.c b/src/lxc/lxc_conf.c index 13c0d97..81a4a33 100644 --- a/src/lxc/lxc_conf.c +++ b/src/lxc/lxc_conf.c @@ -37,7 +37,7 @@ #include "configmake.h" #include "lxc_container.h" #include "virnodesuspend.h" - +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_LXC @@ -119,10 +119,10 @@ virCapsPtr lxcCapsInit(virLXCDriverPtr driver) if (VIR_ALLOC(caps->host.secModels) < 0) goto no_memory; caps->host.nsecModels = 1; - if (!(caps->host.secModels[0].model = strdup(model))) - goto no_memory; - if (!(caps->host.secModels[0].doi = strdup(doi))) - goto no_memory; + if (VIR_STRDUP(caps->host.secModels[0].model, model) < 0) + goto error; + if (VIR_STRDUP(caps->host.secModels[0].doi, doi) < 0) + goto error; } VIR_DEBUG("Initialized caps for security driver \"%s\" with " @@ -161,18 +161,18 @@ int lxcLoadDriverConfig(virLXCDriverPtr driver) driver->securityRequireConfined = false; /* Set the container configuration directory */ - if ((driver->configDir = strdup(LXC_CONFIG_DIR)) == NULL) - goto no_memory; - if ((driver->stateDir = strdup(LXC_STATE_DIR)) == NULL) - goto no_memory; - if ((driver->logDir = strdup(LXC_LOG_DIR)) == NULL) - goto no_memory; - if ((driver->autostartDir = strdup(LXC_AUTOSTART_DIR)) == NULL) - goto no_memory; + if (VIR_STRDUP(driver->configDir, LXC_CONFIG_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->stateDir, LXC_STATE_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->logDir, LXC_LOG_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->autostartDir, LXC_AUTOSTART_DIR) < 0) + goto error; - if ((filename = strdup(SYSCONFDIR "/libvirt/lxc.conf")) == NULL) - goto no_memory; + if (VIR_STRDUP(filename, SYSCONFDIR "/libvirt/lxc.conf") < 0) + goto error; /* Avoid error from non-existant or unreadable file. */ if (access(filename, R_OK) == -1) @@ -196,8 +196,7 @@ int lxcLoadDriverConfig(virLXCDriverPtr driver) p = virConfGetValue(conf, "security_driver"); CHECK_TYPE("security_driver", VIR_CONF_STRING); if (p && p->str) { - if (!(driver->securityDriverName = strdup(p->str))) { - virReportOOMError(); + if (VIR_STRDUP(driver->securityDriverName, p->str) < 0) { virConfFree(conf); return -1; } @@ -220,7 +219,6 @@ done: VIR_FREE(filename); return 0; -no_memory: - virReportOOMError(); +error: return -1; } diff --git a/src/lxc/lxc_container.c b/src/lxc/lxc_container.c index ff4069a..2ad0bcf 100644 --- a/src/lxc/lxc_container.c +++ b/src/lxc/lxc_container.c @@ -439,10 +439,8 @@ static int lxcContainerGetSubtree(const char *prefix, virReportOOMError(); goto cleanup; } - if (!(mounts[nmounts] = strdup(mntent.mnt_dir))) { - virReportOOMError(); + if (VIR_STRDUP(mounts[nmounts], mntent.mnt_dir) < 0) goto cleanup; - } nmounts++; VIR_DEBUG("Grabbed %s", mntent.mnt_dir); } @@ -1041,10 +1039,8 @@ lxcContainerMountDetectFilesystem(const char *src, char **type) goto cleanup; } - if (!(*type = strdup(data))) { - virReportOOMError(); + if (VIR_STRDUP(*type, data) < 0) goto cleanup; - } done: ret = 0; @@ -1947,17 +1943,11 @@ static int lxcContainerChild(void *data) virReportOOMError(); goto cleanup; } - } else { - if (!(ttyPath = strdup(argv->ttyPaths[0]))) { - virReportOOMError(); + } else if (VIR_STRDUP(ttyPath, argv->ttyPaths[0]) < 0) { goto cleanup; - } } - } else { - if (!(ttyPath = strdup("/dev/null"))) { - virReportOOMError(); + } else if (VIR_STRDUP(ttyPath, "/dev/null") < 0) { goto cleanup; - } } VIR_DEBUG("Container TTY path: %s", ttyPath); diff --git a/src/lxc/lxc_controller.c b/src/lxc/lxc_controller.c index f1800eb..8c358c3 100644 --- a/src/lxc/lxc_controller.c +++ b/src/lxc/lxc_controller.c @@ -150,14 +150,16 @@ static virLXCControllerPtr virLXCControllerNew(const char *name) virDomainXMLOptionPtr xmlopt = NULL; char *configFile = NULL; - if (VIR_ALLOC(ctrl) < 0) - goto no_memory; + if (VIR_ALLOC(ctrl) < 0) { + virReportOOMError(); + goto error; + } ctrl->timerShutdown = -1; ctrl->firstClient = true; - if (!(ctrl->name = strdup(name))) - goto no_memory; + if (VIR_STRDUP(ctrl->name, name) < 0) + goto error; if ((caps = lxcCapsInit(NULL)) == NULL) goto error; @@ -186,8 +188,6 @@ cleanup: virObjectUnref(xmlopt); return ctrl; -no_memory: - virReportOOMError(); error: virLXCControllerFree(ctrl); ctrl = NULL; @@ -1566,10 +1566,8 @@ int main(int argc, char *argv[]) break; case 'n': - if ((name = strdup(optarg)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(name, optarg) < 0) goto cleanup; - } break; case 'v': @@ -1577,10 +1575,8 @@ int main(int argc, char *argv[]) virReportOOMError(); goto cleanup; } - if ((veths[nveths++] = strdup(optarg)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(veths[nveths++], optarg) < 0) goto cleanup; - } break; case 'c': diff --git a/src/lxc/lxc_driver.c b/src/lxc/lxc_driver.c index 84a97de..42e4989 100644 --- a/src/lxc/lxc_driver.c +++ b/src/lxc/lxc_driver.c @@ -626,10 +626,7 @@ static char *lxcDomainGetOSType(virDomainPtr dom) goto cleanup; } - ret = strdup(vm->def->os.type); - - if (ret == NULL) - virReportOOMError(); + ignore_value(VIR_STRDUP(ret, vm->def->os.type)); cleanup: if (vm) @@ -1629,9 +1626,7 @@ static char *lxcDomainGetSchedulerType(virDomainPtr dom, *nparams = 3; } - ret = strdup("posix"); - if (!ret) - virReportOOMError(); + ignore_value(VIR_STRDUP(ret, "posix")); cleanup: if (vm) diff --git a/src/lxc/lxc_process.c b/src/lxc/lxc_process.c index b10e81c..b06d748 100644 --- a/src/lxc/lxc_process.c +++ b/src/lxc/lxc_process.c @@ -996,9 +996,9 @@ virLXCProcessEnsureRootFS(virDomainObjPtr vm) root->type = VIR_DOMAIN_FS_TYPE_MOUNT; - if (!(root->src = strdup("/")) || - !(root->dst = strdup("/"))) - goto no_memory; + if (VIR_STRDUP(root->src, "/") < 0 || + VIR_STRDUP(root->dst, "/") < 0) + goto error; if (VIR_INSERT_ELEMENT(vm->def->fss, 0, @@ -1010,6 +1010,7 @@ virLXCProcessEnsureRootFS(virDomainObjPtr vm) no_memory: virReportOOMError(); +error: virDomainFSDefFree(root); return -1; } -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/lxc/lxc_cgroup.c | 3 +-- src/lxc/lxc_conf.c | 36 +++++++++++++++++------------------- src/lxc/lxc_container.c | 18 ++++-------------- src/lxc/lxc_controller.c | 20 ++++++++------------ src/lxc/lxc_driver.c | 9 ++------- src/lxc/lxc_process.c | 7 ++++--- 6 files changed, 36 insertions(+), 57 deletions(-)
diff --git a/src/lxc/lxc_cgroup.c b/src/lxc/lxc_cgroup.c @@ -161,18 +161,18 @@ int lxcLoadDriverConfig(virLXCDriverPtr driver) driver->securityRequireConfined = false;
/* Set the container configuration directory */ - if ((driver->configDir = strdup(LXC_CONFIG_DIR)) == NULL) - goto no_memory; - if ((driver->stateDir = strdup(LXC_STATE_DIR)) == NULL) - goto no_memory; - if ((driver->logDir = strdup(LXC_LOG_DIR)) == NULL) - goto no_memory; - if ((driver->autostartDir = strdup(LXC_AUTOSTART_DIR)) == NULL) - goto no_memory; + if (VIR_STRDUP(driver->configDir, LXC_CONFIG_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->stateDir, LXC_STATE_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->logDir, LXC_LOG_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->autostartDir, LXC_AUTOSTART_DIR) < 0) + goto error;
You could chain these into one 'if', if desired. ACK. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On Wed, May 08, 2013 at 04:01:04PM -0600, Eric Blake wrote:
On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/lxc/lxc_cgroup.c | 3 +-- src/lxc/lxc_conf.c | 36 +++++++++++++++++------------------- src/lxc/lxc_container.c | 18 ++++-------------- src/lxc/lxc_controller.c | 20 ++++++++------------ src/lxc/lxc_driver.c | 9 ++------- src/lxc/lxc_process.c | 7 ++++--- 6 files changed, 36 insertions(+), 57 deletions(-)
diff --git a/src/lxc/lxc_cgroup.c b/src/lxc/lxc_cgroup.c @@ -161,18 +161,18 @@ int lxcLoadDriverConfig(virLXCDriverPtr driver) driver->securityRequireConfined = false;
/* Set the container configuration directory */ - if ((driver->configDir = strdup(LXC_CONFIG_DIR)) == NULL) - goto no_memory; - if ((driver->stateDir = strdup(LXC_STATE_DIR)) == NULL) - goto no_memory; - if ((driver->logDir = strdup(LXC_LOG_DIR)) == NULL) - goto no_memory; - if ((driver->autostartDir = strdup(LXC_AUTOSTART_DIR)) == NULL) - goto no_memory; + if (VIR_STRDUP(driver->configDir, LXC_CONFIG_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->stateDir, LXC_STATE_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->logDir, LXC_LOG_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->autostartDir, LXC_AUTOSTART_DIR) < 0) + goto error;
You could chain these into one 'if', if desired.
I generally prefer it if we do not merge separate statements like these into one if, because it makes debugging harder. eg if any of these were to generate a SEGV, then GDB can only tell you the line of the start of the if(). Having them separate it can tell you exactly which is at fault. Daniel -- |: http://berrange.com -o- http://www.flickr.com/photos/dberrange/ :| |: http://libvirt.org -o- http://virt-manager.org :| |: http://autobuild.org -o- http://search.cpan.org/~danberr/ :| |: http://entangle-photo.org -o- http://live.gnome.org/gtk-vnc :|

On 09.05.2013 10:15, Daniel P. Berrange wrote:
On Wed, May 08, 2013 at 04:01:04PM -0600, Eric Blake wrote:
On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/lxc/lxc_cgroup.c | 3 +-- src/lxc/lxc_conf.c | 36 +++++++++++++++++------------------- src/lxc/lxc_container.c | 18 ++++-------------- src/lxc/lxc_controller.c | 20 ++++++++------------ src/lxc/lxc_driver.c | 9 ++------- src/lxc/lxc_process.c | 7 ++++--- 6 files changed, 36 insertions(+), 57 deletions(-)
diff --git a/src/lxc/lxc_cgroup.c b/src/lxc/lxc_cgroup.c @@ -161,18 +161,18 @@ int lxcLoadDriverConfig(virLXCDriverPtr driver) driver->securityRequireConfined = false;
/* Set the container configuration directory */ - if ((driver->configDir = strdup(LXC_CONFIG_DIR)) == NULL) - goto no_memory; - if ((driver->stateDir = strdup(LXC_STATE_DIR)) == NULL) - goto no_memory; - if ((driver->logDir = strdup(LXC_LOG_DIR)) == NULL) - goto no_memory; - if ((driver->autostartDir = strdup(LXC_AUTOSTART_DIR)) == NULL) - goto no_memory; + if (VIR_STRDUP(driver->configDir, LXC_CONFIG_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->stateDir, LXC_STATE_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->logDir, LXC_LOG_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->autostartDir, LXC_AUTOSTART_DIR) < 0) + goto error;
You could chain these into one 'if', if desired.
I generally prefer it if we do not merge separate statements like these into one if, because it makes debugging harder. eg if any of these were to generate a SEGV, then GDB can only tell you the line of the start of the if(). Having them separate it can tell you exactly which is at fault.
Daniel
Not true unless you compile without -g. If you do copile with -g gdb is actually able to tell you the full stack trace - so you can see the right line within if() statement which caused the trouble. Michal

On Thu, May 09, 2013 at 12:31:14PM +0200, Michal Privoznik wrote:
On 09.05.2013 10:15, Daniel P. Berrange wrote:
On Wed, May 08, 2013 at 04:01:04PM -0600, Eric Blake wrote:
On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/lxc/lxc_cgroup.c | 3 +-- src/lxc/lxc_conf.c | 36 +++++++++++++++++------------------- src/lxc/lxc_container.c | 18 ++++-------------- src/lxc/lxc_controller.c | 20 ++++++++------------ src/lxc/lxc_driver.c | 9 ++------- src/lxc/lxc_process.c | 7 ++++--- 6 files changed, 36 insertions(+), 57 deletions(-)
diff --git a/src/lxc/lxc_cgroup.c b/src/lxc/lxc_cgroup.c @@ -161,18 +161,18 @@ int lxcLoadDriverConfig(virLXCDriverPtr driver) driver->securityRequireConfined = false;
/* Set the container configuration directory */ - if ((driver->configDir = strdup(LXC_CONFIG_DIR)) == NULL) - goto no_memory; - if ((driver->stateDir = strdup(LXC_STATE_DIR)) == NULL) - goto no_memory; - if ((driver->logDir = strdup(LXC_LOG_DIR)) == NULL) - goto no_memory; - if ((driver->autostartDir = strdup(LXC_AUTOSTART_DIR)) == NULL) - goto no_memory; + if (VIR_STRDUP(driver->configDir, LXC_CONFIG_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->stateDir, LXC_STATE_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->logDir, LXC_LOG_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->autostartDir, LXC_AUTOSTART_DIR) < 0) + goto error;
You could chain these into one 'if', if desired.
I generally prefer it if we do not merge separate statements like these into one if, because it makes debugging harder. eg if any of these were to generate a SEGV, then GDB can only tell you the line of the start of the if(). Having them separate it can tell you exactly which is at fault.
Daniel
Not true unless you compile without -g. If you do copile with -g gdb is actually able to tell you the full stack trace - so you can see the right line within if() statement which caused the trouble.
Actually it depends on the quality of the debuginfo provided by the compiler. Historically it has not been able todo this correctly. I am not clear on what version of gcc fixed this, but I've certainly hit the problem many times in the past. Daniel -- |: http://berrange.com -o- http://www.flickr.com/photos/dberrange/ :| |: http://libvirt.org -o- http://virt-manager.org :| |: http://autobuild.org -o- http://search.cpan.org/~danberr/ :| |: http://entangle-photo.org -o- http://live.gnome.org/gtk-vnc :|

On 09.05.2013 12:49, Daniel P. Berrange wrote:
On Thu, May 09, 2013 at 12:31:14PM +0200, Michal Privoznik wrote:
On 09.05.2013 10:15, Daniel P. Berrange wrote:
On Wed, May 08, 2013 at 04:01:04PM -0600, Eric Blake wrote:
On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/lxc/lxc_cgroup.c | 3 +-- src/lxc/lxc_conf.c | 36 +++++++++++++++++------------------- src/lxc/lxc_container.c | 18 ++++-------------- src/lxc/lxc_controller.c | 20 ++++++++------------ src/lxc/lxc_driver.c | 9 ++------- src/lxc/lxc_process.c | 7 ++++--- 6 files changed, 36 insertions(+), 57 deletions(-)
diff --git a/src/lxc/lxc_cgroup.c b/src/lxc/lxc_cgroup.c @@ -161,18 +161,18 @@ int lxcLoadDriverConfig(virLXCDriverPtr driver) driver->securityRequireConfined = false;
/* Set the container configuration directory */ - if ((driver->configDir = strdup(LXC_CONFIG_DIR)) == NULL) - goto no_memory; - if ((driver->stateDir = strdup(LXC_STATE_DIR)) == NULL) - goto no_memory; - if ((driver->logDir = strdup(LXC_LOG_DIR)) == NULL) - goto no_memory; - if ((driver->autostartDir = strdup(LXC_AUTOSTART_DIR)) == NULL) - goto no_memory; + if (VIR_STRDUP(driver->configDir, LXC_CONFIG_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->stateDir, LXC_STATE_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->logDir, LXC_LOG_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->autostartDir, LXC_AUTOSTART_DIR) < 0) + goto error;
You could chain these into one 'if', if desired.
I generally prefer it if we do not merge separate statements like these into one if, because it makes debugging harder. eg if any of these were to generate a SEGV, then GDB can only tell you the line of the start of the if(). Having them separate it can tell you exactly which is at fault.
Daniel
Not true unless you compile without -g. If you do copile with -g gdb is actually able to tell you the full stack trace - so you can see the right line within if() statement which caused the trouble.
Actually it depends on the quality of the debuginfo provided by the compiler. Historically it has not been able todo this correctly. I am not clear on what version of gcc fixed this, but I've certainly hit the problem many times in the past.
Daniel
Aaah. Okay then - I've tested on the latest gcc-4.8.0 and gdb-7.6 which could explain why I don't see the problem. So I will not join the if()'s for now. Neither split those already joined. :) I'll just leave everything as is. Michal

On 05/09/2013 12:53 PM, Michal Privoznik wrote:
On 09.05.2013 12:49, Daniel P. Berrange wrote:
On Thu, May 09, 2013 at 12:31:14PM +0200, Michal Privoznik wrote:
On 09.05.2013 10:15, Daniel P. Berrange wrote:
On Wed, May 08, 2013 at 04:01:04PM -0600, Eric Blake wrote:
On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/lxc/lxc_cgroup.c | 3 +-- src/lxc/lxc_conf.c | 36 +++++++++++++++++------------------- src/lxc/lxc_container.c | 18 ++++-------------- src/lxc/lxc_controller.c | 20 ++++++++------------ src/lxc/lxc_driver.c | 9 ++------- src/lxc/lxc_process.c | 7 ++++--- 6 files changed, 36 insertions(+), 57 deletions(-)
diff --git a/src/lxc/lxc_cgroup.c b/src/lxc/lxc_cgroup.c @@ -161,18 +161,18 @@ int lxcLoadDriverConfig(virLXCDriverPtr driver) driver->securityRequireConfined = false;
/* Set the container configuration directory */ - if ((driver->configDir = strdup(LXC_CONFIG_DIR)) == NULL) - goto no_memory; - if ((driver->stateDir = strdup(LXC_STATE_DIR)) == NULL) - goto no_memory; - if ((driver->logDir = strdup(LXC_LOG_DIR)) == NULL) - goto no_memory; - if ((driver->autostartDir = strdup(LXC_AUTOSTART_DIR)) == NULL) - goto no_memory; + if (VIR_STRDUP(driver->configDir, LXC_CONFIG_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->stateDir, LXC_STATE_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->logDir, LXC_LOG_DIR) < 0) + goto error; + if (VIR_STRDUP(driver->autostartDir, LXC_AUTOSTART_DIR) < 0) + goto error;
You could chain these into one 'if', if desired.
I generally prefer it if we do not merge separate statements like these into one if, because it makes debugging harder. eg if any of these were to generate a SEGV, then GDB can only tell you the line of the start of the if(). Having them separate it can tell you exactly which is at fault.
Daniel
Not true unless you compile without -g. If you do copile with -g gdb is actually able to tell you the full stack trace - so you can see the right line within if() statement which caused the trouble.
Actually it depends on the quality of the debuginfo provided by the compiler. Historically it has not been able todo this correctly. I am not clear on what version of gcc fixed this, but I've certainly hit the problem many times in the past.
Daniel
Aaah. Okay then - I've tested on the latest gcc-4.8.0 and gdb-7.6 which could explain why I don't see the problem. So I will not join the if()'s for now. Neither split those already joined. :) I'll just leave everything as is.
Michal
When using 4.8.0, did it make the use of default '-ftrack-macro-expansion=2'? I wonder if it also expands the macro in the debuginfo. Martin

--- src/network/bridge_driver.c | 34 +++++++++++----------------------- 1 file changed, 11 insertions(+), 23 deletions(-) diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c index e828997..fb01ebf 100644 --- a/src/network/bridge_driver.c +++ b/src/network/bridge_driver.c @@ -378,8 +378,8 @@ networkStateInitialize(bool privileged, "%s/log/libvirt/qemu", LOCALSTATEDIR) == -1) goto out_of_memory; - if ((base = strdup(SYSCONFDIR "/libvirt")) == NULL) - goto out_of_memory; + if (VIR_STRDUP(base, SYSCONFDIR "/libvirt") < 0) + goto error; } else { char *userdir = virGetUserCacheDirectory(); @@ -2824,9 +2824,8 @@ static int networkConnectListNetworks(virConnectPtr conn, char **const names, in for (i = 0 ; i < driver->networks.count && got < nnames ; i++) { virNetworkObjLock(driver->networks.objs[i]); if (virNetworkObjIsActive(driver->networks.objs[i])) { - if (!(names[got] = strdup(driver->networks.objs[i]->def->name))) { + if (VIR_STRDUP(names[got], driver->networks.objs[i]->def->name) < 0) { virNetworkObjUnlock(driver->networks.objs[i]); - virReportOOMError(); goto cleanup; } got++; @@ -2868,9 +2867,8 @@ static int networkConnectListDefinedNetworks(virConnectPtr conn, char **const na for (i = 0 ; i < driver->networks.count && got < nnames ; i++) { virNetworkObjLock(driver->networks.objs[i]); if (!virNetworkObjIsActive(driver->networks.objs[i])) { - if (!(names[got] = strdup(driver->networks.objs[i]->def->name))) { + if (VIR_STRDUP(names[got], driver->networks.objs[i]->def->name) < 0) { virNetworkObjUnlock(driver->networks.objs[i]); - virReportOOMError(); goto cleanup; } got++; @@ -3499,9 +3497,7 @@ static char *networkGetBridgeName(virNetworkPtr net) { goto cleanup; } - bridge = strdup(network->def->bridge); - if (!bridge) - virReportOOMError(); + ignore_value(VIR_STRDUP(bridge, network->def->bridge)); cleanup: if (network) @@ -3689,13 +3685,9 @@ networkCreateInterfacePool(virNetworkDefPtr netdef) { (netdef->forward.type == VIR_NETWORK_FORWARD_PASSTHROUGH)) { netdef->forward.ifs[ii].type = VIR_NETWORK_FORWARD_HOSTDEV_DEVICE_NETDEV; if (vfname[ii]) { - netdef->forward.ifs[ii].device.dev = strdup(vfname[ii]); - if (!netdef->forward.ifs[ii].device.dev) { - virReportOOMError(); + if (VIR_STRDUP(netdef->forward.ifs[ii].device.dev, vfname[ii]) < 0) goto finish; - } - } - else { + } else { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Direct mode types require interface names")); goto finish; @@ -3838,11 +3830,9 @@ networkAllocateActualDevice(virDomainNetDefPtr iface) } iface->data.network.actual->type = actualType = VIR_DOMAIN_NET_TYPE_BRIDGE; - iface->data.network.actual->data.bridge.brname = strdup(netdef->bridge); - if (!iface->data.network.actual->data.bridge.brname) { - virReportOOMError(); + if (VIR_STRDUP(iface->data.network.actual->data.bridge.brname, + netdef->bridge) < 0) goto error; - } /* merge virtualports from interface, network, and portgroup to * arrive at actual virtualport to use @@ -4059,11 +4049,9 @@ networkAllocateActualDevice(virDomainNetDefPtr iface) netdef->name); goto error; } - iface->data.network.actual->data.direct.linkdev = strdup(dev->device.dev); - if (!iface->data.network.actual->data.direct.linkdev) { - virReportOOMError(); + if (VIR_STRDUP(iface->data.network.actual->data.direct.linkdev, + dev->device.dev) < 0) goto error; - } } } -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/network/bridge_driver.c | 34 +++++++++++----------------------- 1 file changed, 11 insertions(+), 23 deletions(-)
ACK. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/node_device/node_device_driver.c | 33 ++++-------- src/node_device/node_device_hal.c | 13 ++--- src/node_device/node_device_udev.c | 99 ++++++++++-------------------------- 3 files changed, 46 insertions(+), 99 deletions(-) diff --git a/src/node_device/node_device_driver.c b/src/node_device/node_device_driver.c index 05dc49c..8a84094 100644 --- a/src/node_device/node_device_driver.c +++ b/src/node_device/node_device_driver.c @@ -89,13 +89,8 @@ static int update_driver_name(virNodeDeviceObjPtr dev) } p = strrchr(devpath, '/'); - if (p) { - dev->def->driver = strdup(p+1); - if (!dev->def->driver) { - virReportOOMError(); - goto cleanup; - } - } + if (p && VIR_STRDUP(dev->def->driver, p+1) < 0) + goto cleanup; ret = 0; cleanup: @@ -162,9 +157,8 @@ nodeListDevices(virConnectPtr conn, virNodeDeviceObjLock(driver->devs.objs[i]); if (cap == NULL || virNodeDeviceHasCap(driver->devs.objs[i], cap)) { - if ((names[ndevs++] = strdup(driver->devs.objs[i]->def->name)) == NULL) { + if (VIR_STRDUP(names[ndevs++], driver->devs.objs[i]->def->name) < 0) { virNodeDeviceObjUnlock(driver->devs.objs[i]); - virReportOOMError(); goto failure; } } @@ -322,9 +316,8 @@ nodeDeviceGetParent(virNodeDevicePtr dev) } if (obj->def->parent) { - ret = strdup(obj->def->parent); - if (!ret) - virReportOOMError(); + if (VIR_STRDUP(ret, obj->def->parent) < 0) + goto cleanup; } else { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("no parent for this device")); @@ -389,11 +382,8 @@ nodeDeviceListCaps(virNodeDevicePtr dev, char **const names, int maxnames) } for (caps = obj->def->caps; caps && ncaps < maxnames; caps = caps->next) { - names[ncaps] = strdup(virNodeDevCapTypeToString(caps->type)); - if (names[ncaps++] == NULL) { - virReportOOMError(); + if (VIR_STRDUP(names[ncaps], virNodeDevCapTypeToString(caps->type)) < 0) goto cleanup; - } } ret = ncaps; @@ -555,19 +545,18 @@ nodeDeviceDestroy(virNodeDevicePtr dev) goto out; } - parent_name = strdup(obj->def->parent); /* virNodeDeviceGetParentHost will cause the device object's lock to be * taken, so we have to dup the parent's name and drop the lock * before calling it. We don't need the reference to the object * any more once we have the parent's name. */ - virNodeDeviceObjUnlock(obj); - obj = NULL; - - if (parent_name == NULL) { - virReportOOMError(); + if (VIR_STRDUP(parent_name, obj->def->parent) < 0) { + virNodeDeviceObjUnlock(obj); + obj = NULL; goto out; } + virNodeDeviceObjUnlock(obj); + obj = NULL; if (virNodeDeviceGetParentHost(&driver->devs, dev->name, diff --git a/src/node_device/node_device_hal.c b/src/node_device/node_device_hal.c index 8c77cc3..1a3b507 100644 --- a/src/node_device/node_device_hal.c +++ b/src/node_device/node_device_hal.c @@ -446,10 +446,10 @@ static void dev_create(const char *udi) virNodeDeviceDefPtr def = NULL; const char *name = hal_name(udi); int rv; - char *privData = strdup(udi); + char *privData; char *devicePath = NULL; - if (!privData) + if (VIR_STRDUP(privData, udi) < 0) return; nodeDeviceLock(driverState); @@ -458,14 +458,15 @@ static void dev_create(const char *udi) if (VIR_ALLOC(def) < 0) goto failure; - if ((def->name = strdup(name)) == NULL) + if (VIR_STRDUP(def->name, name) < 0) goto failure; if (get_str_prop(ctx, udi, "info.parent", &parent_key) == 0) { - def->parent = strdup(hal_name(parent_key)); - VIR_FREE(parent_key); - if (def->parent == NULL) + if (VIR_STRDUP(def->parent, hal_name(parent_key)) < 0) { + VIR_FREE(parent_key); goto failure; + } + VIR_FREE(parent_key); } rv = gather_capabilities(ctx, udi, &def->caps); diff --git a/src/node_device/node_device_udev.c b/src/node_device/node_device_udev.c index c3c97d7..7d7718e 100644 --- a/src/node_device/node_device_udev.c +++ b/src/node_device/node_device_udev.c @@ -125,12 +125,10 @@ static int udevGetDeviceProperty(struct udev_device *udev_device, /* If this allocation is changed, the comment at the beginning * of the function must also be changed. */ - *property_value = strdup(udev_value); - if (*property_value == NULL) { + if (VIR_STRDUP(*property_value, udev_value) < 0) { VIR_ERROR(_("Failed to allocate memory for property value for " "property key '%s' on device with sysname '%s'"), property_key, udev_device_get_sysname(udev_device)); - virReportOOMError(); ret = PROPERTY_ERROR; goto out; } @@ -214,12 +212,10 @@ static int udevGetDeviceSysfsAttr(struct udev_device *udev_device, /* If this allocation is changed, the comment at the beginning * of the function must also be changed. */ - *attr_value = strdup(udev_value); - if (*attr_value == NULL) { + if (VIR_STRDUP(*attr_value, udev_value) < 0) { VIR_ERROR(_("Failed to allocate memory for sysfs attribute value for " "sysfs attribute '%s' on device with sysname '%s'"), attr_name, udev_device_get_sysname(udev_device)); - virReportOOMError(); ret = PROPERTY_ERROR; goto out; } @@ -387,21 +383,9 @@ static int udevTranslatePCIIds(unsigned int vendor, NULL, NULL); - if (vendor_name != NULL) { - *vendor_string = strdup(vendor_name); - if (*vendor_string == NULL) { - virReportOOMError(); - goto out; - } - } - - if (device_name != NULL) { - *product_string = strdup(device_name); - if (*product_string == NULL) { - virReportOOMError(); - goto out; - } - } + if ((vendor_name && VIR_STRDUP(*vendor_string, vendor_name) < 0) || + (device_name && VIR_STRDUP(*product_string, device_name) < 0)) + goto out; ret = 0; @@ -691,11 +675,8 @@ static int udevProcessSCSITarget(struct udev_device *device ATTRIBUTE_UNUSED, sysname = udev_device_get_sysname(device); - data->scsi_target.name = strdup(sysname); - if (data->scsi_target.name == NULL) { - virReportOOMError(); + if (VIR_STRDUP(data->scsi_target.name, sysname) < 0) goto out; - } if (udevGenerateDeviceName(device, def, NULL) != 0) { goto out; @@ -718,34 +699,34 @@ static int udevGetSCSIType(virNodeDeviceDefPtr def ATTRIBUTE_UNUSED, switch (type) { case TYPE_DISK: - *typestring = strdup("disk"); + ignore_value(VIR_STRDUP(*typestring, "disk")); break; case TYPE_TAPE: - *typestring = strdup("tape"); + ignore_value(VIR_STRDUP(*typestring, "tape")); break; case TYPE_PROCESSOR: - *typestring = strdup("processor"); + ignore_value(VIR_STRDUP(*typestring, "processor")); break; case TYPE_WORM: - *typestring = strdup("worm"); + ignore_value(VIR_STRDUP(*typestring, "worm")); break; case TYPE_ROM: - *typestring = strdup("cdrom"); + ignore_value(VIR_STRDUP(*typestring, "cdrom")); break; case TYPE_SCANNER: - *typestring = strdup("scanner"); + ignore_value(VIR_STRDUP(*typestring, "scanner")); break; case TYPE_MOD: - *typestring = strdup("mod"); + ignore_value(VIR_STRDUP(*typestring, "mod")); break; case TYPE_MEDIUM_CHANGER: - *typestring = strdup("changer"); + ignore_value(VIR_STRDUP(*typestring, "changer")); break; case TYPE_ENCLOSURE: - *typestring = strdup("enclosure"); + ignore_value(VIR_STRDUP(*typestring, "enclosure")); break; case TYPE_RAID: - *typestring = strdup("raid"); + ignore_value(VIR_STRDUP(*typestring, "raid")); break; case TYPE_NO_LUN: default: @@ -756,7 +737,6 @@ static int udevGetSCSIType(virNodeDeviceDefPtr def ATTRIBUTE_UNUSED, if (*typestring == NULL) { if (foundtype == 1) { ret = -1; - virReportOOMError(); } else { VIR_DEBUG("Failed to find SCSI device type %d for %s", type, def->sysfs_path); @@ -917,11 +897,8 @@ static int udevProcessCDROM(struct udev_device *device, * change it to cdrom to preserve compatibility with earlier * versions of libvirt. */ VIR_FREE(def->caps->data.storage.drive_type); - def->caps->data.storage.drive_type = strdup("cdrom"); - if (def->caps->data.storage.drive_type == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->caps->data.storage.drive_type, "cdrom") < 0) goto out; - } if ((udevGetIntProperty(device, "ID_CDROM_MEDIA", &tmp_int, 0) == PROPERTY_FOUND)) @@ -996,10 +973,7 @@ static int udevKludgeStorageType(virNodeDeviceDefPtr def) if (STRPREFIX(def->caps->data.storage.block, "/dev/vd")) { /* virtio disk */ - def->caps->data.storage.drive_type = strdup("disk"); - if (def->caps->data.storage.drive_type != NULL) { - ret = 0; - } + ret = VIR_STRDUP(def->caps->data.storage.drive_type, "disk"); } if (ret != 0) { @@ -1043,7 +1017,7 @@ static int udevProcessStorage(struct udev_device *device, VIR_DEBUG("No devnode for '%s'", udev_device_get_devpath(device)); goto out; } - data->storage.block = strdup(devnode); + ignore_value(VIR_STRDUP(data->storage.block, devnode)); if (udevGetStringProperty(device, "ID_BUS", @@ -1083,15 +1057,13 @@ static int udevProcessStorage(struct udev_device *device, &tmp_int, 0) == PROPERTY_FOUND) && (tmp_int == 1)) { - data->storage.drive_type = strdup("floppy"); - if (!data->storage.drive_type) + if (VIR_STRDUP(data->storage.drive_type, "floppy") < 0) goto out; } else if ((udevGetIntProperty(device, "ID_DRIVE_FLASH_SD", &tmp_int, 0) == PROPERTY_FOUND) && (tmp_int == 1)) { - data->storage.drive_type = strdup("sd"); - if (!data->storage.drive_type) + if (VIR_STRDUP(data->storage.drive_type, "sd") < 0) goto out; } else { @@ -1294,32 +1266,20 @@ static int udevSetParent(struct udev_device *device, dev = virNodeDeviceFindBySysfsPath(&driverState->devs, parent_sysfs_path); if (dev != NULL) { - def->parent = strdup(dev->def->name); - virNodeDeviceObjUnlock(dev); - - if (def->parent == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->parent, dev->def->name) < 0) { goto out; + virNodeDeviceObjUnlock(dev); } + virNodeDeviceObjUnlock(dev); - def->parent_sysfs_path = strdup(parent_sysfs_path); - if (def->parent_sysfs_path == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->parent_sysfs_path, parent_sysfs_path) < 0) goto out; - } - } } while (def->parent == NULL && parent_device != NULL); - if (def->parent == NULL) { - def->parent = strdup("computer"); - } - - if (def->parent == NULL) { - virReportOOMError(); + if (!def->parent && VIR_STRDUP(def->parent, "computer") < 0) goto out; - } ret = 0; @@ -1339,7 +1299,7 @@ static int udevAddOneDevice(struct udev_device *device) goto out; } - def->sysfs_path = strdup(udev_device_get_syspath(device)); + ignore_value(VIR_STRDUP(def->sysfs_path, udev_device_get_syspath(device))); if (udevGetStringProperty(device, "DRIVER", &def->driver) == PROPERTY_ERROR) { @@ -1617,11 +1577,8 @@ static int udevSetupSystemDev(void) goto out; } - def->name = strdup("computer"); - if (def->name == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->name, "computer") < 0) goto out; - } if (VIR_ALLOC(def->caps) != 0) { virReportOOMError(); -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/node_device/node_device_driver.c | 33 ++++-------- src/node_device/node_device_hal.c | 13 ++--- src/node_device/node_device_udev.c | 99 ++++++++++-------------------------- 3 files changed, 46 insertions(+), 99 deletions(-)
diff --git a/src/node_device/node_device_driver.c b/src/node_device/node_device_driver.c index 05dc49c..8a84094 100644 --- a/src/node_device/node_device_driver.c +++ b/src/node_device/node_device_driver.c @@ -89,13 +89,8 @@ static int update_driver_name(virNodeDeviceObjPtr dev) }
p = strrchr(devpath, '/'); - if (p) { - dev->def->driver = strdup(p+1); - if (!dev->def->driver) { - virReportOOMError(); - goto cleanup; - } - } + if (p && VIR_STRDUP(dev->def->driver, p+1) < 0)
spaces around + while you are touching this
+++ b/src/node_device/node_device_hal.c @@ -446,10 +446,10 @@ static void dev_create(const char *udi) virNodeDeviceDefPtr def = NULL; const char *name = hal_name(udi); int rv; - char *privData = strdup(udi); + char *privData; char *devicePath = NULL;
- if (!privData) + if (VIR_STRDUP(privData, udi) < 0) return;
silent->noisy in a void function, but the rest of the function is just using VIR_DEBUG on failure, so I think this is an improvement. Not to mention that HAL code is used less and less these days.
+++ b/src/node_device/node_device_udev.c @@ -387,21 +383,9 @@ static int udevTranslatePCIIds(unsigned int vendor, NULL, NULL);
- if (vendor_name != NULL) { - *vendor_string = strdup(vendor_name); - if (*vendor_string == NULL) { - virReportOOMError(); - goto out; - } - } - - if (device_name != NULL) { - *product_string = strdup(device_name); - if (*product_string == NULL) { - virReportOOMError(); - goto out; - } - } + if ((vendor_name && VIR_STRDUP(*vendor_string, vendor_name) < 0) || + (device_name && VIR_STRDUP(*product_string, device_name) < 0)) + goto out;
Can be simplified now that we allow NULL source.
@@ -718,34 +699,34 @@ static int udevGetSCSIType(virNodeDeviceDefPtr def ATTRIBUTE_UNUSED,
switch (type) { case TYPE_DISK: - *typestring = strdup("disk"); + ignore_value(VIR_STRDUP(*typestring, "disk")); break; case TYPE_TAPE: - *typestring = strdup("tape"); + ignore_value(VIR_STRDUP(*typestring, "tape")); break;
Another situation where you could reduce the number of ignore_value() by assigning to a const char*, then saving the dup until after the switch finishes - although such a rework would be no real semantic change. For that matter, this whole switch statement could be rewritten with VIR_ENUM_* magic, but that would be a separate cleanup.
@@ -996,10 +973,7 @@ static int udevKludgeStorageType(virNodeDeviceDefPtr def)
if (STRPREFIX(def->caps->data.storage.block, "/dev/vd")) { /* virtio disk */ - def->caps->data.storage.drive_type = strdup("disk"); - if (def->caps->data.storage.drive_type != NULL) { - ret = 0; - } + ret = VIR_STRDUP(def->caps->data.storage.drive_type, "disk");
silent->noisy, but I think it's an improvement.
@@ -1043,7 +1017,7 @@ static int udevProcessStorage(struct udev_device *device, VIR_DEBUG("No devnode for '%s'", udev_device_get_devpath(device)); goto out; } - data->storage.block = strdup(devnode); + ignore_value(VIR_STRDUP(data->storage.block, devnode));
Pre-existing bug - udevKludgeStorageType() dereferences data->storage.block, and expects it to be non-null. Please touch this up to 'goto out' rather than silently pushing on in spite of allocation failure.
@@ -1294,32 +1266,20 @@ static int udevSetParent(struct udev_device *device, dev = virNodeDeviceFindBySysfsPath(&driverState->devs, parent_sysfs_path); if (dev != NULL) { - def->parent = strdup(dev->def->name); - virNodeDeviceObjUnlock(dev); - - if (def->parent == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->parent, dev->def->name) < 0) { goto out; + virNodeDeviceObjUnlock(dev);
Umm, that order won't work. Swap those two lines.
@@ -1339,7 +1299,7 @@ static int udevAddOneDevice(struct udev_device *device) goto out; }
- def->sysfs_path = strdup(udev_device_get_syspath(device)); + ignore_value(VIR_STRDUP(def->sysfs_path, udev_device_get_syspath(device)));
Another pre-existing bug where we should 'goto out' instead of leaving sysfs_path NULL, since several places in the rest of the file blindly dereference the field. For that matter, the 'out' label itself is one such place - fix that VIR_DEBUG to use NULLSTR(def->sysfs_path). ACK with the bugs fixed. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/interface/interface_backend_udev.c | 36 +++++++++------------------------- 1 file changed, 9 insertions(+), 27 deletions(-) diff --git a/src/interface/interface_backend_udev.c b/src/interface/interface_backend_udev.c index 7daad16..7f01fce 100644 --- a/src/interface/interface_backend_udev.c +++ b/src/interface/interface_backend_udev.c @@ -227,14 +227,11 @@ udevListInterfacesByStatus(virConnectPtr conn, path = udev_list_entry_get_name(dev_entry); dev = udev_device_new_from_syspath(udev, path); - names[count] = strdup(udev_device_get_sysname(dev)); - udev_device_unref(dev); - - /* If strdup() failed, we are out of memory */ - if (!names[count]) { - virReportOOMError(); + if (VIR_STRDUP(names[count], udev_device_get_sysname(dev)) < 0) { + udev_device_unref(dev); goto err; } + udev_device_unref(dev); count++; } @@ -751,11 +748,8 @@ udevGetIfaceDefBond(struct udev *udev, _("Could not retrieve 'bonding/arp_ip_target' for '%s'"), name); goto cleanup; } - ifacedef->data.bond.target = strdup(tmp_str); - if (!ifacedef->data.bond.target) { - virReportOOMError(); + if (VIR_STRDUP(ifacedef->data.bond.target, tmp_str) < 0) goto cleanup; - } /* Slaves of the bond */ /* Get each slave in the bond */ @@ -839,11 +833,8 @@ udevGetIfaceDefBridge(struct udev *udev, goto error; } - ifacedef->data.bridge.delay = strdup(tmp_str); - if (!ifacedef->data.bridge.delay) { - virReportOOMError(); + if (VIR_STRDUP(ifacedef->data.bridge.delay, tmp_str) < 0) goto error; - } /* Retrieve Spanning Tree State. Valid values = -1, 0, 1 */ tmp_str = udev_device_get_sysattr_value(dev, "bridge/stp_state"); @@ -938,11 +929,8 @@ udevGetIfaceDefVlan(struct udev *udev ATTRIBUTE_UNUSED, char *vid; char *vlan_parent_dev = NULL; - vlan_parent_dev = strdup(name); - if (!vlan_parent_dev) { - virReportOOMError(); + if (VIR_STRDUP(vlan_parent_dev, name) < 0) goto cleanup; - } /* Find the DEVICE.VID again */ vid = strrchr(vlan_parent_dev, '.'); @@ -987,12 +975,8 @@ udevGetIfaceDef(struct udev *udev, const char *name) /* Clear our structure and set safe defaults */ ifacedef->startmode = VIR_INTERFACE_START_UNSPECIFIED; - ifacedef->name = strdup(name); - - if (!ifacedef->name) { - virReportOOMError(); + if (VIR_STRDUP(ifacedef->name, name) < 0) goto cleanup; - } /* Lookup the device we've been asked about */ dev = udev_device_new_from_subsystem_sysname(udev, "net", name); @@ -1003,11 +987,9 @@ udevGetIfaceDef(struct udev *udev, const char *name) } /* MAC address */ - ifacedef->mac = strdup(udev_device_get_sysattr_value(dev, "address")); - if (!ifacedef->mac) { - virReportOOMError(); + if (VIR_STRDUP(ifacedef->mac, + udev_device_get_sysattr_value(dev, "address")) < 0) goto cleanup; - } /* MTU */ mtu_str = udev_device_get_sysattr_value(dev, "mtu"); -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/interface/interface_backend_udev.c | 36 +++++++++------------------------- 1 file changed, 9 insertions(+), 27 deletions(-)
ACK. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/nwfilter/nwfilter_dhcpsnoop.c | 22 +++++++++++----------- src/nwfilter/nwfilter_driver.c | 7 +++---- src/nwfilter/nwfilter_ebiptables_driver.c | 2 +- src/nwfilter/nwfilter_gentech_driver.c | 5 ++--- src/nwfilter/nwfilter_learnipaddr.c | 5 +---- 5 files changed, 18 insertions(+), 23 deletions(-) diff --git a/src/nwfilter/nwfilter_dhcpsnoop.c b/src/nwfilter/nwfilter_dhcpsnoop.c index 50042df..a3e05a1 100644 --- a/src/nwfilter/nwfilter_dhcpsnoop.c +++ b/src/nwfilter/nwfilter_dhcpsnoop.c @@ -133,11 +133,11 @@ struct _virNWFilterSnoopReq { virNWFilterTechDriverPtr techdriver; char *ifname; int ifindex; - const char *linkdev; + char *linkdev; enum virDomainNetType nettype; char ifkey[VIR_IFKEY_LEN]; virMacAddr macaddr; - const char *filtername; + char *filtername; virNWFilterHashTablePtr vars; virNWFilterDriverStatePtr driver; /* start and end of lease list, ordered by lease time */ @@ -1110,10 +1110,8 @@ virNWFilterSnoopDHCPOpen(const char *ifname, virMacAddr *mac, * generate much more traffic than if we filtered by VM and * braodcast MAC as well */ - if (!(ext_filter = strdup(filter))) { - virReportOOMError(); + if (VIR_STRDUP(ext_filter, filter) < 0) return NULL; - } } handle = pcap_create(ifname, pcap_errbuf); @@ -1408,7 +1406,7 @@ virNWFilterDHCPSnoopThread(void *req0) fds[i].fd = pcap_fileno(pcapConf[i].handle); } tmp = virNetDevGetIndex(req->ifname, &ifindex); - threadkey = strdup(req->threadkey); + ignore_value(VIR_STRDUP(threadkey, req->threadkey)); worker = virThreadPoolNew(1, 1, 0, virNWFilterDHCPDecodeWorker, req); @@ -1631,15 +1629,17 @@ virNWFilterDHCPSnoopReq(virNWFilterTechDriverPtr techdriver, req->driver = driver; req->techdriver = techdriver; tmp = virNetDevGetIndex(ifname, &req->ifindex); - req->linkdev = linkdev ? strdup(linkdev) : NULL; req->nettype = nettype; - req->ifname = strdup(ifname); virMacAddrSet(&req->macaddr, macaddr); - req->filtername = strdup(filtername); req->vars = virNWFilterHashTableCreate(0); + req->linkdev = NULL; + + if (VIR_STRDUP(req->ifname, ifname) < 0 || + VIR_STRDUP(req->filtername, filtername) < 0 || + (linkdev && VIR_STRDUP(req->linkdev, linkdev) < 0)) + goto exit_snoopreqput; - if (!req->ifname || !req->filtername || !req->vars || tmp < 0 || - (linkdev != NULL && req->linkdev == NULL)) { + if (!req->vars || tmp < 0) { virReportOOMError(); goto exit_snoopreqput; } diff --git a/src/nwfilter/nwfilter_driver.c b/src/nwfilter/nwfilter_driver.c index 7eec3de..64ea251 100644 --- a/src/nwfilter/nwfilter_driver.c +++ b/src/nwfilter/nwfilter_driver.c @@ -221,8 +221,8 @@ nwfilterStateInitialize(bool privileged, goto error; } - if ((base = strdup(SYSCONFDIR "/libvirt")) == NULL) - goto out_of_memory; + if (VIR_STRDUP(base, SYSCONFDIR "/libvirt") < 0) + goto error; if (virAsprintf(&driverState->configDir, "%s/nwfilter", base) == -1) @@ -454,9 +454,8 @@ nwfilterConnectListNWFilters(virConnectPtr conn, nwfilterDriverLock(driver); for (i = 0 ; i < driver->nwfilters.count && got < nnames ; i++) { virNWFilterObjLock(driver->nwfilters.objs[i]); - if (!(names[got] = strdup(driver->nwfilters.objs[i]->def->name))) { + if (VIR_STRDUP(names[got], driver->nwfilters.objs[i]->def->name) < 0) { virNWFilterObjUnlock(driver->nwfilters.objs[i]); - virReportOOMError(); goto cleanup; } got++; diff --git a/src/nwfilter/nwfilter_ebiptables_driver.c b/src/nwfilter/nwfilter_ebiptables_driver.c index ac94355..b772847 100644 --- a/src/nwfilter/nwfilter_ebiptables_driver.c +++ b/src/nwfilter/nwfilter_ebiptables_driver.c @@ -2982,7 +2982,7 @@ ebtablesCreateTmpSubChain(ebiptablesRuleInstPtr *inst, switch (protoidx) { case L2_PROTO_MAC_IDX: - protostr = strdup(""); + ignore_value(VIR_STRDUP_QUIET(protostr, "")); break; case L2_PROTO_STP_IDX: ignore_value(virAsprintf(&protostr, "-d " NWFILTER_MAC_BGA " ")); diff --git a/src/nwfilter/nwfilter_gentech_driver.c b/src/nwfilter/nwfilter_gentech_driver.c index 958f47a..7bca2f4 100644 --- a/src/nwfilter/nwfilter_gentech_driver.c +++ b/src/nwfilter/nwfilter_gentech_driver.c @@ -37,6 +37,7 @@ #include "nwfilter_learnipaddr.h" #include "virnetdev.h" #include "datatypes.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_NWFILTER @@ -866,9 +867,7 @@ __virNWFilterInstantiateFilter(const unsigned char *vmuuid, } virMacAddrFormat(macaddr, vmmacaddr); - str_macaddr = strdup(vmmacaddr); - if (!str_macaddr) { - virReportOOMError(); + if (VIR_STRDUP(str_macaddr, vmmacaddr) < 0) { rc = -1; goto err_exit; } diff --git a/src/nwfilter/nwfilter_learnipaddr.c b/src/nwfilter/nwfilter_learnipaddr.c index 14fd32c..f50a246 100644 --- a/src/nwfilter/nwfilter_learnipaddr.c +++ b/src/nwfilter/nwfilter_learnipaddr.c @@ -705,11 +705,8 @@ virNWFilterLearnIPAddress(virNWFilterTechDriverPtr techdriver, if (virNWFilterHashTablePutAll(filterparams, ht) < 0) goto err_free_ht; - req->filtername = strdup(filtername); - if (req->filtername == NULL) { - virReportOOMError(); + if (VIR_STRDUP(req->filtername, filtername) < 0) goto err_free_ht; - } if (virStrcpyStatic(req->ifname, ifname) == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/nwfilter/nwfilter_dhcpsnoop.c | 22 +++++++++++----------- src/nwfilter/nwfilter_driver.c | 7 +++---- src/nwfilter/nwfilter_ebiptables_driver.c | 2 +- src/nwfilter/nwfilter_gentech_driver.c | 5 ++--- src/nwfilter/nwfilter_learnipaddr.c | 5 +---- 5 files changed, 18 insertions(+), 23 deletions(-)
diff --git a/src/nwfilter/nwfilter_dhcpsnoop.c b/src/nwfilter/nwfilter_dhcpsnoop.c @@ -1631,15 +1629,17 @@ virNWFilterDHCPSnoopReq(virNWFilterTechDriverPtr techdriver, req->driver = driver; req->techdriver = techdriver; tmp = virNetDevGetIndex(ifname, &req->ifindex); - req->linkdev = linkdev ? strdup(linkdev) : NULL; req->nettype = nettype; - req->ifname = strdup(ifname); virMacAddrSet(&req->macaddr, macaddr); - req->filtername = strdup(filtername); req->vars = virNWFilterHashTableCreate(0); + req->linkdev = NULL; + + if (VIR_STRDUP(req->ifname, ifname) < 0 || + VIR_STRDUP(req->filtername, filtername) < 0 || + (linkdev && VIR_STRDUP(req->linkdev, linkdev) < 0)) + goto exit_snoopreqput;
Can be simplified by passing NULL source.
+++ b/src/nwfilter/nwfilter_ebiptables_driver.c @@ -2982,7 +2982,7 @@ ebtablesCreateTmpSubChain(ebiptablesRuleInstPtr *inst,
switch (protoidx) { case L2_PROTO_MAC_IDX: - protostr = strdup(""); + ignore_value(VIR_STRDUP_QUIET(protostr, ""));
You could use VIR_STRDUP here; it will be a double oom report (since the code is just reporting OOM error a few lines later), but it will avoid churn when you touch this function again for the virAsprintf/oom cleanup pass. But I can also live with this patch as-is. ACK. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/openvz/openvz_conf.c | 45 ++++++++++++++++++++++----------------------- src/openvz/openvz_driver.c | 39 +++++++++++++++------------------------ 2 files changed, 37 insertions(+), 47 deletions(-) diff --git a/src/openvz/openvz_conf.c b/src/openvz/openvz_conf.c index 49fae28..1d401fc 100644 --- a/src/openvz/openvz_conf.c +++ b/src/openvz/openvz_conf.c @@ -135,12 +135,10 @@ openvzParseBarrierLimit(const char* value, { char *token; char *saveptr = NULL; - char *str = strdup(value); + char *str; - if (str == NULL) { - virReportOOMError(); + if (VIR_STRDUP(str, value) < 0) goto error; - } token = strtok_r(str, ":", &saveptr); if (token == NULL) { @@ -230,10 +228,8 @@ openvzReadNetworkConf(virDomainDefPtr def, goto no_memory; net->type = VIR_DOMAIN_NET_TYPE_ETHERNET; - net->data.ethernet.ipaddr = strdup(token); - - if (net->data.ethernet.ipaddr == NULL) - goto no_memory; + if (VIR_STRDUP(net->data.ethernet.ipaddr, token) < 0) + goto error; if (VIR_REALLOC_N(def->nets, def->nnets + 1) < 0) goto no_memory; @@ -405,7 +401,8 @@ openvzReadFSConf(virDomainDefPtr def, goto no_memory; fs->type = VIR_DOMAIN_FS_TYPE_TEMPLATE; - fs->src = strdup(temp); + if (VIR_STRDUP(fs->src, temp) < 0) + goto error; } else { /* OSTEMPLATE was not found, VE was booted from a private dir directly */ ret = openvzReadVPSConfigParam(veid, "VE_PRIVATE", &temp); @@ -423,12 +420,14 @@ openvzReadFSConf(virDomainDefPtr def, goto no_memory; fs->type = VIR_DOMAIN_FS_TYPE_MOUNT; - fs->src = openvz_replace(temp, "$VEID", veid_str); + if (!(fs->src = openvz_replace(temp, "$VEID", veid_str))) + goto no_memory; VIR_FREE(veid_str); } - fs->dst = strdup("/"); + if (VIR_STRDUP(fs->dst, "/") < 0) + goto error; param = "DISKSPACE"; ret = openvzReadVPSConfigParam(veid, param, &temp); @@ -451,9 +450,6 @@ openvzReadFSConf(virDomainDefPtr def, } } - if (fs->src == NULL || fs->dst == NULL) - goto no_memory; - if (VIR_REALLOC_N(def->fss, def->nfss + 1) < 0) goto no_memory; def->fss[def->nfss++] = fs; @@ -607,10 +603,10 @@ int openvzLoadDomains(struct openvz_driver *driver) { goto cleanup; } - if (!(def->os.type = strdup("exe"))) - goto no_memory; - if (!(def->os.init = strdup("/sbin/init"))) - goto no_memory; + if (VIR_STRDUP(def->os.type, "exe") < 0) + goto cleanup; + if (VIR_STRDUP(def->os.init, "/sbin/init") < 0) + goto cleanup; ret = openvzReadVPSConfigParam(veid, "CPUS", &temp); if (ret < 0) { @@ -800,8 +796,7 @@ openvzReadConfigParam(const char *conf_file, const char *param, char **value) saveptr = NULL; if ((token = strtok_r(sf, "\"\t\n", &saveptr)) != NULL) { VIR_FREE(*value); - *value = strdup(token); - if (*value == NULL) { + if (VIR_STRDUP(*value, token) < 0) { err = 1; break; } @@ -952,14 +947,18 @@ openvzLocateConfDir(void) { const char *conf_dir_list[] = {"/etc/vz/conf", "/usr/local/etc/conf", NULL}; int i=0; + char *ret = NULL; while (conf_dir_list[i]) { - if (!access(conf_dir_list[i], F_OK)) - return strdup(conf_dir_list[i]); + if (!access(conf_dir_list[i], F_OK)) { + ignore_value(VIR_STRDUP(ret, conf_dir_list[i])); + goto cleanup; + } i++; } - return NULL; +cleanup: + return ret; } /* Richard Steven's classic readline() function */ diff --git a/src/openvz/openvz_driver.c b/src/openvz/openvz_driver.c index e6d7146..65b1163 100644 --- a/src/openvz/openvz_driver.c +++ b/src/openvz/openvz_driver.c @@ -88,7 +88,7 @@ static void openvzDriverUnlock(struct openvz_driver *driver) struct openvz_driver ovz_driver; -static void cmdExecFree(const char *cmdExec[]) +static void cmdExecFree(char *cmdExec[]) { int i=-1; while (cmdExec[++i]) { @@ -103,13 +103,8 @@ openvzDomainDefPostParse(virDomainDefPtr def, void *opaque ATTRIBUTE_UNUSED) { /* fill the init path */ - if (STREQ(def->os.type, "exe") && !def->os.init) { - if (!(def->os.init = strdup("/sbin/init"))) { - virReportOOMError(); - return -1; - } - } - + if (STREQ(def->os.type, "exe") && !def->os.init) + return VIR_STRDUP(def->os.init, "/sbin/init"); return 0; } @@ -358,8 +353,7 @@ static char *openvzDomainGetOSType(virDomainPtr dom) goto cleanup; } - if (!(ret = strdup(vm->def->os.type))) - virReportOOMError(); + ignore_value(VIR_STRDUP(ret, vm->def->os.type)); cleanup: if (vm) @@ -772,12 +766,14 @@ openvzGenerateVethName(int veid, char *dev_name_ve) { char dev_name[32]; int ifNo = 0; + char *ret; if (sscanf(dev_name_ve, "%*[^0-9]%d", &ifNo) != 1) return NULL; if (snprintf(dev_name, sizeof(dev_name), "veth%d.%d", veid, ifNo) < 7) return NULL; - return strdup(dev_name); + ignore_value(VIR_STRDUP(ret, dev_name)); + return ret; } static char * @@ -788,7 +784,7 @@ openvzGenerateContainerVethName(int veid) /* try to get line "^NETIF=..." from config */ if (openvzReadVPSConfigParam(veid, "NETIF", &temp) <= 0) { - name = strdup("eth0"); + ignore_value(VIR_STRDUP(name, "eth0")); } else { char *saveptr = NULL; char *s; @@ -803,15 +799,12 @@ openvzGenerateContainerVethName(int veid) } /* set new name */ - ignore_value(virAsprintf(&name, "eth%d", max + 1)); + if (virAsprintf(&name, "eth%d", max + 1) < 0) + virReportOOMError(); } VIR_FREE(temp); - if (name == NULL) { - virReportOOMError(); - } - return name; } @@ -821,7 +814,7 @@ openvzDomainSetNetwork(virConnectPtr conn, const char *vpsid, virBufferPtr configBuf) { int rc = 0, narg; - const char *prog[OPENVZ_MAX_ARG]; + char *prog[OPENVZ_MAX_ARG]; char macaddr[VIR_MAC_STRING_BUFLEN]; virMacAddr host_mac; char host_macaddr[VIR_MAC_STRING_BUFLEN]; @@ -830,9 +823,9 @@ openvzDomainSetNetwork(virConnectPtr conn, const char *vpsid, #define ADD_ARG_LIT(thisarg) \ do { \ - if (narg >= OPENVZ_MAX_ARG) \ + if (narg >= OPENVZ_MAX_ARG) \ goto no_memory; \ - if ((prog[narg++] = strdup(thisarg)) == NULL) \ + if (VIR_STRDUP(prog[narg++], thisarg) < 0) \ goto no_memory; \ } while (0) @@ -928,7 +921,7 @@ openvzDomainSetNetwork(virConnectPtr conn, const char *vpsid, if (prog[0] != NULL) { ADD_ARG_LIT("--save"); - if (virRun(prog, NULL) < 0) { + if (virRun((const char **)prog, NULL) < 0) { rc = -1; goto exit; } @@ -1642,10 +1635,8 @@ static int openvzConnectListDefinedDomains(virConnectPtr conn ATTRIBUTE_UNUSED, continue; } snprintf(vpsname, sizeof(vpsname), "%d", veid); - if (!(names[got] = strdup(vpsname))) { - virReportOOMError(); + if (VIR_STRDUP(names[got], vpsname) < 0) goto out; - } got ++; } -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/openvz/openvz_conf.c | 45 ++++++++++++++++++++++----------------------- src/openvz/openvz_driver.c | 39 +++++++++++++++------------------------ 2 files changed, 37 insertions(+), 47 deletions(-)
diff --git a/src/openvz/openvz_conf.c b/src/openvz/openvz_conf.c @@ -607,10 +603,10 @@ int openvzLoadDomains(struct openvz_driver *driver) { goto cleanup; }
- if (!(def->os.type = strdup("exe"))) - goto no_memory; - if (!(def->os.init = strdup("/sbin/init"))) - goto no_memory; + if (VIR_STRDUP(def->os.type, "exe") < 0) + goto cleanup; + if (VIR_STRDUP(def->os.init, "/sbin/init") < 0) + goto cleanup;
Could chain this in one 'if'.
@@ -800,8 +796,7 @@ openvzReadConfigParam(const char *conf_file, const char *param, char **value) saveptr = NULL; if ((token = strtok_r(sf, "\"\t\n", &saveptr)) != NULL) { VIR_FREE(*value); - *value = strdup(token); - if (*value == NULL) { + if (VIR_STRDUP(*value, token) < 0) { err = 1;
silent->noisy, but leaves other error paths in this function silent (for example, if fopen fails) - so there is no way the caller could be reporting all errors correctly. This one could probably use another followup patch to clean it all up to have this function report errors on all paths, and audit callers to avoid duplicate reporting. Furthermore, we are using 'int err' as a boolean, so while we clean things up, we should fix that.
+++ b/src/openvz/openvz_driver.c @@ -88,7 +88,7 @@ static void openvzDriverUnlock(struct openvz_driver *driver)
struct openvz_driver ovz_driver;
-static void cmdExecFree(const char *cmdExec[]) +static void cmdExecFree(char *cmdExec[])
Do we even need this function, or can virStringFreeList do the same? For that matter, can we use virCommand instead of hand-rolling our own char*[] for command execution? But that can be a followup patch.
@@ -772,12 +766,14 @@ openvzGenerateVethName(int veid, char *dev_name_ve) { char dev_name[32]; int ifNo = 0; + char *ret;
if (sscanf(dev_name_ve, "%*[^0-9]%d", &ifNo) != 1) return NULL; if (snprintf(dev_name, sizeof(dev_name), "veth%d.%d", veid, ifNo) < 7) return NULL; - return strdup(dev_name); + ignore_value(VIR_STRDUP(ret, dev_name));
silent->noisy, but only on some of the failure paths. Callers are currently using virReportError(), which means you won't notice this on your pass to clean up oom reporting; so add this to the list of things that needs explicit followup.
@@ -788,7 +784,7 @@ openvzGenerateContainerVethName(int veid)
/* try to get line "^NETIF=..." from config */ if (openvzReadVPSConfigParam(veid, "NETIF", &temp) <= 0) { - name = strdup("eth0"); + ignore_value(VIR_STRDUP(name, "eth0"));
Wow. This function was previously reporting oom but callers were then throwing it away to report internal error. Again, something we ought to clean up.
@@ -821,7 +814,7 @@ openvzDomainSetNetwork(virConnectPtr conn, const char *vpsid, virBufferPtr configBuf) { int rc = 0, narg; - const char *prog[OPENVZ_MAX_ARG]; + char *prog[OPENVZ_MAX_ARG]; char macaddr[VIR_MAC_STRING_BUFLEN]; virMacAddr host_mac; char host_macaddr[VIR_MAC_STRING_BUFLEN]; @@ -830,9 +823,9 @@ openvzDomainSetNetwork(virConnectPtr conn, const char *vpsid,
#define ADD_ARG_LIT(thisarg) \ do { \ - if (narg >= OPENVZ_MAX_ARG) \ + if (narg >= OPENVZ_MAX_ARG) \ goto no_memory; \ - if ((prog[narg++] = strdup(thisarg)) == NULL) \ + if (VIR_STRDUP(prog[narg++], thisarg) < 0) \ goto no_memory; \ } while (0)
Again, why aren't we using virCommand? -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/parallels/parallels_driver.c | 71 +++++++++++++++++---------------------- src/parallels/parallels_network.c | 23 +++++-------- src/parallels/parallels_storage.c | 62 +++++++++++----------------------- 3 files changed, 58 insertions(+), 98 deletions(-) diff --git a/src/parallels/parallels_driver.c b/src/parallels/parallels_driver.c index c29a5ba..eec315d 100644 --- a/src/parallels/parallels_driver.c +++ b/src/parallels/parallels_driver.c @@ -186,8 +186,8 @@ parallelsGetSerialInfo(virDomainChrDefPtr chr, return -1; } - if (!(chr->source.data.file.path = strdup(tmp))) - goto no_memory; + if (VIR_STRDUP(chr->source.data.file.path, tmp) < 0) + goto error; } else if (virJSONValueObjectHasKey(value, "socket")) { chr->source.type = VIR_DOMAIN_CHR_TYPE_UNIX; @@ -197,8 +197,8 @@ parallelsGetSerialInfo(virDomainChrDefPtr chr, return -1; } - if (!(chr->source.data.nix.path = strdup(tmp))) - goto no_memory; + if (VIR_STRDUP(chr->source.data.nix.path, tmp) < 0) + goto error; chr->source.data.nix.listen = false; } else if (virJSONValueObjectHasKey(value, "real")) { chr->source.type = VIR_DOMAIN_CHR_TYPE_DEV; @@ -209,8 +209,8 @@ parallelsGetSerialInfo(virDomainChrDefPtr chr, return -1; } - if (!(chr->source.data.file.path = strdup(tmp))) - goto no_memory; + if (VIR_STRDUP(chr->source.data.file.path, tmp) < 0) + goto error; } else { parallelsParseError(); return -1; @@ -218,8 +218,7 @@ parallelsGetSerialInfo(virDomainChrDefPtr chr, return 0; - no_memory: - virReportOOMError(); +error: return -1; } @@ -318,10 +317,8 @@ parallelsGetHddInfo(virDomainDefPtr def, return -1; } - if (!(disk->src = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(disk->src, tmp) < 0) return -1; - } } else { disk->type = VIR_DOMAIN_DISK_TYPE_FILE; @@ -330,10 +327,8 @@ parallelsGetHddInfo(virDomainDefPtr def, return -1; } - if (!(disk->src = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(disk->src, tmp) < 0) return -1; - } } tmp = virJSONValueObjectGetString(value, "port"); @@ -454,10 +449,8 @@ parallelsGetNetInfo(virDomainNetDefPtr net, /* use device name, shown by prlctl as target device * for identifying network adapter in virDomainDefineXML */ - if (!(net->ifname = strdup(key))) { - virReportOOMError(); + if (VIR_STRDUP(net->ifname, key) < 0) goto error; - } net->type = VIR_DOMAIN_NET_TYPE_NETWORK; @@ -478,10 +471,8 @@ parallelsGetNetInfo(virDomainNetDefPtr net, goto error; } - if (!(net->data.network.name = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(net->data.network.name, tmp) < 0) goto error; - } } else if (virJSONValueObjectHasKey(value, "type")) { if (!(tmp = virJSONValueObjectGetString(value, "type"))) { parallelsParseError(); @@ -493,10 +484,9 @@ parallelsGetNetInfo(virDomainNetDefPtr net, goto error; } - if (!(net->data.network.name = strdup(PARALLELS_ROUTED_NETWORK_NAME))) { - virReportOOMError(); + if (VIR_STRDUP(net->data.network.name, + PARALLELS_ROUTED_NETWORK_NAME) < 0) goto error; - } } else { parallelsParseError(); goto error; @@ -641,8 +631,8 @@ parallelsAddVNCInfo(virDomainDefPtr def, virJSONValuePtr jobj_root) gr->nListens = 1; - if (!(gr->listens[0].address = strdup(tmp))) - goto no_memory; + if (VIR_STRDUP(gr->listens[0].address, tmp) < 0) + goto cleanup; gr->listens[0].type = VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS; @@ -686,8 +676,8 @@ parallelsLoadDomain(parallelsConnPtr privconn, virJSONValuePtr jobj) parallelsParseError(); goto cleanup; } - if (!(def->name = strdup(tmp))) - goto no_memory; + if (VIR_STRDUP(def->name, tmp) < 0) + goto cleanup; if (!(tmp = virJSONValueObjectGetString(jobj, "ID"))) { parallelsParseError(); @@ -704,8 +694,8 @@ parallelsLoadDomain(parallelsConnPtr privconn, virJSONValuePtr jobj) parallelsParseError(); goto cleanup; } - if (!(def->description = strdup(tmp))) - goto no_memory; + if (VIR_STRDUP(def->description, tmp) < 0) + goto cleanup; if (!(jobj2 = virJSONValueObjectGet(jobj, "Hardware"))) { parallelsParseError(); @@ -771,13 +761,13 @@ parallelsLoadDomain(parallelsConnPtr privconn, virJSONValuePtr jobj) } if (STREQ(tmp, "CT")) { - if (!(def->os.type = strdup("exe"))) - goto no_memory; - if (!(def->os.init = strdup("/sbin/init"))) - goto no_memory; + if (VIR_STRDUP(def->os.type, "exe") < 0) + goto cleanup; + if (VIR_STRDUP(def->os.init, "/sbin/init") < 0) + goto cleanup; } else if (STREQ(tmp, "VM")) { - if (!(def->os.type = strdup("hvm"))) - goto no_memory; + if (VIR_STRDUP(def->os.type, "hvm") < 0) + goto cleanup; } def->os.arch = VIR_ARCH_X86_64; @@ -792,16 +782,16 @@ parallelsLoadDomain(parallelsConnPtr privconn, virJSONValuePtr jobj) parallelsParseError(); goto cleanup; } - if (!(pdom->uuid = strdup(tmp))) - goto no_memory; + if (VIR_STRDUP(pdom->uuid, tmp) < 0) + goto cleanup; if (!(tmp = virJSONValueObjectGetString(jobj, "Home"))) { parallelsParseError(); goto cleanup; } - if (!(pdom->home = strdup(tmp))) - goto no_memory; + if (VIR_STRDUP(pdom->home, tmp) < 0) + goto cleanup; if (!(state = virJSONValueObjectGetString(jobj, "State"))) { parallelsParseError(); @@ -1239,8 +1229,7 @@ parallelsDomainGetOSType(virDomainPtr domain) goto cleanup; } - if (!(ret = strdup(privdom->def->os.type))) - virReportOOMError(); + ignore_value(VIR_STRDUP(ret, privdom->def->os.type)); cleanup: if (privdom) diff --git a/src/parallels/parallels_network.c b/src/parallels/parallels_network.c index 23109d3..2e5523b 100644 --- a/src/parallels/parallels_network.c +++ b/src/parallels/parallels_network.c @@ -66,10 +66,8 @@ static int parallelsGetBridgedNetInfo(virNetworkDefPtr def, virJSONValuePtr jobj goto cleanup; } - if (!(def->bridge = strdup(last_component(bridgePath)))) { - virReportOOMError(); + if (VIR_STRDUP(def->bridge, last_component(bridgePath)) < 0) goto cleanup; - } if (virAsprintf(&bridgeAddressPath, "%s/%s/brport/bridge/address", SYSFS_NET_DIR, ifname) < 0) { @@ -130,10 +128,9 @@ static int parallelsGetHostOnlyNetInfo(virNetworkDefPtr def, const char *name) goto cleanup; } - if (!(def->ips[0].family = strdup("ipv4"))) { - virReportOOMError(); + if (VIR_STRDUP(def->ips[0].family, "ipv4") < 0) goto cleanup; - }; + if (!(tmp = virJSONValueObjectGetString(jobj2, "IP address"))) { parallelsParseError(); goto cleanup; @@ -207,8 +204,8 @@ parallelsLoadNetwork(parallelsConnPtr privconn, virJSONValuePtr jobj) goto cleanup; } - if (!(def->name = strdup(tmp))) - goto no_memory; + if (VIR_STRDUP(def->name, tmp) < 0) + goto cleanup; /* Network names are unique in Parallels Cloud Server, so we can make * an UUID from it */ @@ -264,8 +261,8 @@ parallelsAddRoutedNetwork(parallelsConnPtr privconn) def->forward.type = VIR_NETWORK_FORWARD_ROUTE; - if (!(def->name = strdup(PARALLELS_ROUTED_NETWORK_NAME))) - goto no_memory; + if (VIR_STRDUP(def->name, PARALLELS_ROUTED_NETWORK_NAME) < 0) + goto cleanup; if (virUUIDParse(PARALLELS_ROUTED_NETWORK_UUID, def->uuid) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", @@ -390,9 +387,8 @@ static int parallelsConnectListNetworks(virConnectPtr conn, for (i = 0 ; i < privconn->networks.count && got < nnames ; i++) { virNetworkObjLock(privconn->networks.objs[i]); if (virNetworkObjIsActive(privconn->networks.objs[i])) { - if (!(names[got] = strdup(privconn->networks.objs[i]->def->name))) { + if (VIR_STRDUP(names[got], privconn->networks.objs[i]->def->name) < 0) { virNetworkObjUnlock(privconn->networks.objs[i]); - virReportOOMError(); goto cleanup; } got++; @@ -438,9 +434,8 @@ static int parallelsConnectListDefinedNetworks(virConnectPtr conn, for (i = 0 ; i < privconn->networks.count && got < nnames ; i++) { virNetworkObjLock(privconn->networks.objs[i]); if (!virNetworkObjIsActive(privconn->networks.objs[i])) { - if (!(names[got] = strdup(privconn->networks.objs[i]->def->name))) { + if (VIR_STRDUP(names[got], privconn->networks.objs[i]->def->name) < 0) { virNetworkObjUnlock(privconn->networks.objs[i]); - virReportOOMError(); goto cleanup; } got++; diff --git a/src/parallels/parallels_storage.c b/src/parallels/parallels_storage.c index 4c98e43..3123e29 100644 --- a/src/parallels/parallels_storage.c +++ b/src/parallels/parallels_storage.c @@ -136,20 +136,9 @@ static char *parallelsMakePoolName(virConnectPtr conn, const char *path) bool found = false; int j; - if (!(name = strdup(path))) { - virReportOOMError(); - return NULL; - } - - if (i == 0) - name = strdup(path); - else - ignore_value(virAsprintf(&name, "%s-%u", path, i)); - - if (!name) { - virReportOOMError(); + if ((!i && VIR_STRDUP(name, path) < 0) || + (i && virAsprintf(&name, "%s-%u", path, i) < 0)) return 0; - } for (j = 0; j < strlen(name); j++) if (name[j] == '/') @@ -195,7 +184,8 @@ parallelsPoolCreateByPath(virConnectPtr conn, const char *path) } def->type = VIR_STORAGE_POOL_DIR; - def->target.path = strdup(path); + if (VIR_STRDUP(def->target.path, path) < 0) + goto error; if (!(pool = virStoragePoolObjAssignDef(pools, def))) goto error; @@ -324,8 +314,8 @@ static int parallelsAddDiskVolume(virStoragePoolObjPtr pool, if (!(def->target.path = realpath(diskPath, NULL))) goto no_memory; - if (!(def->key = strdup(def->target.path))) - goto no_memory; + if (VIR_STRDUP(def->key, def->target.path) < 0) + goto error; if (VIR_REALLOC_N(pool->volumes.objs, pool->volumes.count + 1) < 0) goto no_memory; @@ -425,8 +415,8 @@ static int parallelsLoadPools(virConnectPtr conn) char *base = NULL; size_t i; - if ((base = strdup(SYSCONFDIR "/libvirt")) == NULL) - goto out_of_memory; + if (VIR_STRDUP(base, SYSCONFDIR "/libvirt") < 0) + goto error; /* Configuration path is /etc/libvirt/parallels-storage/... . */ if (virAsprintf(&storageState->configDir, @@ -540,9 +530,9 @@ parallelsConnectListStoragePools(virConnectPtr conn, char **const names, int nna for (i = 0; i < privconn->pools.count && n < nnames; i++) { virStoragePoolObjLock(privconn->pools.objs[i]); if (virStoragePoolObjIsActive(privconn->pools.objs[i]) && - !(names[n++] = strdup(privconn->pools.objs[i]->def->name))) { + VIR_STRDUP(names[n++], privconn->pools.objs[i]->def->name) < 0) { virStoragePoolObjUnlock(privconn->pools.objs[i]); - goto no_memory; + goto error; } virStoragePoolObjUnlock(privconn->pools.objs[i]); } @@ -550,8 +540,7 @@ parallelsConnectListStoragePools(virConnectPtr conn, char **const names, int nna return n; -no_memory: - virReportOOMError(); +error: for (n = 0; n < nnames; n++) VIR_FREE(names[n]); parallelsDriverUnlock(privconn); @@ -590,9 +579,9 @@ parallelsConnectListDefinedStoragePools(virConnectPtr conn, for (i = 0; i < privconn->pools.count && n < nnames; i++) { virStoragePoolObjLock(privconn->pools.objs[i]); if (!virStoragePoolObjIsActive(privconn->pools.objs[i]) && - !(names[n++] = strdup(privconn->pools.objs[i]->def->name))) { + VIR_STRDUP(names[n++], privconn->pools.objs[i]->def->name) < 0) { virStoragePoolObjUnlock(privconn->pools.objs[i]); - goto no_memory; + goto error; } virStoragePoolObjUnlock(privconn->pools.objs[i]); } @@ -600,7 +589,7 @@ parallelsConnectListDefinedStoragePools(virConnectPtr conn, return n; -no_memory: +error: virReportOOMError(); for (n = 0; n < nnames; n++) VIR_FREE(names[n]); @@ -758,11 +747,8 @@ parallelsStoragePoolDefineXML(virConnectPtr conn, } def = NULL; - pool->configFile = strdup("\0"); - if (!pool->configFile) { - virReportOOMError(); + if (VIR_STRDUP(pool->configFile, "\0") < 0) goto cleanup; - } ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid, NULL, NULL); @@ -1085,10 +1071,8 @@ parallelsStoragePoolListVolumes(virStoragePoolPtr pool, } for (i = 0; i < privpool->volumes.count && n < maxnames; i++) { - if ((names[n++] = strdup(privpool->volumes.objs[i]->name)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(names[n++], privpool->volumes.objs[i]->name) < 0) goto error; - } } virStoragePoolObjUnlock(privpool); @@ -1271,11 +1255,8 @@ parallelsStorageVolDefineXML(virStoragePoolObjPtr pool, goto cleanup; } - privvol->key = strdup(privvol->target.path); - if (privvol->key == NULL) { - virReportOOMError(); + if (VIR_STRDUP(privvol->key, privvol->target.path) < 0) goto cleanup; - } if (is_new) { xml_path = parallelsAddFileExt(privvol->target.path, ".xml"); @@ -1412,11 +1393,8 @@ parallelsStorageVolCreateXMLFrom(virStoragePoolPtr pool, goto cleanup; } - privvol->key = strdup(privvol->target.path); - if (privvol->key == NULL) { - virReportOOMError(); + if (VIR_STRDUP(privvol->key, privvol->target.path) < 0) goto cleanup; - } privpool->def->allocation += privvol->allocation; privpool->def->available = (privpool->def->capacity - @@ -1659,9 +1637,7 @@ parallelsStorageVolGetPath(virStorageVolPtr vol) goto cleanup; } - ret = strdup(privvol->target.path); - if (ret == NULL) - virReportOOMError(); + ignore_value(VIR_STRDUP(ret, privvol->target.path)); cleanup: if (privpool) -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/parallels/parallels_driver.c | 71 +++++++++++++++++---------------------- src/parallels/parallels_network.c | 23 +++++-------- src/parallels/parallels_storage.c | 62 +++++++++++----------------------- 3 files changed, 58 insertions(+), 98 deletions(-)
diff --git a/src/parallels/parallels_driver.c b/src/parallels/parallels_driver.c @@ -209,8 +209,8 @@ parallelsGetSerialInfo(virDomainChrDefPtr chr, return -1; }
- if (!(chr->source.data.file.path = strdup(tmp))) - goto no_memory; + if (VIR_STRDUP(chr->source.data.file.path, tmp) < 0) + goto error; } else { parallelsParseError(); return -1; @@ -218,8 +218,7 @@ parallelsGetSerialInfo(virDomainChrDefPtr chr,
return 0;
- no_memory: - virReportOOMError(); +error: return -1;
It looks a bit odd that this function has inlined 'return -1' in some spots, and uses a label with no action other than 'return -1' in others. If you WANT to make it consistent, I don't care whether you use all inline or all goto; but I'm not going to insist on consistency.
@@ -771,13 +761,13 @@ parallelsLoadDomain(parallelsConnPtr privconn, virJSONValuePtr jobj) }
if (STREQ(tmp, "CT")) { - if (!(def->os.type = strdup("exe"))) - goto no_memory; - if (!(def->os.init = strdup("/sbin/init"))) - goto no_memory; + if (VIR_STRDUP(def->os.type, "exe") < 0) + goto cleanup; + if (VIR_STRDUP(def->os.init, "/sbin/init") < 0) + goto cleanup;
You could merge these into one 'if'.
+++ b/src/parallels/parallels_storage.c @@ -136,20 +136,9 @@ static char *parallelsMakePoolName(virConnectPtr conn, const char *path) bool found = false; int j;
- if (!(name = strdup(path))) { - virReportOOMError(); - return NULL; - } - - if (i == 0) - name = strdup(path);
Thanks for squashing this memory leak in the process :)
- else - ignore_value(virAsprintf(&name, "%s-%u", path, i)); - - if (!name) { - virReportOOMError(); + if ((!i && VIR_STRDUP(name, path) < 0) || + (i && virAsprintf(&name, "%s-%u", path, i) < 0)) return 0;
Pre-existing, but this should be 'return NULL'.
@@ -195,7 +184,8 @@ parallelsPoolCreateByPath(virConnectPtr conn, const char *path) }
def->type = VIR_STORAGE_POOL_DIR; - def->target.path = strdup(path); + if (VIR_STRDUP(def->target.path, path) < 0) + goto error;
silent->noisy, but looks like a good bug fix.
@@ -590,9 +579,9 @@ parallelsConnectListDefinedStoragePools(virConnectPtr conn, for (i = 0; i < privconn->pools.count && n < nnames; i++) { virStoragePoolObjLock(privconn->pools.objs[i]); if (!virStoragePoolObjIsActive(privconn->pools.objs[i]) && - !(names[n++] = strdup(privconn->pools.objs[i]->def->name))) { + VIR_STRDUP(names[n++], privconn->pools.objs[i]->def->name) < 0) { virStoragePoolObjUnlock(privconn->pools.objs[i]); - goto no_memory; + goto error; } virStoragePoolObjUnlock(privconn->pools.objs[i]); } @@ -600,7 +589,7 @@ parallelsConnectListDefinedStoragePools(virConnectPtr conn,
return n;
-no_memory: +error: virReportOOMError();
Drop this oom, since the only client of this label already reported oom. ACK with minor fixes. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/phyp/phyp_driver.c | 50 ++++++++++---------------------------------------- 1 file changed, 10 insertions(+), 40 deletions(-) diff --git a/src/phyp/phyp_driver.c b/src/phyp/phyp_driver.c index 85eb650..7079974 100644 --- a/src/phyp/phyp_driver.c +++ b/src/phyp/phyp_driver.c @@ -954,12 +954,8 @@ openSSHSession(virConnectPtr conn, virConnectAuthPtr auth, } if (conn->uri->user != NULL) { - username = strdup(conn->uri->user); - - if (username == NULL) { - virReportOOMError(); + if (VIR_STRDUP(username, conn->uri->user) < 0) goto err; - } } else { if (auth == NULL || auth->cb == NULL) { virReportError(VIR_ERR_AUTH_FAILED, @@ -1141,15 +1137,9 @@ phypConnectOpen(virConnectPtr conn, if (conn->uri->path) { /* need to shift one byte in order to remove the first "/" of URI component */ - if (conn->uri->path[0] == '/') - managed_system = strdup(conn->uri->path + 1); - else - managed_system = strdup(conn->uri->path); - - if (!managed_system) { - virReportOOMError(); + if (VIR_STRDUP(managed_system, conn->uri->path[0] == '/' ? + conn->uri->path + 1 : conn->uri->path) < 0) goto failure; - } /* here we are handling only the first component of the path, * so skipping the second: @@ -1498,12 +1488,8 @@ phypGetBackingDevice(virConnectPtr conn, const char *managed_system, else goto cleanup; - backing_device = strdup(char_ptr); - - if (backing_device == NULL) { - virReportOOMError(); + if (VIR_STRDUP(backing_device, char_ptr) < 0) goto cleanup; - } } else { backing_device = ret; ret = NULL; @@ -1731,12 +1717,8 @@ phypDomainAttachDevice(virDomainPtr domain, const char *xml) goto cleanup; } - def->os.type = strdup("aix"); - - if (def->os.type == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->os.type, "aix") < 0) goto cleanup; - } dev = virDomainDeviceDefParse(xml, def, phyp_driver->caps, NULL, VIR_DOMAIN_XML_INACTIVE); @@ -2281,12 +2263,8 @@ phypStorageVolGetXMLDesc(virStorageVolPtr vol, unsigned int flags) goto cleanup; } - voldef.key = strdup(vol->key); - - if (voldef.key == NULL) { - virReportOOMError(); + if (VIR_STRDUP(voldef.key, vol->key) < 0) goto cleanup; - } voldef.type = VIR_STORAGE_POOL_LOGICAL; @@ -2399,10 +2377,8 @@ phypStoragePoolListVolumes(virStoragePoolPtr pool, char **const volumes, if (char_ptr) { *char_ptr = '\0'; - if ((volumes[got++] = strdup(volumes_list)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(volumes[got++], volumes_list) < 0) goto cleanup; - } char_ptr++; volumes_list = char_ptr; } else @@ -2600,10 +2576,8 @@ phypConnectListStoragePools(virConnectPtr conn, char **const pools, int npools) if (char_ptr) { *char_ptr = '\0'; - if ((pools[got++] = strdup(storage_pools)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(pools[got++], storage_pools) < 0) goto cleanup; - } char_ptr++; storage_pools = char_ptr; } else @@ -3067,10 +3041,8 @@ phypConnectListInterfaces(virConnectPtr conn, char **const names, int nnames) if (char_ptr) { *char_ptr = '\0'; - if ((names[got++] = strdup(networks)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(names[got++], networks) < 0) goto cleanup; - } char_ptr++; networks = char_ptr; } else { @@ -3234,10 +3206,8 @@ phypConnectListDefinedDomains(virConnectPtr conn, char **const names, int nnames if (char_ptr) { *char_ptr = '\0'; - if ((names[got++] = strdup(domains)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(names[got++], domains) < 0) goto cleanup; - } char_ptr++; domains = char_ptr; } else -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/phyp/phyp_driver.c | 50 ++++++++++---------------------------------------- 1 file changed, 10 insertions(+), 40 deletions(-)
diff --git a/src/phyp/phyp_driver.c b/src/phyp/phyp_driver.c @@ -1141,15 +1137,9 @@ phypConnectOpen(virConnectPtr conn,
if (conn->uri->path) { /* need to shift one byte in order to remove the first "/" of URI component */ - if (conn->uri->path[0] == '/') - managed_system = strdup(conn->uri->path + 1); - else - managed_system = strdup(conn->uri->path); - - if (!managed_system) { - virReportOOMError(); + if (VIR_STRDUP(managed_system, conn->uri->path[0] == '/' ? + conn->uri->path + 1 : conn->uri->path) < 0)
Simpler to write: VIR_STRDUP(managed_system, conn->uri->path + (conn->uri->path[0] == '/')) ACK. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- include/libvirt/libvirt.h.in | 10 +- src/qemu/qemu_capabilities.c | 79 ++++---- src/qemu/qemu_cgroup.c | 4 +- src/qemu/qemu_command.c | 419 +++++++++++++++++-------------------------- src/qemu/qemu_conf.c | 58 +++--- src/qemu/qemu_domain.c | 26 ++- src/qemu/qemu_driver.c | 113 ++++-------- src/qemu/qemu_hotplug.c | 15 +- src/qemu/qemu_migration.c | 20 +-- src/qemu/qemu_monitor_json.c | 63 ++----- src/qemu/qemu_monitor_text.c | 15 +- src/qemu/qemu_process.c | 64 +++---- src/remote/remote_driver.c | 2 +- 13 files changed, 333 insertions(+), 555 deletions(-) diff --git a/include/libvirt/libvirt.h.in b/include/libvirt/libvirt.h.in index 693b834..9a8090d 100644 --- a/include/libvirt/libvirt.h.in +++ b/include/libvirt/libvirt.h.in @@ -1294,7 +1294,7 @@ typedef enum { struct _virConnectCredential { int type; /* One of virConnectCredentialType constants */ - const char *prompt; /* Prompt to show to user */ + char *prompt; /* Prompt to show to user */ const char *challenge; /* Additional challenge to show */ const char *defresult; /* Optional default result */ char *result; /* Result to be filled with user response (or defresult) */ @@ -4504,8 +4504,8 @@ typedef enum { */ struct _virDomainEventGraphicsAddress { int family; /* Address family, virDomainEventGraphicsAddressType */ - const char *node; /* Address of node (eg IP address, or UNIX path) */ - const char *service; /* Service name/number (eg TCP port, or NULL) */ + char *node; /* Address of node (eg IP address, or UNIX path) */ + char *service; /* Service name/number (eg TCP port, or NULL) */ }; typedef struct _virDomainEventGraphicsAddress virDomainEventGraphicsAddress; typedef virDomainEventGraphicsAddress *virDomainEventGraphicsAddressPtr; @@ -4520,8 +4520,8 @@ typedef virDomainEventGraphicsAddress *virDomainEventGraphicsAddressPtr; * some examples are 'x509dname' and 'saslUsername'. */ struct _virDomainEventGraphicsSubjectIdentity { - const char *type; /* Type of identity */ - const char *name; /* Identity value */ + char *type; /* Type of identity */ + char *name; /* Identity value */ }; typedef struct _virDomainEventGraphicsSubjectIdentity virDomainEventGraphicsSubjectIdentity; typedef virDomainEventGraphicsSubjectIdentity *virDomainEventGraphicsSubjectIdentityPtr; diff --git a/src/qemu/qemu_capabilities.c b/src/qemu/qemu_capabilities.c index a3a8d1f..7597a4b 100644 --- a/src/qemu/qemu_capabilities.c +++ b/src/qemu/qemu_capabilities.c @@ -362,8 +362,8 @@ virQEMUCapsParseMachineTypesStr(const char *output, if (!(t = strchr(p, ' ')) || (next && t >= next)) continue; - if (!(name = strndup(p, t - p))) - goto no_memory; + if (VIR_STRNDUP(name, p, t - p) < 0) + goto error; p = t; if ((t = strstr(p, "(default)")) && (!next || t < next)) @@ -374,9 +374,9 @@ virQEMUCapsParseMachineTypesStr(const char *output, if (!(t = strchr(p, ')')) || (next && t >= next)) continue; - if (!(canonical = strndup(p, t - p))) { + if (VIR_STRNDUP(canonical, p, t - p) < 0) { VIR_FREE(name); - goto no_memory; + goto error; } } @@ -384,7 +384,8 @@ virQEMUCapsParseMachineTypesStr(const char *output, VIR_REALLOC_N(qemuCaps->machineAliases, qemuCaps->nmachineTypes + 1) < 0) { VIR_FREE(name); VIR_FREE(canonical); - goto no_memory; + virReportOOMError(); + goto error; } qemuCaps->nmachineTypes++; if (canonical) { @@ -402,8 +403,7 @@ virQEMUCapsParseMachineTypesStr(const char *output, return 0; -no_memory: - virReportOOMError(); +error: return -1; } @@ -499,10 +499,8 @@ virQEMUCapsParseX86Models(const char *output, len -= 2; } - if (!(qemuCaps->cpuDefinitions[qemuCaps->ncpuDefinitions - 1] = strndup(p, len))) { - virReportOOMError(); + if (VIR_STRNDUP(qemuCaps->cpuDefinitions[qemuCaps->ncpuDefinitions - 1], p, len) < 0) goto cleanup; - } } while ((p = next)); ret = 0; @@ -552,10 +550,8 @@ virQEMUCapsParsePPCModels(const char *output, len = t - p - 1; - if (!(qemuCaps->cpuDefinitions[qemuCaps->ncpuDefinitions - 1] = strndup(p, len))) { - virReportOOMError(); + if (VIR_STRNDUP(qemuCaps->cpuDefinitions[qemuCaps->ncpuDefinitions - 1], p, len) < 0) goto cleanup; - } } while ((p = next)); ret = 0; @@ -1498,10 +1494,8 @@ virQEMUCapsParseDeviceStrObjectTypes(const char *str, virReportOOMError(); goto cleanup; } - if (!(typelist[ntypelist-1] = strndup(tmp, end-tmp))) { - virReportOOMError(); + if (VIR_STRNDUP(typelist[ntypelist-1], tmp, end-tmp) < 0) goto cleanup; - } } *types = typelist; @@ -1555,10 +1549,8 @@ virQEMUCapsParseDeviceStrObjectProps(const char *str, virReportOOMError(); goto cleanup; } - if (!(proplist[nproplist-1] = strndup(tmp, end-tmp))) { - virReportOOMError(); + if (VIR_STRNDUP(proplist[nproplist-1], tmp, end-tmp) < 0) goto cleanup; - } } *props = proplist; @@ -1726,8 +1718,8 @@ virQEMUCapsPtr virQEMUCapsNewCopy(virQEMUCapsPtr qemuCaps) goto no_memory; ret->ncpuDefinitions = qemuCaps->ncpuDefinitions; for (i = 0 ; i < qemuCaps->ncpuDefinitions ; i++) { - if (!(ret->cpuDefinitions[i] = strdup(qemuCaps->cpuDefinitions[i]))) - goto no_memory; + if (VIR_STRDUP(ret->cpuDefinitions[i], qemuCaps->cpuDefinitions[i]) < 0) + goto error; } if (VIR_ALLOC_N(ret->machineTypes, qemuCaps->nmachineTypes) < 0) @@ -1736,17 +1728,18 @@ virQEMUCapsPtr virQEMUCapsNewCopy(virQEMUCapsPtr qemuCaps) goto no_memory; ret->nmachineTypes = qemuCaps->nmachineTypes; for (i = 0 ; i < qemuCaps->nmachineTypes ; i++) { - if (!(ret->machineTypes[i] = strdup(qemuCaps->machineTypes[i]))) - goto no_memory; + if (VIR_STRDUP(ret->machineTypes[i], qemuCaps->machineTypes[i]) < 0) + goto error; if (qemuCaps->machineAliases[i] && - !(ret->machineAliases[i] = strdup(qemuCaps->machineAliases[i]))) - goto no_memory; + VIR_STRDUP(ret->machineAliases[i], qemuCaps->machineAliases[i]) < 0) + goto error; } return ret; no_memory: virReportOOMError(); +error: virObjectUnref(ret); return NULL; } @@ -1848,11 +1841,10 @@ unsigned int virQEMUCapsGetKVMVersion(virQEMUCapsPtr qemuCaps) int virQEMUCapsAddCPUDefinition(virQEMUCapsPtr qemuCaps, const char *name) { - char *tmp = strdup(name); - if (!tmp) { - virReportOOMError(); + char *tmp; + + if (VIR_STRDUP(tmp, name) < 0) return -1; - } if (VIR_EXPAND_N(qemuCaps->cpuDefinitions, qemuCaps->ncpuDefinitions, 1) < 0) { VIR_FREE(tmp); virReportOOMError(); @@ -1897,12 +1889,12 @@ int virQEMUCapsGetMachineTypesCaps(virQEMUCapsPtr qemuCaps, if (VIR_ALLOC(mach) < 0) goto no_memory; if (qemuCaps->machineAliases[i]) { - if (!(mach->name = strdup(qemuCaps->machineAliases[i]))) + if (VIR_STRDUP(mach->name, qemuCaps->machineAliases[i]) < 0) goto no_memory; - if (!(mach->canonical = strdup(qemuCaps->machineTypes[i]))) + if (VIR_STRDUP(mach->canonical, qemuCaps->machineTypes[i]) < 0) goto no_memory; } else { - if (!(mach->name = strdup(qemuCaps->machineTypes[i]))) + if (VIR_STRDUP(mach->name, qemuCaps->machineTypes[i]) < 0) goto no_memory; } (*machines)[i] = mach; @@ -2091,16 +2083,11 @@ virQEMUCapsProbeQMPMachineTypes(virQEMUCapsPtr qemuCaps, } for (i = 0 ; i < nmachines ; i++) { - if (machines[i]->alias) { - if (!(qemuCaps->machineAliases[i] = strdup(machines[i]->alias))) { - virReportOOMError(); - goto cleanup; - } - } - if (!(qemuCaps->machineTypes[i] = strdup(machines[i]->name))) { - virReportOOMError(); + if (machines[i]->alias && + VIR_STRDUP(qemuCaps->machineAliases[i], machines[i]->alias) < 0) + goto cleanup; + if (VIR_STRDUP(qemuCaps->machineTypes[i], machines[i]->name) < 0) goto cleanup; - } if (machines[i]->isDefault) defIdx = i; } @@ -2590,8 +2577,8 @@ virQEMUCapsPtr virQEMUCapsNewForBinary(const char *binary, struct stat sb; int rv; - if (!(qemuCaps->binary = strdup(binary))) - goto no_memory; + if (VIR_STRDUP(qemuCaps->binary, binary) < 0) + goto error; /* We would also want to check faccessat if we cared about ACLs, * but we don't. */ @@ -2621,8 +2608,6 @@ virQEMUCapsPtr virQEMUCapsNewForBinary(const char *binary, return qemuCaps; -no_memory: - virReportOOMError(); error: virObjectUnref(qemuCaps); qemuCaps = NULL; @@ -2672,10 +2657,8 @@ virQEMUCapsCacheNew(const char *libDir, if (!(cache->binaries = virHashCreate(10, virQEMUCapsHashDataFree))) goto error; - if (!(cache->libDir = strdup(libDir))) { - virReportOOMError(); + if (VIR_STRDUP(cache->libDir, libDir) < 0) goto error; - } cache->runUid = runUid; cache->runGid = runGid; diff --git a/src/qemu/qemu_cgroup.c b/src/qemu/qemu_cgroup.c index 4819cfe..57839b3 100644 --- a/src/qemu/qemu_cgroup.c +++ b/src/qemu/qemu_cgroup.c @@ -31,6 +31,7 @@ #include "viralloc.h" #include "virerror.h" #include "domain_audit.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_QEMU @@ -388,8 +389,7 @@ int qemuInitCgroup(virQEMUDriverPtr driver, goto cleanup; } - if (!(res->partition = strdup("/machine"))) { - virReportOOMError(); + if (VIR_STRDUP(res->partition, "/machine") < 0) { VIR_FREE(res); goto cleanup; } diff --git a/src/qemu/qemu_command.c b/src/qemu/qemu_command.c index 144620c..786ed1e 100644 --- a/src/qemu/qemu_command.c +++ b/src/qemu/qemu_command.c @@ -322,10 +322,8 @@ qemuNetworkIfaceConnect(virDomainDefPtr def, return -1; } else if (actualType == VIR_DOMAIN_NET_TYPE_BRIDGE) { - if (!(brname = strdup(virDomainNetGetActualBridgeName(net)))) { - virReportOOMError(); + if (VIR_STRDUP(brname, virDomainNetGetActualBridgeName(net)) < 0) return -1; - } } else { virReportError(VIR_ERR_INTERNAL_ERROR, _("Network type %d is not supported"), @@ -337,10 +335,8 @@ qemuNetworkIfaceConnect(virDomainDefPtr def, STRPREFIX(net->ifname, VIR_NET_GENERATED_PREFIX) || strchr(net->ifname, '%')) { VIR_FREE(net->ifname); - if (!(net->ifname = strdup(VIR_NET_GENERATED_PREFIX "%d"))) { - virReportOOMError(); + if (VIR_STRDUP(net->ifname, VIR_NET_GENERATED_PREFIX "%d") < 0) goto cleanup; - } /* avoid exposing vnet%d in getXMLDesc or error outputs */ template_ifname = true; } @@ -486,17 +482,10 @@ static int qemuAssignDeviceDiskAliasLegacy(virDomainDiskDefPtr disk) { char *dev_name; - if (disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM && - STREQ(disk->dst, "hdc")) - dev_name = strdup("cdrom"); - else - dev_name = strdup(disk->dst); - - if (!dev_name) { - virReportOOMError(); + if (VIR_STRDUP(dev_name, + disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM && + STREQ(disk->dst, "hdc") ? "cdrom" : disk->dst) < 0) return -1; - } - disk->info.alias = dev_name; return 0; } @@ -513,10 +502,7 @@ char *qemuDeviceDriveHostAlias(virDomainDiskDefPtr disk, return NULL; } } else { - if (!(ret = strdup(disk->info.alias))) { - virReportOOMError(); - return NULL; - } + ignore_value(VIR_STRDUP(ret, disk->info.alias)); } return ret; } @@ -2418,13 +2404,11 @@ static int qemuAddRBDHost(virDomainDiskDefPtr disk, char *hostport) if (port) { *port = '\0'; port += skip; - disk->hosts[disk->nhosts-1].port = strdup(port); - if (!disk->hosts[disk->nhosts-1].port) - goto no_memory; + if (VIR_STRDUP(disk->hosts[disk->nhosts-1].port, port) < 0) + goto error; } else { - disk->hosts[disk->nhosts-1].port = strdup("6789"); - if (!disk->hosts[disk->nhosts-1].port) - goto no_memory; + if (VIR_STRDUP(disk->hosts[disk->nhosts-1].port, "6789") < 0) + goto error; } parts = virStringSplit(hostport, "\\:", 0); @@ -2442,6 +2426,7 @@ static int qemuAddRBDHost(virDomainDiskDefPtr disk, char *hostport) no_memory: virReportOOMError(); +error: VIR_FREE(disk->hosts[disk->nhosts-1].port); VIR_FREE(disk->hosts[disk->nhosts-1].name); return -1; @@ -2455,9 +2440,8 @@ static int qemuParseRBDString(virDomainDiskDefPtr disk) p = strchr(disk->src, ':'); if (p) { - options = strdup(p + 1); - if (!options) - goto no_memory; + if (VIR_STRDUP(options, p + 1) < 0) + goto error; *p = '\0'; } @@ -2482,11 +2466,9 @@ static int qemuParseRBDString(virDomainDiskDefPtr disk) *e = '\0'; } - if (STRPREFIX(p, "id=")) { - disk->auth.username = strdup(p + strlen("id=")); - if (!disk->auth.username) - goto no_memory; - } + if (STRPREFIX(p, "id=") && + VIR_STRDUP(disk->auth.username, p + strlen("id=")) < 0) + goto error; if (STRPREFIX(p, "mon_host=")) { char *h, *sep; @@ -2513,9 +2495,8 @@ static int qemuParseRBDString(virDomainDiskDefPtr disk) VIR_FREE(options); return 0; -no_memory: +error: VIR_FREE(options); - virReportOOMError(); return -1; } @@ -2555,9 +2536,8 @@ qemuParseDriveURIString(virDomainDiskDefPtr def, virURIPtr uri, def->nhosts = 0; /* set to 1 once everything succeeds */ if (def->hosts->transport != VIR_DOMAIN_DISK_PROTO_TRANS_UNIX) { - def->hosts->name = strdup(uri->server); - if (!def->hosts->name) - goto no_memory; + if (VIR_STRDUP(def->hosts->name, uri->server) < 0) + goto error; if (virAsprintf(&def->hosts->port, "%d", uri->port) < 0) goto no_memory; @@ -2567,9 +2547,8 @@ qemuParseDriveURIString(virDomainDiskDefPtr def, virURIPtr uri, if (uri->query) { if (STRPREFIX(uri->query, "socket=")) { sock = strchr(uri->query, '=') + 1; - def->hosts->socket = strdup(sock); - if (!def->hosts->socket) - goto no_memory; + if (VIR_STRDUP(def->hosts->socket, sock) < 0) + goto error; } else { virReportError(VIR_ERR_INTERNAL_ERROR, _("Invalid query parameter '%s'"), uri->query); @@ -2580,9 +2559,8 @@ qemuParseDriveURIString(virDomainDiskDefPtr def, virURIPtr uri, if (uri->path) { volimg = uri->path + 1; /* skip the prefix slash */ VIR_FREE(def->src); - def->src = strdup(volimg); - if (!def->src) - goto no_memory; + if (VIR_STRDUP(def->src, volimg) < 0) + goto error; } else { VIR_FREE(def->src); def->src = NULL; @@ -2593,9 +2571,8 @@ qemuParseDriveURIString(virDomainDiskDefPtr def, virURIPtr uri, if (secret) *secret = '\0'; - def->auth.username = strdup(uri->user); - if (!def->auth.username) - goto no_memory; + if (VIR_STRDUP(def->auth.username, uri->user) < 0) + goto error; } def->nhosts = 1; @@ -2675,7 +2652,8 @@ qemuParseNBDString(virDomainDiskDefPtr disk) *src++ = '\0'; h->transport = VIR_DOMAIN_DISK_PROTO_TRANS_UNIX; - h->socket = strdup(host + strlen("unix:")); + if (VIR_STRDUP(h->socket, host + strlen("unix:")) < 0) + goto error; } else { port = strchr(host, ':'); if (!port) { @@ -2685,23 +2663,20 @@ qemuParseNBDString(virDomainDiskDefPtr disk) } *port++ = '\0'; - h->name = strdup(host); - if (!h->name) - goto no_memory; + if (VIR_STRDUP(h->name, host) < 0) + goto error; src = strchr(port, ':'); if (src) *src++ = '\0'; - h->port = strdup(port); - if (!h->port) - goto no_memory; + if (VIR_STRDUP(h->port, port) < 0) + goto error; } if (src && STRPREFIX(src, "exportname=")) { - src = strdup(strchr(src, '=') + 1); - if (!src) - goto no_memory; + if (VIR_STRDUP(src, strchr(src, '=') + 1) < 0) + goto error; } else { src = NULL; } @@ -2751,9 +2726,8 @@ qemuBuildDriveURIString(virConnectPtr conn, transp = virDomainDiskProtocolTransportTypeToString(disk->hosts->transport); if (disk->hosts->transport == VIR_DOMAIN_DISK_PROTO_TRANS_TCP) { - tmpscheme = strdup(scheme); - if (tmpscheme == NULL) - goto no_memory; + if (VIR_STRDUP(tmpscheme, scheme) < 0) + goto cleanup; } else { if (virAsprintf(&tmpscheme, "%s+%s", scheme, transp) < 0) goto no_memory; @@ -5456,9 +5430,10 @@ qemuBuildCpuArgStr(const virQEMUDriverPtr driver, } virBufferAddLit(&buf, "host"); } else { - if (VIR_ALLOC(guest) < 0 || - (cpu->vendor_id && !(guest->vendor_id = strdup(cpu->vendor_id)))) + if (VIR_ALLOC(guest) < 0) goto no_memory; + if (cpu->vendor_id && VIR_STRDUP(guest->vendor_id, cpu->vendor_id) < 0) + goto cleanup; guest->arch = host->arch; if (cpu->match == VIR_CPU_MATCH_MINIMUM) @@ -7039,8 +7014,8 @@ qemuBuildCommandLine(virConnectPtr conn, virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("network disks are only supported with -drive")); } else { - if (!(file = strdup(disk->src))) { - goto no_memory; + if (VIR_STRDUP(file, disk->src) < 0) { + goto error; } } @@ -7875,8 +7850,8 @@ qemuBuildCommandLine(virConnectPtr conn, goto error; } - if (!(optstr = strdup(model))) - goto no_memory; + if (VIR_STRDUP(optstr, model) < 0) + goto error; } virCommandAddArg(cmd, optstr); VIR_FREE(optstr); @@ -8312,17 +8287,16 @@ static int qemuStringToArgvEnv(const char *args, next = strchr(curr, '\n'); if (next) { - arg = strndup(curr, next-curr); + if (VIR_STRNDUP(arg, curr, next-curr) < 0) + goto error; if (*next == '\'' || *next == '"') next++; } else { - arg = strdup(curr); + if (VIR_STRDUP(arg, curr) < 0) + goto error; } - if (!arg) - goto no_memory; - if (argalloc == argcount) { if (VIR_REALLOC_N(arglist, argalloc+10) < 0) { VIR_FREE(arg); @@ -8372,13 +8346,14 @@ static int qemuStringToArgvEnv(const char *args, return 0; no_memory: + virReportOOMError(); +error: for (i = 0 ; progenv && progenv[i] ; i++) VIR_FREE(progenv[i]); VIR_FREE(progenv); for (i = 0 ; i < argcount ; i++) VIR_FREE(arglist[i]); VIR_FREE(arglist); - virReportOOMError(); return -1; } @@ -8452,14 +8427,14 @@ qemuParseKeywords(const char *str, separator = endmark; } - if (!(keyword = strndup(start, separator - start))) - goto no_memory; + if (VIR_STRNDUP(keyword, start, separator - start) < 0) + goto error; if (separator < endmark) { separator++; - if (!(value = strndup(separator, endmark - separator))) { + if (VIR_STRNDUP(value, separator, endmark - separator) < 0) { VIR_FREE(keyword); - goto no_memory; + goto error; } if (strchr(value, ',')) { char *p = strchr(value, ',') + 1; @@ -8563,11 +8538,8 @@ qemuParseCommandLineDisk(virDomainXMLOptionPtr xmlopt, def->type = VIR_DOMAIN_DISK_TYPE_NETWORK; def->protocol = VIR_DOMAIN_DISK_PROTOCOL_RBD; - def->src = strdup(p + strlen("rbd:")); - if (!def->src) { - virReportOOMError(); + if (VIR_STRDUP(def->src, p + strlen("rbd:")) < 0) goto error; - } /* old-style CEPH_ARGS env variable is parsed later */ if (!old_style_ceph_args && qemuParseRBDString(def) < 0) goto cleanup; @@ -8592,11 +8564,8 @@ qemuParseCommandLineDisk(virDomainXMLOptionPtr xmlopt, def->type = VIR_DOMAIN_DISK_TYPE_NETWORK; def->protocol = VIR_DOMAIN_DISK_PROTOCOL_SHEEPDOG; - def->src = strdup(p + strlen("sheepdog:")); - if (!def->src) { - virReportOOMError(); + if (VIR_STRDUP(def->src, p + strlen("sheepdog:")) < 0) goto error; - } /* def->src must be [vdiname] or [host]:[port]:[vdiname] */ port = strchr(def->src, ':'); @@ -8615,18 +8584,12 @@ qemuParseCommandLineDisk(virDomainXMLOptionPtr xmlopt, } def->nhosts = 1; def->hosts->name = def->src; - def->hosts->port = strdup(port); - if (!def->hosts->port) { - virReportOOMError(); + if (VIR_STRDUP(def->hosts->port, port) < 0) goto error; - } def->hosts->transport = VIR_DOMAIN_DISK_PROTO_TRANS_TCP; def->hosts->socket = NULL; - def->src = strdup(vdi); - if (!def->src) { - virReportOOMError(); + if (VIR_STRDUP(def->src, vdi) < 0) goto error; - } } VIR_FREE(p); @@ -8651,11 +8614,8 @@ qemuParseCommandLineDisk(virDomainXMLOptionPtr xmlopt, } else if (STREQ(values[i], "floppy")) def->device = VIR_DOMAIN_DISK_DEVICE_FLOPPY; } else if (STREQ(keywords[i], "format")) { - def->driverName = strdup("qemu"); - if (!def->driverName) { - virReportOOMError(); + if (VIR_STRDUP(def->driverName, "qemu") < 0) goto error; - } def->format = virStorageFileFormatTypeFromString(values[i]); } else if (STREQ(keywords[i], "cache")) { if (STREQ(values[i], "off") || @@ -8795,21 +8755,19 @@ qemuParseCommandLineDisk(virDomainXMLOptionPtr xmlopt, } if (def->bus == VIR_DOMAIN_DISK_BUS_IDE) { - def->dst = strdup("hda"); + ignore_value(VIR_STRDUP(def->dst, "hda")); } else if (def->bus == VIR_DOMAIN_DISK_BUS_SCSI) { - def->dst = strdup("sda"); + ignore_value(VIR_STRDUP(def->dst, "sda")); } else if (def->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) { - def->dst = strdup("vda"); + ignore_value(VIR_STRDUP(def->dst, "vda")); } else if (def->bus == VIR_DOMAIN_DISK_BUS_XEN) { - def->dst = strdup("xvda"); + ignore_value(VIR_STRDUP(def->dst, "xvda")); } else { - def->dst = strdup("hda"); + ignore_value(VIR_STRDUP(def->dst, "hda")); } - if (!def->dst) { - virReportOOMError(); + if (!def->dst) goto error; - } if (STREQ(def->dst, "xvda")) def->dst[3] = 'a' + idx; else @@ -9161,14 +9119,12 @@ qemuParseCommandLineChr(virDomainChrSourceDefPtr source, source->type = VIR_DOMAIN_CHR_TYPE_PTY; } else if (STRPREFIX(val, "file:")) { source->type = VIR_DOMAIN_CHR_TYPE_FILE; - source->data.file.path = strdup(val+strlen("file:")); - if (!source->data.file.path) - goto no_memory; + if (VIR_STRDUP(source->data.file.path, val+strlen("file:")) < 0) + goto error; } else if (STRPREFIX(val, "pipe:")) { source->type = VIR_DOMAIN_CHR_TYPE_PIPE; - source->data.file.path = strdup(val+strlen("pipe:")); - if (!source->data.file.path) - goto no_memory; + if (VIR_STRDUP(source->data.file.path, val+strlen("pipe:")) < 0) + goto error; } else if (STREQ(val, "stdio")) { source->type = VIR_DOMAIN_CHR_TYPE_STDIO; } else if (STRPREFIX(val, "udp:")) { @@ -9179,40 +9135,32 @@ qemuParseCommandLineChr(virDomainChrSourceDefPtr source, host2 = svc1 ? strchr(svc1, '@') : NULL; svc2 = host2 ? strchr(host2, ':') : NULL; - if (svc1 && (svc1 != val)) { - source->data.udp.connectHost = strndup(val, svc1-val); - - if (!source->data.udp.connectHost) - goto no_memory; - } + if (svc1 && svc1 != val && + VIR_STRNDUP(source->data.udp.connectHost, val, svc1-val) < 0) + goto error; if (svc1) { svc1++; - if (host2) - source->data.udp.connectService = strndup(svc1, host2-svc1); - else - source->data.udp.connectService = strdup(svc1); - if (!source->data.udp.connectService) - goto no_memory; + if ((host2 && VIR_STRNDUP(source->data.udp.connectService, + svc1, host2 - svc1) < 0) || + (!host2 && VIR_STRDUP(source->data.udp.connectService, + svc1) < 0)) + goto error; } if (host2) { host2++; - if (svc2 && (svc2 != host2)) { - source->data.udp.bindHost = strndup(host2, svc2-host2); - - if (!source->data.udp.bindHost) - goto no_memory; - } + if (svc2 && svc2 != host2 && + VIR_STRNDUP(source->data.udp.bindHost, host2, svc2-host2) < 0) + goto no_memory; } if (svc2) { svc2++; if (STRNEQ(svc2, "0")) { - source->data.udp.bindService = strdup(svc2); - if (!source->data.udp.bindService) - goto no_memory; + if (VIR_STRDUP(source->data.udp.bindService, svc2) < 0) + goto error; } } } else if (STRPREFIX(val, "tcp:") || @@ -9235,37 +9183,25 @@ qemuParseCommandLineChr(virDomainChrSourceDefPtr source, if (opt && strstr(opt, "server")) source->data.tcp.listen = true; - source->data.tcp.host = strndup(val, svc-val); - if (!source->data.tcp.host) - goto no_memory; + if (VIR_STRNDUP(source->data.tcp.host, val, svc-val) < 0) + goto error; svc++; - if (opt) { - source->data.tcp.service = strndup(svc, opt-svc); - } else { - source->data.tcp.service = strdup(svc); - } - if (!source->data.tcp.service) - goto no_memory; + if ((opt && VIR_STRNDUP(source->data.tcp.service, svc, opt - svc) < 0) || + (!opt && VIR_STRDUP(source->data.tcp.service, svc) < 0)) + goto error; } else if (STRPREFIX(val, "unix:")) { const char *opt; val += strlen("unix:"); opt = strchr(val, ','); source->type = VIR_DOMAIN_CHR_TYPE_UNIX; - if (opt) { - if (strstr(opt, "listen")) - source->data.nix.listen = true; - source->data.nix.path = strndup(val, opt-val); - } else { - source->data.nix.path = strdup(val); - } - if (!source->data.nix.path) - goto no_memory; + if ((opt && VIR_STRNDUP(source->data.nix.path, val, opt - val) < 0) || + (!opt && VIR_STRDUP(source->data.nix.path, val) < 0)) + goto error; } else if (STRPREFIX(val, "/dev")) { source->type = VIR_DOMAIN_CHR_TYPE_DEV; - source->data.file.path = strdup(val); - if (!source->data.file.path) - goto no_memory; + if (VIR_STRDUP(source->data.file.path, val) < 0) + goto error; } else { virReportError(VIR_ERR_INTERNAL_ERROR, _("unknown character device syntax %s"), val); @@ -9318,13 +9254,9 @@ qemuParseCommandLineCPU(virDomainDefPtr dom, next++; if (p == val) { - if (next) - model = strndup(p, next - p - 1); - else - model = strdup(p); - - if (!model) - goto no_memory; + if ((next && VIR_STRNDUP(model, p, next - p -1) < 0) || + (!next && VIR_STRDUP(model, p) < 0)) + goto error; if (!STREQ(model, "qemu32") && !STREQ(model, "qemu64")) { if (!(cpu = qemuInitGuestCPU(dom))) @@ -9347,13 +9279,9 @@ qemuParseCommandLineCPU(virDomainDefPtr dom, if (*p == '\0' || *p == ',') goto syntax; - if (next) - feature = strndup(p, next - p - 1); - else - feature = strdup(p); - - if (!feature) - goto no_memory; + if ((next && VIR_STRNDUP(feature, p, next - p - 1) < 0) || + (!next && VIR_STRDUP(feature, p) < 0)) + goto error; if (STREQ(feature, "kvmclock")) { bool present = (policy == VIR_CPU_FEATURE_REQUIRE); @@ -9411,13 +9339,9 @@ qemuParseCommandLineCPU(virDomainDefPtr dom, if (*p == '\0' || *p == ',') goto syntax; - if (next) - feature = strndup(p, next - p - 1); - else - feature = strdup(p); - - if (!feature) - goto no_memory; + if ((next && VIR_STRNDUP(feature, p, next - p - 1) < 0) || + (!next && VIR_STRDUP(feature, p) < 0)) + goto error; dom->features |= (1 << VIR_DOMAIN_FEATURE_HYPERV); @@ -9635,8 +9559,8 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, def->onCrash = VIR_DOMAIN_LIFECYCLE_DESTROY; def->onPoweroff = VIR_DOMAIN_LIFECYCLE_DESTROY; def->virtType = VIR_DOMAIN_VIRT_QEMU; - if (!(def->emulator = strdup(progargv[0]))) - goto no_memory; + if (VIR_STRDUP(def->emulator, progargv[0]) < 0) + goto error; if (strstr(def->emulator, "kvm")) { def->virtType = VIR_DOMAIN_VIRT_KVM; @@ -9646,12 +9570,12 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, if (strstr(def->emulator, "xenner")) { def->virtType = VIR_DOMAIN_VIRT_KVM; - def->os.type = strdup("xen"); + if (VIR_STRDUP(def->os.type, "xen") < 0) + goto error; } else { - def->os.type = strdup("hvm"); + if (VIR_STRDUP(def->os.type, "hvm") < 0) + goto error; } - if (!def->os.type) - goto no_memory; if (STRPREFIX(def->emulator, "qemu")) path = def->emulator; @@ -9714,10 +9638,9 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, if (STRPREFIX(val, "unix:")) { /* -vnc unix:/some/big/path */ - vnc->data.vnc.socket = strdup(val + 5); - if (!vnc->data.vnc.socket) { + if (VIR_STRDUP(vnc->data.vnc.socket, val + 5) < 0) { virDomainGraphicsDefFree(vnc); - goto no_memory; + goto error; } } else { /* @@ -9810,9 +9733,8 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, disk->type = VIR_DOMAIN_DISK_TYPE_FILE; if (STREQ(arg, "-cdrom")) { disk->device = VIR_DOMAIN_DISK_DEVICE_CDROM; - disk->dst = strdup("hdc"); - if (!disk->dst) - goto no_memory; + if (VIR_STRDUP(disk->dst, "hdc") < 0) + goto error; disk->readonly = true; } else { if (STRPREFIX(arg, "-fd")) { @@ -9825,13 +9747,11 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, else disk->bus = VIR_DOMAIN_DISK_BUS_SCSI; } - disk->dst = strdup(arg + 1); - if (!disk->dst) - goto no_memory; + if (VIR_STRDUP(disk->dst, arg + 1) < 0) + goto error; } - disk->src = strdup(val); - if (!disk->src) - goto no_memory; + if (VIR_STRDUP(disk->src, val) < 0) + goto error; if (disk->type == VIR_DOMAIN_DISK_TYPE_NETWORK) { char *port; @@ -9864,12 +9784,10 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, goto no_memory; disk->nhosts = 1; disk->hosts->name = disk->src; - disk->hosts->port = strdup(port); - if (!disk->hosts->port) - goto no_memory; - disk->src = strdup(vdi); - if (!disk->src) - goto no_memory; + if (VIR_STRDUP(disk->hosts->port, port) < 0) + goto error; + if (VIR_STRDUP(disk->src, vdi) < 0) + goto error; } break; case VIR_DOMAIN_DISK_PROTOCOL_GLUSTER: @@ -9916,24 +9834,24 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, def->clock.offset = VIR_DOMAIN_CLOCK_OFFSET_LOCALTIME; } else if (STREQ(arg, "-kernel")) { WANT_VALUE(); - if (!(def->os.kernel = strdup(val))) - goto no_memory; + if (VIR_STRDUP(def->os.kernel, val) < 0) + goto error; } else if (STREQ(arg, "-bios")) { WANT_VALUE(); - if (!(def->os.loader = strdup(val))) - goto no_memory; + if (VIR_STRDUP(def->os.loader, val) < 0) + goto error; } else if (STREQ(arg, "-initrd")) { WANT_VALUE(); - if (!(def->os.initrd = strdup(val))) - goto no_memory; + if (VIR_STRDUP(def->os.initrd, val) < 0) + goto error; } else if (STREQ(arg, "-append")) { WANT_VALUE(); - if (!(def->os.cmdline = strdup(val))) - goto no_memory; + if (VIR_STRDUP(def->os.cmdline, val) < 0) + goto error; } else if (STREQ(arg, "-dtb")) { WANT_VALUE(); - if (!(def->os.dtb = strdup(val))) - goto no_memory; + if (VIR_STRDUP(def->os.dtb, val) < 0) + goto error; } else if (STREQ(arg, "-boot")) { const char *token = NULL; WANT_VALUE(); @@ -9977,11 +9895,11 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, WANT_VALUE(); process = strstr(val, ",process="); if (process == NULL) { - if (!(def->name = strdup(val))) - goto no_memory; + if (VIR_STRDUP(def->name, val) < 0) + goto error; } else { - if (!(def->name = strndup(val, process - val))) - goto no_memory; + if (VIR_STRNDUP(def->name, val, process - val) < 0) + goto error; } if (STREQ(def->name, "")) VIR_FREE(def->name); @@ -9991,11 +9909,11 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, WANT_VALUE(); params = strchr(val, ','); if (params == NULL) { - if (!(def->os.machine = strdup(val))) - goto no_memory; + if (VIR_STRDUP(def->os.machine, val) < 0) + goto error; } else { - if (!(def->os.machine = strndup(val, params - val))) - goto no_memory; + if (VIR_STRNDUP(def->os.machine, val, params - val) < 0) + goto error; while (params++) { /* prepared for more "-machine" parameters */ @@ -10004,11 +9922,8 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, if (STRPREFIX(tmp, "dump-guest-core=")) { tmp += strlen("dump-guest-core="); - if (params) { - tmp = strndup(tmp, params - tmp); - if (tmp == NULL) - goto no_memory; - } + if (params && VIR_STRNDUP(tmp, tmp, params - tmp) < 0) + goto error; def->mem.dump_core = virDomainMemDumpTypeFromString(tmp); if (def->mem.dump_core <= 0) def->mem.dump_core = VIR_DOMAIN_MEM_DUMP_DEFAULT; @@ -10077,17 +9992,17 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, } else if (STRPREFIX(val, "disk:")) { if (VIR_ALLOC(disk) < 0) goto no_memory; - disk->src = strdup(val + strlen("disk:")); - if (!disk->src) - goto no_memory; + if (VIR_STRDUP(disk->src, val + strlen("disk:")) < 0) + goto error; if (STRPREFIX(disk->src, "/dev/")) disk->type = VIR_DOMAIN_DISK_TYPE_BLOCK; else disk->type = VIR_DOMAIN_DISK_TYPE_FILE; disk->device = VIR_DOMAIN_DISK_DEVICE_DISK; disk->bus = VIR_DOMAIN_DISK_BUS_USB; - if (!(disk->dst = strdup("sda")) || - VIR_REALLOC_N(def->disks, def->ndisks+1) < 0) + if (VIR_STRDUP(disk->dst, "sda") < 0) + goto error; + if (VIR_REALLOC_N(def->disks, def->ndisks+1) < 0) goto no_memory; def->disks[def->ndisks++] = disk; disk = NULL; @@ -10189,9 +10104,8 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, def->watchdog->action = action; } else if (STREQ(arg, "-bootloader")) { WANT_VALUE(); - def->os.bootloader = strdup(val); - if (!def->os.bootloader) - goto no_memory; + if (VIR_STRDUP(def->os.bootloader, val) < 0) + goto error; } else if (STREQ(arg, "-vmwarevga")) { video = VIR_DOMAIN_VIDEO_TYPE_VMVGA; } else if (STREQ(arg, "-std-vga")) { @@ -10224,8 +10138,8 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, } else if (STREQ(arg, "-pidfile")) { WANT_VALUE(); if (pidfile) - if (!(*pidfile = strdup(val))) - goto no_memory; + if (VIR_STRDUP(*pidfile, val) < 0) + goto error; } else if (STREQ(arg, "-incoming")) { WANT_VALUE(); /* ignore, used via restore/migrate APIs */ @@ -10307,9 +10221,8 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, arg); if (VIR_REALLOC_N(cmd->args, cmd->num_args+1) < 0) goto no_memory; - cmd->args[cmd->num_args] = strdup(arg); - if (cmd->args[cmd->num_args] == NULL) - goto no_memory; + if (VIR_STRDUP(cmd->args[cmd->num_args], arg) < 0) + goto error; cmd->num_args++; } } @@ -10338,9 +10251,8 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, _("could not parse CEPH_ARGS '%s'"), ceph_args); goto error; } - hosts = strdup(strchr(ceph_args, ' ') + 1); - if (!hosts) - goto no_memory; + if (VIR_STRDUP(hosts, strchr(ceph_args, ' ') + 1) < 0) + goto error; first_rbd_disk->nhosts = 0; token = strtok_r(hosts, ",", &saveptr); while (token != NULL) { @@ -10351,17 +10263,16 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, port = strchr(token, ':'); if (port) { *port++ = '\0'; - port = strdup(port); - if (!port) { + if (VIR_STRDUP(port, port) < 0) { VIR_FREE(hosts); - goto no_memory; + goto error; } } first_rbd_disk->hosts[first_rbd_disk->nhosts].port = port; - first_rbd_disk->hosts[first_rbd_disk->nhosts].name = strdup(token); - if (!first_rbd_disk->hosts[first_rbd_disk->nhosts].name) { + if (VIR_STRDUP(first_rbd_disk->hosts[first_rbd_disk->nhosts].name, + token) < 0) { VIR_FREE(hosts); - goto no_memory; + goto error; } first_rbd_disk->hosts[first_rbd_disk->nhosts].transport = VIR_DOMAIN_DISK_PROTO_TRANS_TCP; first_rbd_disk->hosts[first_rbd_disk->nhosts].socket = NULL; @@ -10385,8 +10296,8 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, def->os.arch, virDomainVirtTypeToString(def->virtType)); if (defaultMachine != NULL) - if (!(def->os.machine = strdup(defaultMachine))) - goto no_memory; + if (VIR_STRDUP(def->os.machine, defaultMachine) < 0) + goto error; } if (!nographics && def->ngraphics == 0) { @@ -10398,14 +10309,14 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, sdl->type = VIR_DOMAIN_GRAPHICS_TYPE_SDL; sdl->data.sdl.fullscreen = fullscreen; if (display && - !(sdl->data.sdl.display = strdup(display))) { + VIR_STRDUP(sdl->data.sdl.display, display) < 0) { VIR_FREE(sdl); - goto no_memory; + goto error; } if (xauth && - !(sdl->data.sdl.xauth = strdup(xauth))) { + VIR_STRDUP(sdl->data.sdl.xauth, xauth) < 0) { VIR_FREE(sdl); - goto no_memory; + goto error; } if (VIR_REALLOC_N(def->graphics, def->ngraphics+1) < 0) { @@ -10522,7 +10433,7 @@ static int qemuParseProcFileStrings(int pid_value, ssize_t len; char *tmp; size_t nstr = 0; - const char **str = NULL; + char **str = NULL; int i; if (virAsprintf(&path, "/proc/%d/%s", pid_value, name) < 0) { @@ -10540,10 +10451,8 @@ static int qemuParseProcFileStrings(int pid_value, goto cleanup; } - if (!(str[nstr-1] = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(str[nstr-1], tmp) < 0) goto cleanup; - } /* Skip arg */ tmp += strlen(tmp); /* Skip \0 separator */ @@ -10558,7 +10467,7 @@ static int qemuParseProcFileStrings(int pid_value, str[nstr-1] = NULL; ret = nstr-1; - *list = str; + *list = (const char **) str; cleanup: if (ret < 0) { diff --git a/src/qemu/qemu_conf.c b/src/qemu/qemu_conf.c index c16b90d..11ff61f 100644 --- a/src/qemu/qemu_conf.c +++ b/src/qemu/qemu_conf.c @@ -140,8 +140,8 @@ virQEMUDriverConfigPtr virQEMUDriverConfigNew(bool privileged) "%s/log/libvirt/qemu", LOCALSTATEDIR) < 0) goto no_memory; - if ((cfg->configBaseDir = strdup(SYSCONFDIR "/libvirt")) == NULL) - goto no_memory; + if (VIR_STRDUP(cfg->configBaseDir, SYSCONFDIR "/libvirt") < 0) + goto error; if (virAsprintf(&cfg->stateDir, "%s/run/libvirt/qemu", LOCALSTATEDIR) < 0) @@ -210,19 +210,17 @@ virQEMUDriverConfigPtr virQEMUDriverConfigNew(bool privileged) goto no_memory; - if (!(cfg->vncListen = strdup("127.0.0.1"))) - goto no_memory; + if (VIR_STRDUP(cfg->vncListen, "127.0.0.1") < 0) + goto error; - if (!(cfg->vncTLSx509certdir - = strdup(SYSCONFDIR "/pki/libvirt-vnc"))) - goto no_memory; + if (VIR_STRDUP(cfg->vncTLSx509certdir, SYSCONFDIR "/pki/libvirt-vnc") < 0) + goto error; - if (!(cfg->spiceListen = strdup("127.0.0.1"))) - goto no_memory; + if (VIR_STRDUP(cfg->spiceListen, "127.0.0.1") < 0) + goto error; - if (!(cfg->spiceTLSx509certdir - = strdup(SYSCONFDIR "/pki/libvirt-spice"))) - goto no_memory; + if (VIR_STRDUP(cfg->spiceTLSx509certdir , SYSCONFDIR "/pki/libvirt-spice") < 0) + goto error; cfg->remotePortMin = QEMU_REMOTE_PORT_MIN; cfg->remotePortMax = QEMU_REMOTE_PORT_MAX; @@ -240,8 +238,8 @@ virQEMUDriverConfigPtr virQEMUDriverConfigNew(bool privileged) } } #endif - if (!(cfg->bridgeHelperName = strdup("/usr/libexec/qemu-bridge-helper"))) - goto no_memory; + if (VIR_STRDUP(cfg->bridgeHelperName, "/usr/libexec/qemu-bridge-helper") < 0) + goto error; cfg->clearEmulatorCapabilities = true; @@ -347,8 +345,8 @@ int virQEMUDriverConfigLoadFile(virQEMUDriverConfigPtr cfg, CHECK_TYPE(NAME, VIR_CONF_STRING); \ if (p && p->str) { \ VIR_FREE(VAR); \ - if (!(VAR = strdup(p->str))) \ - goto no_memory; \ + if (VIR_STRDUP(VAR, p->str) < 0) \ + goto cleanup; \ } GET_VALUE_BOOL("vnc_auto_unix_socket", cfg->vncAutoUnixSocket); @@ -379,16 +377,17 @@ int virQEMUDriverConfigLoadFile(virQEMUDriverConfigPtr cfg, goto no_memory; for (i = 0, pp = p->list; pp; i++, pp = pp->next) { - if (!(cfg->securityDriverNames[i] = strdup(pp->str))) - goto no_memory; + if (VIR_STRDUP(cfg->securityDriverNames[i], pp->str) < 0) + goto cleanup; } cfg->securityDriverNames[len] = NULL; } else { CHECK_TYPE("security_driver", VIR_CONF_STRING); if (p && p->str) { - if (VIR_ALLOC_N(cfg->securityDriverNames, 2) < 0 || - !(cfg->securityDriverNames[0] = strdup(p->str))) + if (VIR_ALLOC_N(cfg->securityDriverNames, 2) < 0) goto no_memory; + if (VIR_STRDUP(cfg->securityDriverNames[0], p->str) < 0) + goto cleanup; cfg->securityDriverNames[1] = NULL; } @@ -486,8 +485,8 @@ int virQEMUDriverConfigLoadFile(virQEMUDriverConfigPtr cfg, "list of strings")); goto cleanup; } - if (!(cfg->cgroupDeviceACL[i] = strdup(pp->str))) - goto no_memory; + if (VIR_STRDUP(cfg->cgroupDeviceACL[i], pp->str) < 0) + goto cleanup; } cfg->cgroupDeviceACL[i] = NULL; } @@ -586,10 +585,9 @@ virCapsPtr virQEMUDriverCreateCapabilities(virQEMUDriverPtr driver) for (i = 0; sec_managers[i]; i++) { doi = virSecurityManagerGetDOI(sec_managers[i]); model = virSecurityManagerGetModel(sec_managers[i]); - if (!(caps->host.secModels[i].model = strdup(model))) - goto no_memory; - if (!(caps->host.secModels[i].doi = strdup(doi))) - goto no_memory; + if (VIR_STRDUP(caps->host.secModels[i].model, model) < 0 || + VIR_STRDUP(caps->host.secModels[i].doi, doi) < 0) + goto error; VIR_DEBUG("Initialized caps for security driver \"%s\" with " "DOI \"%s\"", model, doi); } @@ -1070,10 +1068,8 @@ qemuSharedDiskEntryCopy(const qemuSharedDiskEntryPtr entry) } for (i = 0; i < entry->ref; i++) { - if (!(ret->domains[i] = strdup(entry->domains[i]))) { - virReportOOMError(); + if (VIR_STRDUP(ret->domains[i], entry->domains[i]) < 0) goto cleanup; - } ret->ref++; } @@ -1135,7 +1131,7 @@ qemuAddSharedDisk(virQEMUDriverPtr driver, goto cleanup; if ((VIR_EXPAND_N(new_entry->domains, new_entry->ref, 1) < 0) || - !(new_entry->domains[new_entry->ref - 1] = strdup(name))) { + VIR_STRDUP(new_entry->domains[new_entry->ref - 1], name) < 0) { qemuSharedDiskEntryFree(new_entry, NULL); virReportOOMError(); goto cleanup; @@ -1148,7 +1144,7 @@ qemuAddSharedDisk(virQEMUDriverPtr driver, } else { if ((VIR_ALLOC(entry) < 0) || (VIR_ALLOC_N(entry->domains, 1) < 0) || - !(entry->domains[0] = strdup(name))) { + VIR_STRDUP(entry->domains[0], name) < 0) { qemuSharedDiskEntryFree(entry, NULL); virReportOOMError(); goto cleanup; diff --git a/src/qemu/qemu_domain.c b/src/qemu/qemu_domain.c index 33088ea..6dc0436 100644 --- a/src/qemu/qemu_domain.c +++ b/src/qemu/qemu_domain.c @@ -730,14 +730,10 @@ qemuDomainDeviceDefPostParse(virDomainDeviceDefPtr dev, if (dev->type == VIR_DOMAIN_DEVICE_NET && dev->data.net->type != VIR_DOMAIN_NET_TYPE_HOSTDEV && !dev->data.net->model) { - if (def->os.arch == VIR_ARCH_S390 || - def->os.arch == VIR_ARCH_S390X) - dev->data.net->model = strdup("virtio"); - else - dev->data.net->model = strdup("rtl8139"); - - if (!dev->data.net->model) - goto no_memory; + if (VIR_STRDUP(dev->data.net->model, + def->os.arch == VIR_ARCH_S390 || + def->os.arch == VIR_ARCH_S390X ? "virtio" : "rtl8139") < 0) + goto cleanup; } /* set default disk types and drivers */ @@ -761,8 +757,8 @@ qemuDomainDeviceDefPostParse(virDomainDeviceDefPtr dev, } else { /* default driver if probing is forbidden */ if (!disk->driverName && - !(disk->driverName = strdup("qemu"))) - goto no_memory; + VIR_STRDUP(disk->driverName, "qemu") < 0) + goto cleanup; /* default disk format for drives */ if (disk->format == VIR_STORAGE_FILE_NONE && @@ -804,8 +800,10 @@ qemuDomainDeviceDefPostParse(virDomainDeviceDefPtr dev, if (virAsprintf(&dev->data.chr->source.data.nix.path, "%s/channel/target/%s.%s", cfg->libDir, def->name, - dev->data.chr->target.name) < 0) - goto no_memory; + dev->data.chr->target.name) < 0) { + virReportOOMError(); + goto cleanup; + } dev->data.chr->source.data.nix.listen = true; } @@ -814,10 +812,6 @@ qemuDomainDeviceDefPostParse(virDomainDeviceDefPtr dev, cleanup: virObjectUnref(cfg); return ret; - -no_memory: - virReportOOMError(); - goto cleanup; } diff --git a/src/qemu/qemu_driver.c b/src/qemu/qemu_driver.c index d5d7de3..feaf49a 100644 --- a/src/qemu/qemu_driver.c +++ b/src/qemu/qemu_driver.c @@ -1441,10 +1441,8 @@ qemuCanonicalizeMachine(virDomainDefPtr def, virQEMUCapsPtr qemuCaps) if (STRNEQ(canon, def->os.machine)) { char *tmp; - if (!(tmp = strdup(canon))) { - virReportOOMError(); + if (VIR_STRDUP(tmp, canon) < 0) return -1; - } VIR_FREE(def->os.machine); def->os.machine = tmp; } @@ -2014,8 +2012,7 @@ static char *qemuDomainGetOSType(virDomainPtr dom) { if (!(vm = qemuDomObjFromDomain(dom))) goto cleanup; - if (!(type = strdup(vm->def->os.type))) - virReportOOMError(); + ignore_value(VIR_STRDUP(type, vm->def->os.type)); cleanup: if (vm) @@ -3392,7 +3389,7 @@ qemuDomainScreenshot(virDomainPtr dom, goto endjob; } - ret = strdup("image/x-portable-pixmap"); + ignore_value(VIR_STRDUP(ret, "image/x-portable-pixmap")); endjob: VIR_FORCE_CLOSE(tmp_fd); @@ -5140,11 +5137,8 @@ static char *qemuConnectDomainXMLFromNative(virConnectPtr conn, if (!def) goto cleanup; - if (!def->name && - !(def->name = strdup("unnamed"))) { - virReportOOMError(); + if (!def->name && VIR_STRDUP(def->name, "unnamed") < 0) goto cleanup; - } xml = qemuDomainDefFormatXML(driver, def, VIR_DOMAIN_XML_INACTIVE); @@ -5210,11 +5204,9 @@ static char *qemuConnectDomainXMLToNative(virConnectPtr conn, if ((actualType == VIR_DOMAIN_NET_TYPE_BRIDGE) && (brname = virDomainNetGetActualBridgeName(net))) { - char *brnamecopy = strdup(brname); - if (!brnamecopy) { - virReportOOMError(); + char *brnamecopy; + if (VIR_STRDUP(brnamecopy, brname) < 0) goto cleanup; - } virDomainActualNetDefFree(net->data.network.actual); @@ -6634,9 +6626,7 @@ static char *qemuDomainGetSchedulerType(virDomainPtr dom, *nparams = 5; } - ret = strdup("posix"); - if (!ret) - virReportOOMError(); + ignore_value(VIR_STRDUP(ret, "posix")); cleanup: if (vm) @@ -6694,11 +6684,8 @@ qemuDomainParseDeviceWeightStr(char *deviceWeightStr, if (!p) goto error; - result[i].path = strndup(temp, p - temp); - if (!result[i].path) { - virReportOOMError(); + if (VIR_STRNDUP(result[i].path, temp, p - temp) < 0) goto cleanup; - } /* weight */ temp = p + 1; @@ -7062,13 +7049,8 @@ qemuDomainGetBlkioParameters(virDomainPtr dom, } param->value.s = virBufferContentAndReset(&buf); } - if (!param->value.s) { - param->value.s = strdup(""); - if (!param->value.s) { - virReportOOMError(); - goto cleanup; - } - } + if (!param->value.s && VIR_STRDUP(param->value.s, "") < 0) + goto cleanup; param->type = VIR_TYPED_PARAM_STRING; if (virStrcpyStatic(param->field, VIR_DOMAIN_BLKIO_DEVICE_WEIGHT) == NULL) { @@ -7590,8 +7572,8 @@ qemuDomainGetNumaParameters(virDomainPtr dom, case 1: /* fill numa nodeset here */ if (flags & VIR_DOMAIN_AFFECT_CONFIG) { nodeset = virBitmapFormat(persistentDef->numatune.memory.nodemask); - if (!nodeset) - nodeset = strdup(""); + if (!nodeset && VIR_STRDUP(nodeset, "") < 0) + goto cleanup; } else { rc = virCgroupGetCpusetMems(priv->cgroup, &nodeset); if (rc != 0) { @@ -10582,9 +10564,8 @@ qemuDomainSnapshotCreateInactiveExternal(virQEMUDriverPtr driver, if (snapdisk->snapshot == VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL) { VIR_FREE(defdisk->src); - if (!(defdisk->src = strdup(snapdisk->file))) { + if (VIR_STRDUP(defdisk->src, snapdisk->file) < 0) { /* we cannot rollback here in a sane way */ - virReportOOMError(); goto cleanup; } defdisk->format = snapdisk->format; @@ -10873,9 +10854,8 @@ qemuDomainSnapshotCreateSingleDiskActive(virQEMUDriverPtr driver, } if (virAsprintf(&device, "drive-%s", disk->info.alias) < 0 || - !(source = strdup(snap->file)) || - (persistDisk && - !(persistSource = strdup(source)))) { + VIR_STRDUP(source, snap->file) < 0 || + (persistDisk && VIR_STRDUP(persistSource, source) < 0)) { virReportOOMError(); goto cleanup; } @@ -10952,12 +10932,9 @@ qemuDomainSnapshotUndoSingleDiskActive(virQEMUDriverPtr driver, char *persistSource = NULL; struct stat st; - if (!(source = strdup(origdisk->src)) || - (persistDisk && - !(persistSource = strdup(source)))) { - virReportOOMError(); + if (VIR_STRDUP(source, origdisk->src) < 0 || + (persistDisk && VIR_STRDUP(persistSource, source) < 0)) goto cleanup; - } qemuDomainPrepareDiskChainElement(driver, vm, disk, origdisk->src, VIR_DISK_CHAIN_NO_ACCESS); @@ -11561,13 +11538,9 @@ qemuDomainSnapshotCreateXML(virDomainPtr domain, if (update_current) snap->def->current = true; if (vm->current_snapshot) { - if (!(flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE)) { - snap->def->parent = strdup(vm->current_snapshot->def->name); - if (snap->def->parent == NULL) { - virReportOOMError(); + if (!(flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) && + VIR_STRDUP(snap->def->parent, vm->current_snapshot->def->name) < 0) goto cleanup; - } - } if (update_current) { vm->current_snapshot->def->current = false; if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot, @@ -12346,14 +12319,10 @@ qemuDomainSnapshotReparentChildren(void *payload, VIR_FREE(snap->def->parent); snap->parent = rep->parent; - if (rep->parent->def) { - snap->def->parent = strdup(rep->parent->def->name); - - if (snap->def->parent == NULL) { - virReportOOMError(); - rep->err = -1; - return; - } + if (rep->parent->def && + VIR_STRDUP(snap->def->parent, rep->parent->def->name) < 0) { + rep->err = -1; + return; } if (!snap->sibling) @@ -13260,10 +13229,8 @@ qemuDomainBlockCopy(virDomainPtr dom, const char *path, } if (!format && disk->mirrorFormat > 0) format = virStorageFileFormatTypeToString(disk->mirrorFormat); - if (!(mirror = strdup(dest))) { - virReportOOMError(); + if (VIR_STRDUP(mirror, dest) < 0) goto endjob; - } if (qemuDomainPrepareDiskChainElement(driver, vm, disk, dest, VIR_DISK_CHAIN_READ_WRITE) < 0) { @@ -13894,10 +13861,8 @@ qemuDomainGetDiskErrors(virDomainPtr dom, if (n == nerrors) break; - if (!(errors[n].disk = strdup(disk->dst))) { - virReportOOMError(); + if (VIR_STRDUP(errors[n].disk, disk->dst) < 0) goto endjob; - } errors[n].error = info->io_status; n++; } @@ -13954,15 +13919,13 @@ qemuDomainSetMetadata(virDomainPtr dom, switch ((virDomainMetadataType) type) { case VIR_DOMAIN_METADATA_DESCRIPTION: VIR_FREE(vm->def->description); - if (metadata && - !(vm->def->description = strdup(metadata))) - goto no_memory; + if (metadata && VIR_STRDUP(vm->def->description, metadata) < 0) + goto cleanup; break; case VIR_DOMAIN_METADATA_TITLE: VIR_FREE(vm->def->title); - if (metadata && - !(vm->def->title = strdup(metadata))) - goto no_memory; + if (metadata && VIR_STRDUP(vm->def->title, metadata) < 0) + goto cleanup; break; case VIR_DOMAIN_METADATA_ELEMENT: virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", @@ -13982,15 +13945,13 @@ qemuDomainSetMetadata(virDomainPtr dom, switch ((virDomainMetadataType) type) { case VIR_DOMAIN_METADATA_DESCRIPTION: VIR_FREE(persistentDef->description); - if (metadata && - !(persistentDef->description = strdup(metadata))) - goto no_memory; + if (metadata && VIR_STRDUP(persistentDef->description, metadata) < 0) + goto cleanup; break; case VIR_DOMAIN_METADATA_TITLE: VIR_FREE(persistentDef->title); - if (metadata && - !(persistentDef->title = strdup(metadata))) - goto no_memory; + if (metadata && VIR_STRDUP(persistentDef->title, metadata) < 0) + goto cleanup; break; case VIR_DOMAIN_METADATA_ELEMENT: virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", @@ -14016,9 +13977,6 @@ cleanup: virObjectUnref(caps); virObjectUnref(cfg); return ret; -no_memory: - virReportOOMError(); - goto cleanup; } static char * @@ -14076,10 +14034,7 @@ qemuDomainGetMetadata(virDomainPtr dom, goto cleanup; } - if (!(ret = strdup(field))) { - virReportOOMError(); - goto cleanup; - } + ignore_value(VIR_STRDUP(ret, field)); cleanup: if (vm) diff --git a/src/qemu/qemu_hotplug.c b/src/qemu/qemu_hotplug.c index a4f48b0..c464712 100644 --- a/src/qemu/qemu_hotplug.c +++ b/src/qemu/qemu_hotplug.c @@ -1283,10 +1283,8 @@ qemuDomainNetGetBridgeName(virConnectPtr conn, virDomainNetDefPtr net) goto cleanup; } /* we need a copy, not just a pointer to the original */ - if (!(brname = strdup(tmpbr))) { - virReportOOMError(); + if (VIR_STRDUP(brname, tmpbr) < 0) goto cleanup; - } } else if (actualType == VIR_DOMAIN_NET_TYPE_NETWORK) { int active; virErrorPtr errobj; @@ -1539,11 +1537,8 @@ qemuDomainChangeNet(virQEMUDriverPtr driver, } /* ifname: check if it's set in newdev. If not, retain the autogenerated one */ - if (!(newdev->ifname || - (newdev->ifname = strdup(olddev->ifname)))) { - virReportOOMError(); + if (!newdev->ifname && VIR_STRDUP(newdev->ifname, olddev->ifname) < 0) goto cleanup; - } if (STRNEQ_NULLABLE(olddev->ifname, newdev->ifname)) { virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s", _("cannot modify network device tap name")); @@ -1568,11 +1563,9 @@ qemuDomainChangeNet(virQEMUDriverPtr driver, goto cleanup; } /* grab alias from olddev if not set in newdev */ - if (!(newdev->info.alias || - (newdev->info.alias = strdup(olddev->info.alias)))) { - virReportOOMError(); + if (!newdev->info.alias && + VIR_STRDUP(newdev->info.alias, olddev->info.alias) < 0) goto cleanup; - } if (STRNEQ_NULLABLE(olddev->info.alias, newdev->info.alias)) { virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s", _("cannot modify network device alias")); diff --git a/src/qemu/qemu_migration.c b/src/qemu/qemu_migration.c index 0732614..c69eea9 100644 --- a/src/qemu/qemu_migration.c +++ b/src/qemu/qemu_migration.c @@ -316,8 +316,8 @@ qemuMigrationCookieGraphicsAlloc(virQEMUDriverPtr driver, goto error; #endif } - if (!(mig->listen = strdup(listenAddr))) - goto no_memory; + if (VIR_STRDUP(mig->listen, listenAddr) < 0) + goto error; virObjectUnref(cfg); return mig; @@ -400,8 +400,8 @@ qemuMigrationCookieNew(virDomainObjPtr dom) name = priv->origname; else name = dom->def->name; - if (!(mig->name = strdup(name))) - goto no_memory; + if (VIR_STRDUP(mig->name, name) < 0) + goto error; memcpy(mig->uuid, dom->def->uuid, VIR_UUID_BUFLEN); if (!(mig->localHostname = virGetHostname(NULL))) @@ -460,15 +460,14 @@ qemuMigrationCookieAddLockstate(qemuMigrationCookiePtr mig, } if (virDomainObjGetState(dom, NULL) == VIR_DOMAIN_PAUSED) { - if (priv->lockState && - !(mig->lockState = strdup(priv->lockState))) + if (priv->lockState && VIR_STRDUP(mig->lockState, priv->lockState) < 0) return -1; } else { if (virDomainLockProcessInquire(driver->lockManager, dom, &mig->lockState) < 0) return -1; } - if (!(mig->lockDriver = strdup(virLockManagerPluginGetName(driver->lockManager)))) { + if (VIR_STRDUP(mig->lockDriver, virLockManagerPluginGetName(driver->lockManager)) < 0) { VIR_FREE(mig->lockState); return -1; } @@ -2050,8 +2049,7 @@ qemuMigrationPrepareAny(virQEMUDriverPtr driver, /* Target domain name, maybe renamed. */ if (dname) { origname = def->name; - def->name = strdup(dname); - if (def->name == NULL) + if (VIR_STRDUP(def->name, dname) < 0) goto cleanup; } @@ -2101,10 +2099,8 @@ qemuMigrationPrepareAny(virQEMUDriverPtr driver, /* QEMU will be started with -incoming stdio * (which qemu_command might convert to exec:cat or fd:n) */ - if (!(migrateFrom = strdup("stdio"))) { - virReportOOMError(); + if (VIR_STRDUP(migrateFrom, "stdio") < 0) goto cleanup; - } } else { virQEMUCapsPtr qemuCaps = NULL; struct addrinfo *info = NULL; diff --git a/src/qemu/qemu_monitor_json.c b/src/qemu/qemu_monitor_json.c index 6fdd650..50596ea 100644 --- a/src/qemu/qemu_monitor_json.c +++ b/src/qemu/qemu_monitor_json.c @@ -201,11 +201,9 @@ int qemuMonitorJSONIOProcess(qemuMonitorPtr mon, if (nl) { int got = nl - (data + used); - char *line = strndup(data + used, got); - if (!line) { - virReportOOMError(); + char *line; + if (VIR_STRNDUP(line, data + used, got) < 0) return -1; - } used += got + strlen(LINE_ENDING); line[got] = '\0'; /* kill \n */ if (qemuMonitorJSONIOProcessLine(mon, line, msg) < 0) { @@ -958,15 +956,9 @@ qemuMonitorJSONHumanCommandWithFd(qemuMonitorPtr mon, if (reply_str) { const char *data; - if ((data = virJSONValueGetString(obj))) - *reply_str = strdup(data); - else - *reply_str = strdup(""); - - if (!*reply_str) { - virReportOOMError(); + data = virJSONValueGetString(obj); + if (VIR_STRDUP(*reply_str, data ? data : "") < 0) goto cleanup; - } } ret = 0; @@ -2946,11 +2938,9 @@ static int qemuMonitorJSONExtractPtyPaths(virJSONValuePtr reply, } if (STRPREFIX(type, "pty:")) { - char *path = strdup(type + strlen("pty:")); - if (!path) { - virReportOOMError(); + char *path; + if (VIR_STRDUP(path, type + strlen("pty:")) < 0) goto cleanup; - } if (virHashAddEntry(paths, id, path) < 0) { virReportError(VIR_ERR_OPERATION_FAILED, @@ -3925,10 +3915,8 @@ int qemuMonitorJSONGetVersion(qemuMonitorPtr mon, _("query-version reply was missing 'package' version")); goto cleanup; } - if (!(*package = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(*package, tmp) < 0) goto cleanup; - } } ret = 0; @@ -4001,10 +3989,8 @@ int qemuMonitorJSONGetMachines(qemuMonitorPtr mon, goto cleanup; } - if (!(info->name = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(info->name, tmp) < 0) goto cleanup; - } if (virJSONValueObjectHasKey(child, "is-default") && virJSONValueObjectGetBoolean(child, "is-default", &info->isDefault) < 0) { @@ -4019,10 +4005,8 @@ int qemuMonitorJSONGetMachines(qemuMonitorPtr mon, _("query-machines reply has malformed 'alias' data")); goto cleanup; } - if (!(info->alias = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(info->alias, tmp) < 0) goto cleanup; - } } } @@ -4106,10 +4090,8 @@ int qemuMonitorJSONGetCPUDefinitions(qemuMonitorPtr mon, goto cleanup; } - if (!(cpulist[i] = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(cpulist[i], tmp) < 0) goto cleanup; - } } ret = n; @@ -4180,10 +4162,8 @@ int qemuMonitorJSONGetCommands(qemuMonitorPtr mon, goto cleanup; } - if (!(commandlist[i] = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(commandlist[i], tmp) < 0) goto cleanup; - } } ret = n; @@ -4259,10 +4239,8 @@ int qemuMonitorJSONGetEvents(qemuMonitorPtr mon, goto cleanup; } - if (!(eventlist[i] = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(eventlist[i], tmp) < 0) goto cleanup; - } } ret = n; @@ -4384,10 +4362,8 @@ int qemuMonitorJSONGetObjectTypes(qemuMonitorPtr mon, goto cleanup; } - if (!(typelist[i] = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(typelist[i], tmp) < 0) goto cleanup; - } } ret = n; @@ -4466,10 +4442,8 @@ int qemuMonitorJSONGetObjectProps(qemuMonitorPtr mon, goto cleanup; } - if (!(proplist[i] = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(proplist[i], tmp) < 0) goto cleanup; - } } ret = n; @@ -4520,10 +4494,7 @@ qemuMonitorJSONGetTargetArch(qemuMonitorPtr mon) goto cleanup; } - if (!(ret = strdup(arch))) { - virReportOOMError(); - goto cleanup; - } + ignore_value(VIR_STRDUP(ret, arch)); cleanup: virJSONValueFree(cmd); @@ -4817,10 +4788,8 @@ qemuMonitorJSONGetStringArray(qemuMonitorPtr mon, const char *qmpCmd, goto cleanup; } - if (!(list[i] = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(list[i], tmp) < 0) goto cleanup; - } } ret = n; diff --git a/src/qemu/qemu_monitor_text.c b/src/qemu/qemu_monitor_text.c index 696961b..acc8a12 100644 --- a/src/qemu/qemu_monitor_text.c +++ b/src/qemu/qemu_monitor_text.c @@ -258,11 +258,8 @@ qemuMonitorTextCommandWithHandler(qemuMonitorPtr mon, if (msg.rxBuffer) { *reply = msg.rxBuffer; } else { - *reply = strdup(""); - if (!*reply) { - virReportOOMError(); + if (VIR_STRDUP(*reply, "") < 0) return -1; - } } } @@ -330,10 +327,8 @@ qemuMonitorSendDiskPassphrase(qemuMonitorPtr mon, /* Extra the path */ pathStart += strlen(DISK_ENCRYPTION_PREFIX); - if (!(path = strndup(pathStart, pathEnd - pathStart))) { - virReportOOMError(); + if (VIR_STRNDUP(path, pathStart, pathEnd - pathStart) < 0) return -1; - } /* Fetch the disk password if possible */ res = qemuMonitorGetDiskSecret(mon, @@ -2283,11 +2278,9 @@ int qemuMonitorTextGetPtyPaths(qemuMonitorPtr mon, /* Path is everything after needle to the end of the line */ *eol = '\0'; - char *path = strdup(needle + strlen(NEEDLE)); - if (path == NULL) { - virReportOOMError(); + char *path; + if (VIR_STRDUP(path, needle + strlen(NEEDLE)) < 0) goto cleanup; - } if (virHashAddEntry(paths, id, path) < 0) { virReportError(VIR_ERR_OPERATION_FAILED, diff --git a/src/qemu/qemu_process.c b/src/qemu/qemu_process.c index 3dd178c..2f2c92b 100644 --- a/src/qemu/qemu_process.c +++ b/src/qemu/qemu_process.c @@ -1000,16 +1000,16 @@ qemuProcessHandleGraphics(qemuMonitorPtr mon ATTRIBUTE_UNUSED, if (VIR_ALLOC(localAddr) < 0) goto no_memory; localAddr->family = localFamily; - if (!(localAddr->service = strdup(localService)) || - !(localAddr->node = strdup(localNode))) - goto no_memory; + if (VIR_STRDUP(localAddr->service, localService) < 0 || + VIR_STRDUP(localAddr->node, localNode) < 0) + goto error; if (VIR_ALLOC(remoteAddr) < 0) goto no_memory; remoteAddr->family = remoteFamily; - if (!(remoteAddr->service = strdup(remoteService)) || - !(remoteAddr->node = strdup(remoteNode))) - goto no_memory; + if (VIR_STRDUP(remoteAddr->service, remoteService) < 0 || + VIR_STRDUP(remoteAddr->node, remoteNode) < 0) + goto error; if (VIR_ALLOC(subject) < 0) goto no_memory; @@ -1017,17 +1017,17 @@ qemuProcessHandleGraphics(qemuMonitorPtr mon ATTRIBUTE_UNUSED, if (VIR_REALLOC_N(subject->identities, subject->nidentity+1) < 0) goto no_memory; subject->nidentity++; - if (!(subject->identities[subject->nidentity-1].type = strdup("x509dname")) || - !(subject->identities[subject->nidentity-1].name = strdup(x509dname))) - goto no_memory; + if (VIR_STRDUP(subject->identities[subject->nidentity-1].type, "x509dname") < 0 || + VIR_STRDUP(subject->identities[subject->nidentity-1].name, x509dname) < 0) + goto error; } if (saslUsername) { if (VIR_REALLOC_N(subject->identities, subject->nidentity+1) < 0) goto no_memory; subject->nidentity++; - if (!(subject->identities[subject->nidentity-1].type = strdup("saslUsername")) || - !(subject->identities[subject->nidentity-1].name = strdup(saslUsername))) - goto no_memory; + if (VIR_STRDUP(subject->identities[subject->nidentity-1].type, "saslUsername") < 0 || + VIR_STRDUP(subject->identities[subject->nidentity-1].name, saslUsername) < 0) + goto error; } virObjectLock(vm); @@ -1041,6 +1041,7 @@ qemuProcessHandleGraphics(qemuMonitorPtr mon ATTRIBUTE_UNUSED, no_memory: virReportOOMError(); +error: if (localAddr) { VIR_FREE(localAddr->service); VIR_FREE(localAddr->node); @@ -1480,11 +1481,8 @@ qemuProcessExtractTTYPath(const char *haystack, */ while (*tmp) { if (c_isspace(*tmp)) { - *path = strndup(dev, tmp-dev); - if (*path == NULL) { - virReportOOMError(); + if (VIR_STRNDUP(*path, dev, tmp-dev) < 0) return -1; - } /* ... now further update offset till we get EOL */ *offset = tmp - haystack; @@ -1539,12 +1537,8 @@ qemuProcessLookupPTYs(virDomainChrDefPtr *devices, } VIR_FREE(chr->source.data.file.path); - chr->source.data.file.path = strdup(path); - - if (chr->source.data.file.path == NULL) { - virReportOOMError(); + if (VIR_STRDUP(chr->source.data.file.path, path) < 0) return -1; - } } } @@ -2666,12 +2660,12 @@ qemuProcessUpdateState(virQEMUDriverPtr driver, virDomainObjPtr vm) if (state == VIR_DOMAIN_PAUSED && running) { newState = VIR_DOMAIN_RUNNING; newReason = VIR_DOMAIN_RUNNING_UNPAUSED; - msg = strdup("was unpaused"); + ignore_value(VIR_STRDUP(msg, "was unpaused")); } else if (state == VIR_DOMAIN_RUNNING && !running) { if (reason == VIR_DOMAIN_PAUSED_SHUTTING_DOWN) { newState = VIR_DOMAIN_SHUTDOWN; newReason = VIR_DOMAIN_SHUTDOWN_UNKNOWN; - msg = strdup("shutdown"); + ignore_value(VIR_STRDUP(msg, "shutdown")); } else { newState = VIR_DOMAIN_PAUSED; newReason = reason; @@ -2681,7 +2675,7 @@ qemuProcessUpdateState(virQEMUDriverPtr driver, virDomainObjPtr vm) } else if (state == VIR_DOMAIN_SHUTOFF && running) { newState = VIR_DOMAIN_RUNNING; newReason = VIR_DOMAIN_RUNNING_BOOTED; - msg = strdup("finished booting"); + ignore_value(VIR_STRDUP(msg, "finished booting")); } if (newState != VIR_DOMAIN_NOSTATE) { @@ -3479,13 +3473,10 @@ int qemuProcessStart(virConnectPtr conn, goto cleanup; } graphics->listens[0].type = VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS; - if (graphics->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC) - graphics->listens[0].address = strdup(cfg->vncListen); - else - graphics->listens[0].address = strdup(cfg->spiceListen); - if (!graphics->listens[0].address) { + if (VIR_STRDUP(graphics->listens[0].address, + graphics->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC ? + cfg->vncListen : cfg->spiceListen) < 0) { VIR_SHRINK_N(graphics->listens, graphics->nListens, 1); - virReportOOMError(); goto cleanup; } } @@ -4251,9 +4242,8 @@ int qemuProcessAttach(virConnectPtr conn ATTRIBUTE_UNUSED, } VIR_FREE(priv->pidfile); - if (pidfile && - !(priv->pidfile = strdup(pidfile))) - goto no_memory; + if (pidfile && VIR_STRDUP(priv->pidfile, pidfile) < 0) + goto cleanup; VIR_DEBUG("Detect security driver config"); sec_managers = virSecurityManagerGetNested(driver->securityManager); @@ -4274,11 +4264,11 @@ int qemuProcessAttach(virConnectPtr conn ATTRIBUTE_UNUSED, vm->def, vm->pid, seclabel) < 0) goto cleanup; - if (!(seclabeldef->model = strdup(model))) - goto no_memory; + if (VIR_STRDUP(seclabeldef->model, model) < 0) + goto cleanup; - if (!(seclabeldef->label = strdup(seclabel->label))) - goto no_memory; + if (VIR_STRDUP(seclabeldef->label, seclabel->label) < 0) + goto cleanup; VIR_FREE(seclabel); } diff --git a/src/remote/remote_driver.c b/src/remote/remote_driver.c index 13212d0..97be2a0 100644 --- a/src/remote/remote_driver.c +++ b/src/remote/remote_driver.c @@ -3733,7 +3733,7 @@ static int remoteAuthMakeCredentials(sasl_interact_t *interact, } if (interact[*ncred].challenge) (*cred)[*ncred].challenge = interact[ninteract].challenge; - (*cred)[*ncred].prompt = interact[ninteract].prompt; + (*cred)[*ncred].prompt = (char *) interact[ninteract].prompt; if (interact[*ncred].defresult) (*cred)[*ncred].defresult = interact[ninteract].defresult; (*cred)[*ncred].result = NULL; -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- include/libvirt/libvirt.h.in | 10 +- src/qemu/qemu_capabilities.c | 79 ++++---- src/qemu/qemu_cgroup.c | 4 +- src/qemu/qemu_command.c | 419 +++++++++++++++++-------------------------- src/qemu/qemu_conf.c | 58 +++--- src/qemu/qemu_domain.c | 26 ++- src/qemu/qemu_driver.c | 113 ++++-------- src/qemu/qemu_hotplug.c | 15 +- src/qemu/qemu_migration.c | 20 +-- src/qemu/qemu_monitor_json.c | 63 ++----- src/qemu/qemu_monitor_text.c | 15 +- src/qemu/qemu_process.c | 64 +++---- src/remote/remote_driver.c | 2 +- 13 files changed, 333 insertions(+), 555 deletions(-)
You don't mind if I save review for this till later, when I'm not as tired? It is one of the bigger patches, after all... And 17/34 puts us at the halfway mark :) Feel free to start pushing the easier patches and/or posting followups for the issues I've found so far, so we aren't forcing a respin of the entire series. One benefit of doing this early in the release cycle is we have more time to test things before freeze to make sure we aren't hitting obvious regressions. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- include/libvirt/libvirt.h.in | 10 +-
I think this file needs to be its own patch, because it has API considerations. More below.
src/qemu/qemu_capabilities.c | 79 ++++---- src/qemu/qemu_cgroup.c | 4 +- src/qemu/qemu_command.c | 419 +++++++++++++++++-------------------------- src/qemu/qemu_conf.c | 58 +++--- src/qemu/qemu_domain.c | 26 ++- src/qemu/qemu_driver.c | 113 ++++-------- src/qemu/qemu_hotplug.c | 15 +- src/qemu/qemu_migration.c | 20 +-- src/qemu/qemu_monitor_json.c | 63 ++----- src/qemu/qemu_monitor_text.c | 15 +- src/qemu/qemu_process.c | 64 +++---- src/remote/remote_driver.c | 2 +- 13 files changed, 333 insertions(+), 555 deletions(-)
diff --git a/include/libvirt/libvirt.h.in b/include/libvirt/libvirt.h.in index 693b834..9a8090d 100644 --- a/include/libvirt/libvirt.h.in +++ b/include/libvirt/libvirt.h.in @@ -1294,7 +1294,7 @@ typedef enum {
struct _virConnectCredential { int type; /* One of virConnectCredentialType constants */ - const char *prompt; /* Prompt to show to user */ + char *prompt; /* Prompt to show to user */
API change. Prior to this change, users passing a virConnectAuthCallbackPtr as part of their virConnectAuthPtr argument of virConnectOpenAuth could write that callback where they could modify the credential object passed to the callback. For example, I could do: int myCallback(virConnectCredentialPtr cred, unsigned int ncred, void *opaque) { cred->prompt = "new prompt"; return 0; } With your change, this will now fail to compile (attempt to assign a const char * into a char *). Granted, our documentation states that the callback writer should touch _only_ the result and resultlen field, but the fact that the user has to modify the incoming object at all means that the object itself has to declare which fields are input (with const) vs output. So I have no idea if someone writing such a callback handler is violating other aspects of code, and maybe our API break will never affect proper code; but at the same time, we make a strong promise of back-compat, and I'm reluctant to go back on that promise without strong reason. NACK to this change; API breaks are bad. Anywhere that we can't prep these fields using VIR_STRDUP (because VIR_STRDUP rightfully wants to assign to char*, not const char*), then we have to fix that code to do assignment in two parts (VIR_STRDUP into temporary char * var, then add const by assigning and/or casting into the callback struct we are populating).
@@ -4504,8 +4504,8 @@ typedef enum { */ struct _virDomainEventGraphicsAddress { int family; /* Address family, virDomainEventGraphicsAddressType */ - const char *node; /* Address of node (eg IP address, or UNIX path) */ - const char *service; /* Service name/number (eg TCP port, or NULL) */ + char *node; /* Address of node (eg IP address, or UNIX path) */ + char *service; /* Service name/number (eg TCP port, or NULL) */ }; typedef struct _virDomainEventGraphicsAddress virDomainEventGraphicsAddress; typedef virDomainEventGraphicsAddress *virDomainEventGraphicsAddressPtr; @@ -4520,8 +4520,8 @@ typedef virDomainEventGraphicsAddress *virDomainEventGraphicsAddressPtr; * some examples are 'x509dname' and 'saslUsername'. */ struct _virDomainEventGraphicsSubjectIdentity { - const char *type; /* Type of identity */ - const char *name; /* Identity value */ + char *type; /* Type of identity */ + char *name; /* Identity value */
I need to look more at how these structs are used, but I have the same concern of an API break. (ABI-wise, it is still compatible). But since these two structs don't mix const and non-const char*, we might be able to get away with these changes. Sending now, to get my NACK out on the table, while I spend more time reviewing the rest of the patch. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On 05/10/2013 12:11 PM, Eric Blake wrote:
On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- include/libvirt/libvirt.h.in | 10 +-
I think this file needs to be its own patch, because it has API considerations. More below.
@@ -4504,8 +4504,8 @@ typedef enum { */ struct _virDomainEventGraphicsAddress { int family; /* Address family, virDomainEventGraphicsAddressType */ - const char *node; /* Address of node (eg IP address, or UNIX path) */ - const char *service; /* Service name/number (eg TCP port, or NULL) */ + char *node; /* Address of node (eg IP address, or UNIX path) */ + char *service; /* Service name/number (eg TCP port, or NULL) */ }; typedef struct _virDomainEventGraphicsAddress virDomainEventGraphicsAddress; typedef virDomainEventGraphicsAddress *virDomainEventGraphicsAddressPtr; @@ -4520,8 +4520,8 @@ typedef virDomainEventGraphicsAddress *virDomainEventGraphicsAddressPtr; * some examples are 'x509dname' and 'saslUsername'. */ struct _virDomainEventGraphicsSubjectIdentity { - const char *type; /* Type of identity */ - const char *name; /* Identity value */ + char *type; /* Type of identity */ + char *name; /* Identity value */
I need to look more at how these structs are used, but I have the same concern of an API break. (ABI-wise, it is still compatible). But since these two structs don't mix const and non-const char*, we might be able to get away with these changes. Sending now, to get my NACK out on the table, while I spend more time reviewing the rest of the patch.
Here, I _think_ it would be okay to change: typedef void (*virConnectDomainEventGraphicsCallback)(virConnectPtr conn, virDomainPtr dom, int phase, virDomainEventGraphicsAddressPtr local, virDomainEventGraphicsAddressPtr remote, const char *authScheme, virDomainEventGraphicsSubjectPtr subject, void *opaque); to: typedef void (*virConnectDomainEventGraphicsCallback)(virConnectPtr conn, virDomainPtr dom, int phase, const virDomainEventGraphicsAddressPtr local, const virDomainEventGraphicsAddressPtr remote, const char *authScheme, const virDomainEventGraphicsSubjectPtr subject, void *opaque); Although this is an API change, I think that real callers won't be impacted. Why? 1. these callback members are read-only (unlike the ConnectCredential callback struct which was read-write), so it is less likely that someone is trying to assign into the struct members. 2. The only way to register a virConnectDomainEventGraphicsCallback is to cast it through a call to virConnectDomainEventRegisterAny. That is, even if the user's callback function leaves out the const, we never use the typedef as the direct type of any API parameter. Since they are already casting their function pointer into a munged type before registering it, their code will continue to compile. IF you agree with my reasoning about adding 'const' to this particular callback's signature, THEN we can also remove 'const' from the members within those types (that is, your patch did the THEN part; I'd be okay acking if you also add the IF part in the same commit, isolated to an independent patch since it touches user-visible declarations). We can't do that for ConnectCredential, because that type is used directly with no mandated user-casting, and because that type is read-write instead of read-only like these two types. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- include/libvirt/libvirt.h.in | 10 +- src/qemu/qemu_capabilities.c | 79 ++++---- src/qemu/qemu_cgroup.c | 4 +- src/qemu/qemu_command.c | 419 +++++++++++++++++-------------------------- src/qemu/qemu_conf.c | 58 +++--- src/qemu/qemu_domain.c | 26 ++- src/qemu/qemu_driver.c | 113 ++++-------- src/qemu/qemu_hotplug.c | 15 +- src/qemu/qemu_migration.c | 20 +-- src/qemu/qemu_monitor_json.c | 63 ++----- src/qemu/qemu_monitor_text.c | 15 +- src/qemu/qemu_process.c | 64 +++---- src/remote/remote_driver.c | 2 +- 13 files changed, 333 insertions(+), 555 deletions(-)
Part 3 - the qemu changes
+++ b/src/qemu/qemu_capabilities.c @@ -384,7 +384,8 @@ virQEMUCapsParseMachineTypesStr(const char *output, VIR_REALLOC_N(qemuCaps->machineAliases, qemuCaps->nmachineTypes + 1) < 0) { VIR_FREE(name); VIR_FREE(canonical);
Seems like we could move some of this cleanup...
- goto no_memory; + virReportOOMError(); + goto error; } qemuCaps->nmachineTypes++; if (canonical) { @@ -402,8 +403,7 @@ virQEMUCapsParseMachineTypesStr(const char *output,
return 0;
-no_memory: - virReportOOMError(); +error: return -1;
...here, so that we don't have a 'goto/return'. But that can be a separate patch (especially since you'll be revisiting VIR_REALLOC anyway).
@@ -1736,17 +1728,18 @@ virQEMUCapsPtr virQEMUCapsNewCopy(virQEMUCapsPtr qemuCaps) goto no_memory; ret->nmachineTypes = qemuCaps->nmachineTypes; for (i = 0 ; i < qemuCaps->nmachineTypes ; i++) { - if (!(ret->machineTypes[i] = strdup(qemuCaps->machineTypes[i]))) - goto no_memory; + if (VIR_STRDUP(ret->machineTypes[i], qemuCaps->machineTypes[i]) < 0) + goto error; if (qemuCaps->machineAliases[i] && - !(ret->machineAliases[i] = strdup(qemuCaps->machineAliases[i]))) - goto no_memory; + VIR_STRDUP(ret->machineAliases[i], qemuCaps->machineAliases[i]) < 0) + goto error;
Can be simplified with NULL source.
@@ -1897,12 +1889,12 @@ int virQEMUCapsGetMachineTypesCaps(virQEMUCapsPtr qemuCaps, if (VIR_ALLOC(mach) < 0) goto no_memory; if (qemuCaps->machineAliases[i]) { - if (!(mach->name = strdup(qemuCaps->machineAliases[i]))) + if (VIR_STRDUP(mach->name, qemuCaps->machineAliases[i]) < 0) goto no_memory;
double-oom, but I'm assuming you'll clean it later.
@@ -2091,16 +2083,11 @@ virQEMUCapsProbeQMPMachineTypes(virQEMUCapsPtr qemuCaps, }
for (i = 0 ; i < nmachines ; i++) { - if (machines[i]->alias) { - if (!(qemuCaps->machineAliases[i] = strdup(machines[i]->alias))) { - virReportOOMError(); - goto cleanup; - } - } - if (!(qemuCaps->machineTypes[i] = strdup(machines[i]->name))) { - virReportOOMError(); + if (machines[i]->alias && + VIR_STRDUP(qemuCaps->machineAliases[i], machines[i]->alias) < 0) + goto cleanup;
Can be simplified.
+++ b/src/qemu/qemu_command.c @@ -2418,13 +2404,11 @@ static int qemuAddRBDHost(virDomainDiskDefPtr disk, char *hostport) if (port) { *port = '\0'; port += skip; - disk->hosts[disk->nhosts-1].port = strdup(port); - if (!disk->hosts[disk->nhosts-1].port) - goto no_memory; + if (VIR_STRDUP(disk->hosts[disk->nhosts-1].port, port) < 0) + goto error; } else { - disk->hosts[disk->nhosts-1].port = strdup("6789"); - if (!disk->hosts[disk->nhosts-1].port) - goto no_memory; + if (VIR_STRDUP(disk->hosts[disk->nhosts-1].port, "6789") < 0)
Pre-existing, but space around '-' while touching this.
@@ -5456,9 +5430,10 @@ qemuBuildCpuArgStr(const virQEMUDriverPtr driver, } virBufferAddLit(&buf, "host"); } else { - if (VIR_ALLOC(guest) < 0 || - (cpu->vendor_id && !(guest->vendor_id = strdup(cpu->vendor_id)))) + if (VIR_ALLOC(guest) < 0) goto no_memory; + if (cpu->vendor_id && VIR_STRDUP(guest->vendor_id, cpu->vendor_id) < 0) + goto cleanup;
Can be simplified.
@@ -8312,17 +8287,16 @@ static int qemuStringToArgvEnv(const char *args, next = strchr(curr, '\n');
if (next) { - arg = strndup(curr, next-curr); + if (VIR_STRNDUP(arg, curr, next-curr) < 0) + goto error;
Space around '-' while touching this.
@@ -9161,14 +9119,12 @@ qemuParseCommandLineChr(virDomainChrSourceDefPtr source, source->type = VIR_DOMAIN_CHR_TYPE_PTY; } else if (STRPREFIX(val, "file:")) { source->type = VIR_DOMAIN_CHR_TYPE_FILE; - source->data.file.path = strdup(val+strlen("file:")); - if (!source->data.file.path) - goto no_memory; + if (VIR_STRDUP(source->data.file.path, val+strlen("file:")) < 0) + goto error; } else if (STRPREFIX(val, "pipe:")) { source->type = VIR_DOMAIN_CHR_TYPE_PIPE; - source->data.file.path = strdup(val+strlen("pipe:")); - if (!source->data.file.path) - goto no_memory; + if (VIR_STRDUP(source->data.file.path, val+strlen("pipe:")) < 0) + goto error;
Space around '+' while touching this
@@ -9179,40 +9135,32 @@ qemuParseCommandLineChr(virDomainChrSourceDefPtr source, host2 = svc1 ? strchr(svc1, '@') : NULL; svc2 = host2 ? strchr(host2, ':') : NULL;
You know, we could use strchrnul() here (guaranteed by gnulib)...
- if (svc1 && (svc1 != val)) { - source->data.udp.connectHost = strndup(val, svc1-val); - - if (!source->data.udp.connectHost) - goto no_memory; - } + if (svc1 && svc1 != val && + VIR_STRNDUP(source->data.udp.connectHost, val, svc1-val) < 0) + goto error;
Space around '-'
if (svc1) { svc1++; - if (host2) - source->data.udp.connectService = strndup(svc1, host2-svc1); - else - source->data.udp.connectService = strdup(svc1);
- if (!source->data.udp.connectService) - goto no_memory; + if ((host2 && VIR_STRNDUP(source->data.udp.connectService, + svc1, host2 - svc1) < 0) || + (!host2 && VIR_STRDUP(source->data.udp.connectService, + svc1) < 0)) + goto error;
...then here, we could simplify things to always be a strndup (host2 would always be non-null, either because it hit ':' or the end of the string). This whole function could be simplified by doing the string parse with a bit more smarts.
@@ -9235,37 +9183,25 @@ qemuParseCommandLineChr(virDomainChrSourceDefPtr source, if (opt && strstr(opt, "server")) source->data.tcp.listen = true;
- source->data.tcp.host = strndup(val, svc-val); - if (!source->data.tcp.host) - goto no_memory; + if (VIR_STRNDUP(source->data.tcp.host, val, svc-val) < 0) + goto error;
Spaces around '-'
svc++; - if (opt) { - source->data.tcp.service = strndup(svc, opt-svc); - } else { - source->data.tcp.service = strdup(svc); - } - if (!source->data.tcp.service) - goto no_memory; + if ((opt && VIR_STRNDUP(source->data.tcp.service, svc, opt - svc) < 0) || + (!opt && VIR_STRDUP(source->data.tcp.service, svc) < 0)) + goto error;
Another place where strchrnul probably helps.
@@ -9318,13 +9254,9 @@ qemuParseCommandLineCPU(virDomainDefPtr dom, next++;
if (p == val) { - if (next) - model = strndup(p, next - p - 1); - else - model = strdup(p); - - if (!model) - goto no_memory; + if ((next && VIR_STRNDUP(model, p, next - p -1) < 0) || + (!next && VIR_STRDUP(model, p) < 0)) + goto error;
I'll quit pointing out spots where strchrnul might help - at this point converting to use strchrnul is worth splitting into a separate cleanup patch (whether before or after this patch, I don't know which is easier).
@@ -10189,9 +10104,8 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps,
Shoot. I ran out of time for today. What I've seen so far in qemu is looking okay, though.
+++ b/src/remote/remote_driver.c @@ -3733,7 +3733,7 @@ static int remoteAuthMakeCredentials(sasl_interact_t *interact, } if (interact[*ncred].challenge) (*cred)[*ncred].challenge = interact[ninteract].challenge; - (*cred)[*ncred].prompt = interact[ninteract].prompt; + (*cred)[*ncred].prompt = (char *) interact[ninteract].prompt;
This one feels random (oh, it's associated with your proposed changes to libvirt.h, so it belongs to that patch, depending on what we decide there). -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/remote/remote_driver.c | 114 +++++++++++++++++---------------------------- 1 file changed, 44 insertions(+), 70 deletions(-) diff --git a/src/remote/remote_driver.c b/src/remote/remote_driver.c index 97be2a0..ed3467f 100644 --- a/src/remote/remote_driver.c +++ b/src/remote/remote_driver.c @@ -368,8 +368,8 @@ remoteClientCloseFunc(virNetClientPtr client ATTRIBUTE_UNUSED, #define EXTRACT_URI_ARG_STR(ARG_NAME, ARG_VAR) \ if (STRCASEEQ(var->name, ARG_NAME)) { \ VIR_FREE(ARG_VAR); \ - if (!(ARG_VAR = strdup(var->value))) \ - goto no_memory; \ + if (VIR_STRDUP(ARG_VAR, var->value) < 0) \ + goto failed; \ var->ignore = 1; \ continue; \ } @@ -497,24 +497,21 @@ doRemoteOpen(virConnectPtr conn, if (virAsprintf(&port, "%d", conn->uri->port) < 0) goto no_memory; } else if (transport == trans_tls) { - if (!(port = strdup(LIBVIRTD_TLS_PORT))) - goto no_memory; + if (VIR_STRDUP(port, LIBVIRTD_TLS_PORT) < 0) + goto failed; } else if (transport == trans_tcp) { - if (!(port = strdup(LIBVIRTD_TCP_PORT))) - goto no_memory; + if (VIR_STRDUP(port, LIBVIRTD_TCP_PORT) < 0) + goto failed; } /* Port not used for unix, ext., default for ssh */ - if (conn->uri && conn->uri->server) - priv->hostname = strdup(conn->uri->server); - else - priv->hostname = strdup("localhost"); - - if (!priv->hostname) - goto no_memory; + if (VIR_STRDUP(priv->hostname, + conn->uri && conn->uri->server ? + conn->uri->server : "localhost") < 0) + goto failed; if (conn->uri && conn->uri->user && - !(username = strdup(conn->uri->user))) - goto no_memory; + VIR_STRDUP(username, conn->uri->user) < 0) + goto failed; /* Get the variables from the query string. * Then we need to reconstruct the query string (because @@ -557,8 +554,8 @@ doRemoteOpen(virConnectPtr conn, (STREQ(conn->uri->scheme, "remote") || STRPREFIX(conn->uri->scheme, "remote+"))) { /* Allow remote serve to probe */ - if (!(name = strdup(""))) - goto no_memory; + if (VIR_STRDUP(name, "") < 0) + goto failed; } else { virURI tmpuri = { .scheme = conn->uri->scheme, @@ -587,8 +584,8 @@ doRemoteOpen(virConnectPtr conn, } } else { /* Probe URI server side */ - if (!(name = strdup(""))) - goto no_memory; + if (VIR_STRDUP(name, "") < 0) + goto failed; } VIR_DEBUG("proceeding with name = %s", name); @@ -635,15 +632,11 @@ doRemoteOpen(virConnectPtr conn, break; case trans_libssh2: - if (!sockname) { - if (flags & VIR_DRV_OPEN_REMOTE_RO) - sockname = strdup(LIBVIRTD_PRIV_UNIX_SOCKET_RO); - else - sockname = strdup(LIBVIRTD_PRIV_UNIX_SOCKET); - - if (sockname == NULL) - goto no_memory; - } + if (!sockname && + VIR_STRDUP(sockname, + flags & VIR_DRV_OPEN_REMOTE_RO ? + LIBVIRTD_PRIV_UNIX_SOCKET_RO : LIBVIRTD_PRIV_UNIX_SOCKET) < 0) + goto failed; VIR_DEBUG("Starting LibSSH2 session"); @@ -678,12 +671,10 @@ doRemoteOpen(virConnectPtr conn, } VIR_FREE(userdir); } else { - if (flags & VIR_DRV_OPEN_REMOTE_RO) - sockname = strdup(LIBVIRTD_PRIV_UNIX_SOCKET_RO); - else - sockname = strdup(LIBVIRTD_PRIV_UNIX_SOCKET); - if (sockname == NULL) - goto no_memory; + if (VIR_STRDUP(sockname, + flags & VIR_DRV_OPEN_REMOTE_RO ? + LIBVIRTD_PRIV_UNIX_SOCKET_RO : LIBVIRTD_PRIV_UNIX_SOCKET) < 0) + goto failed; } VIR_DEBUG("Proceeding with sockname %s", sockname); } @@ -705,17 +696,13 @@ doRemoteOpen(virConnectPtr conn, break; case trans_ssh: - if (!command && !(command = strdup("ssh"))) - goto no_memory; + if (!command && VIR_STRDUP(command, "ssh") < 0) + goto failed; - if (!sockname) { - if (flags & VIR_DRV_OPEN_REMOTE_RO) - sockname = strdup(LIBVIRTD_PRIV_UNIX_SOCKET_RO); - else - sockname = strdup(LIBVIRTD_PRIV_UNIX_SOCKET); - if (!sockname) - goto no_memory; - } + if (VIR_STRDUP(sockname, + flags & VIR_DRV_OPEN_REMOTE_RO ? + LIBVIRTD_PRIV_UNIX_SOCKET_RO : LIBVIRTD_PRIV_UNIX_SOCKET) < 0) + goto failed; if (!(priv->client = virNetClientNewSSH(priv->hostname, port, @@ -1493,11 +1480,8 @@ remoteSerializeTypedParameters(virTypedParameterPtr params, for (i = 0; i < nparams; ++i) { /* call() will free this: */ - val[i].field = strdup(params[i].field); - if (val[i].field == NULL) { - virReportOOMError(); + if (VIR_STRDUP(val[i].field, params[i].field) < 0) goto cleanup; - } val[i].value.type = params[i].type; switch (params[i].type) { case VIR_TYPED_PARAM_INT: @@ -1519,11 +1503,9 @@ remoteSerializeTypedParameters(virTypedParameterPtr params, val[i].value.remote_typed_param_value_u.b = params[i].value.b; break; case VIR_TYPED_PARAM_STRING: - val[i].value.remote_typed_param_value_u.s = strdup(params[i].value.s); - if (val[i].value.remote_typed_param_value_u.s == NULL) { - virReportOOMError(); + if (VIR_STRDUP(val[i].value.remote_typed_param_value_u.s, + params[i].value.s) < 0) goto cleanup; - } break; default: virReportError(VIR_ERR_RPC, _("unknown parameter type: %d"), @@ -1608,12 +1590,9 @@ remoteDeserializeTypedParameters(remote_typed_param *ret_params_val, ret_param->value.remote_typed_param_value_u.b; break; case VIR_TYPED_PARAM_STRING: - param->value.s = - strdup(ret_param->value.remote_typed_param_value_u.s); - if (!param->value.s) { - virReportOOMError(); + if (VIR_STRDUP(param->value.s, + ret_param->value.remote_typed_param_value_u.s) < 0) goto cleanup; - } break; default: virReportError(VIR_ERR_RPC, _("unknown parameter type: %d"), @@ -1653,10 +1632,8 @@ remoteDeserializeDomainDiskErrors(remote_domain_disk_error *ret_errors_val, } for (i = 0; i < ret_errors_len; i++) { - if (!(errors[i].disk = strdup(ret_errors_val[i].disk))) { - virReportOOMError(); + if (VIR_STRDUP(errors[i].disk, ret_errors_val[i].disk) < 0) goto error; - } errors[i].error = ret_errors_val[i].error; } @@ -4472,15 +4449,15 @@ remoteDomainBuildEventGraphics(virNetClientProgramPtr prog ATTRIBUTE_UNUSED, if (VIR_ALLOC(localAddr) < 0) goto no_memory; localAddr->family = msg->local.family; - if (!(localAddr->service = strdup(msg->local.service)) || - !(localAddr->node = strdup(msg->local.node))) + if (VIR_STRDUP(localAddr->service, msg->local.service) < 0 || + VIR_STRDUP(localAddr->node, msg->local.node) < 0) goto no_memory; if (VIR_ALLOC(remoteAddr) < 0) goto no_memory; remoteAddr->family = msg->remote.family; - if (!(remoteAddr->service = strdup(msg->remote.service)) || - !(remoteAddr->node = strdup(msg->remote.node))) + if (VIR_STRDUP(remoteAddr->service, msg->remote.service) < 0 || + VIR_STRDUP(remoteAddr->node, msg->remote.node) < 0) goto no_memory; if (VIR_ALLOC(subject) < 0) @@ -4489,8 +4466,8 @@ remoteDomainBuildEventGraphics(virNetClientProgramPtr prog ATTRIBUTE_UNUSED, goto no_memory; subject->nidentity = msg->subject.subject_len; for (i = 0 ; i < subject->nidentity ; i++) { - if (!(subject->identities[i].type = strdup(msg->subject.subject_val[i].type)) || - !(subject->identities[i].name = strdup(msg->subject.subject_val[i].name))) + if (VIR_STRDUP(subject->identities[i].type, msg->subject.subject_val[i].type) < 0 || + VIR_STRDUP(subject->identities[i].name, msg->subject.subject_val[i].name) < 0) goto no_memory; } @@ -5100,11 +5077,8 @@ remoteDomainQemuMonitorCommand(virDomainPtr domain, const char *cmd, (xdrproc_t) xdr_qemu_domain_monitor_command_ret, (char *) &ret) == -1) goto done; - *result = strdup(ret.result); - if (*result == NULL) { - virReportOOMError(); + if (VIR_STRDUP(*result, ret.result) < 0) goto cleanup; - } rv = 0; -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/remote/remote_driver.c | 114 +++++++++++++++++---------------------------- 1 file changed, 44 insertions(+), 70 deletions(-)
@@ -4472,15 +4449,15 @@ remoteDomainBuildEventGraphics(virNetClientProgramPtr prog ATTRIBUTE_UNUSED, if (VIR_ALLOC(localAddr) < 0) goto no_memory; localAddr->family = msg->local.family; - if (!(localAddr->service = strdup(msg->local.service)) || - !(localAddr->node = strdup(msg->local.node))) + if (VIR_STRDUP(localAddr->service, msg->local.service) < 0 || + VIR_STRDUP(localAddr->node, msg->local.node) < 0) goto no_memory;
double-oom, but...
if (VIR_ALLOC(remoteAddr) < 0) goto no_memory;
...you'll be making another pass anyway. ACK. There's also a lot of strdup() in src/remote/remote_client_bodies.h; you probably need to touch up src/rpc/gendispatch.pl to generate nicer code there. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/rpc/gendispatch.pl | 21 ++++-------- src/rpc/virnetclient.c | 16 ++++------ src/rpc/virnetmessage.c | 12 ++++--- src/rpc/virnetsaslcontext.c | 6 ++-- src/rpc/virnetserver.c | 6 ++-- src/rpc/virnetserverclient.c | 10 ++---- src/rpc/virnetservermdns.c | 6 ++-- src/rpc/virnetsocket.c | 10 +++--- src/rpc/virnetsshsession.c | 76 ++++++++++++++++++++++---------------------- src/rpc/virnettlscontext.c | 26 +++++++-------- 10 files changed, 82 insertions(+), 107 deletions(-) diff --git a/src/rpc/gendispatch.pl b/src/rpc/gendispatch.pl index 8d3b013..8c83cd2 100755 --- a/src/rpc/gendispatch.pl +++ b/src/rpc/gendispatch.pl @@ -610,12 +610,10 @@ elsif ($mode eq "server") { # SPECIAL: virConnectGetType returns a constant string that must # not be freed. Therefore, duplicate the string here. push(@vars_list, "const char *$1"); - push(@ret_list, "/* We have to strdup because remoteDispatchClientRequest will"); + push(@ret_list, "/* We have to VIR_STRDUP because remoteDispatchClientRequest will"); push(@ret_list, " * free this string after it's been serialised. */"); - push(@ret_list, "if (!(ret->type = strdup(type))) {"); - push(@ret_list, " virReportOOMError();"); + push(@ret_list, "if (VIR_STRDUP(ret->type, type) < 0)"); push(@ret_list, " goto cleanup;"); - push(@ret_list, "}"); } else { push(@vars_list, "char *$1"); push(@ret_list, "ret->$1 = $1;"); @@ -636,11 +634,8 @@ elsif ($mode eq "server") { " goto cleanup;\n" . " }\n" . " \n" . - " *$1_p = strdup($1);\n" . - " if (*$1_p == NULL) {\n" . - " virReportOOMError();\n" . - " goto cleanup;\n" . - " }\n"); + " if (VIR_STRDUP(*$1_p, $1) < 0)\n". + " goto cleanup;\n"); $single_ret_var = $1; $single_ret_by_ref = 0; @@ -1562,16 +1557,14 @@ elsif ($mode eq "client") { print "\n"; print " /* This call is caller-frees (although that isn't clear from\n"; print " * the documentation). However xdr_free will free up both the\n"; - print " * names and the list of pointers, so we have to strdup the\n"; + print " * names and the list of pointers, so we have to VIR_STRDUP the\n"; print " * names here. */\n"; print " for (i = 0; i < ret.$single_ret_list_name.${single_ret_list_name}_len; ++i) {\n"; - print " ${single_ret_list_name}[i] = strdup(ret.$single_ret_list_name.${single_ret_list_name}_val[i]);\n"; - print "\n"; - print " if (${single_ret_list_name}[i] == NULL) {\n"; + print " if (VIR_STRDUP(${single_ret_list_name}[i],\n"; + print " ret.$single_ret_list_name.${single_ret_list_name}_val[i]) < 0) {\n"; print " for (--i; i >= 0; --i)\n"; print " VIR_FREE(${single_ret_list_name}[i]);\n"; print "\n"; - print " virReportOOMError();\n"; print " goto cleanup;\n"; print " }\n"; print " }\n"; diff --git a/src/rpc/virnetclient.c b/src/rpc/virnetclient.c index 1d228f0..bdbb9fe 100644 --- a/src/rpc/virnetclient.c +++ b/src/rpc/virnetclient.c @@ -36,6 +36,7 @@ #include "virlog.h" #include "virutil.h" #include "virerror.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_RPC @@ -317,17 +318,14 @@ static virNetClientPtr virNetClientNew(virNetSocketPtr sock, client->wakeupSendFD = wakeupFD[1]; wakeupFD[0] = wakeupFD[1] = -1; - if (hostname && - !(client->hostname = strdup(hostname))) - goto no_memory; + if (hostname && VIR_STRDUP(client->hostname, hostname) < 0) + goto error; PROBE(RPC_CLIENT_NEW, "client=%p sock=%p", client, client->sock); return client; -no_memory: - virReportOOMError(); error: VIR_FORCE_CLOSE(wakeupFD[0]); VIR_FORCE_CLOSE(wakeupFD[1]); @@ -414,8 +412,8 @@ virNetClientPtr virNetClientNewLibSSH2(const char *host, goto no_memory; } } else { - if (!(knownhosts = strdup(knownHostsPath))) - goto no_memory; + if (VIR_STRDUP(knownhosts, knownHostsPath) < 0) + goto cleanup; } } @@ -438,8 +436,8 @@ virNetClientPtr virNetClientNewLibSSH2(const char *host, VIR_FREE(privkey); } } else { - if (!(privkey = strdup(privkeyPath))) - goto no_memory; + if (VIR_STRDUP(privkey, privkeyPath) < 0) + goto cleanup; } } diff --git a/src/rpc/virnetmessage.c b/src/rpc/virnetmessage.c index 647fef7..9e8a568 100644 --- a/src/rpc/virnetmessage.c +++ b/src/rpc/virnetmessage.c @@ -29,6 +29,7 @@ #include "virlog.h" #include "virfile.h" #include "virutil.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_RPC @@ -485,21 +486,22 @@ void virNetMessageSaveError(virNetMessageErrorPtr rerr) rerr->code = verr->code; rerr->domain = verr->domain; if (verr->message && VIR_ALLOC(rerr->message) == 0) - *rerr->message = strdup(verr->message); + ignore_value(VIR_STRDUP_QUIET(*rerr->message, verr->message)); rerr->level = verr->level; if (verr->str1 && VIR_ALLOC(rerr->str1) == 0) - *rerr->str1 = strdup(verr->str1); + ignore_value(VIR_STRDUP_QUIET(*rerr->str1, verr->str1)); if (verr->str2 && VIR_ALLOC(rerr->str2) == 0) - *rerr->str2 = strdup(verr->str2); + ignore_value(VIR_STRDUP_QUIET(*rerr->str2, verr->str2)); if (verr->str3 && VIR_ALLOC(rerr->str3) == 0) - *rerr->str3 = strdup(verr->str3); + ignore_value(VIR_STRDUP_QUIET(*rerr->str3, verr->str3)); rerr->int1 = verr->int1; rerr->int2 = verr->int2; } else { rerr->code = VIR_ERR_INTERNAL_ERROR; rerr->domain = VIR_FROM_RPC; if (VIR_ALLOC(rerr->message) == 0) - *rerr->message = strdup(_("Library function returned error but did not set virError")); + ignore_value(VIR_STRDUP_QUIET(*rerr->message, + _("Library function returned error but did not set virError"))); rerr->level = VIR_ERR_ERROR; } } diff --git a/src/rpc/virnetsaslcontext.c b/src/rpc/virnetsaslcontext.c index 6943216..35dc6cf 100644 --- a/src/rpc/virnetsaslcontext.c +++ b/src/rpc/virnetsaslcontext.c @@ -29,6 +29,7 @@ #include "viralloc.h" #include "virthread.h" #include "virlog.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_RPC @@ -385,10 +386,7 @@ char *virNetSASLSessionListMechanisms(virNetSASLSessionPtr sasl) err, sasl_errdetail(sasl->conn)); goto cleanup; } - if (!(ret = strdup(mechlist))) { - virReportOOMError(); - goto cleanup; - } + ignore_value(VIR_STRDUP(ret, mechlist)); cleanup: virObjectUnlock(sasl); diff --git a/src/rpc/virnetserver.c b/src/rpc/virnetserver.c index e536cc3..6e73832 100644 --- a/src/rpc/virnetserver.c +++ b/src/rpc/virnetserver.c @@ -37,6 +37,7 @@ #include "virfile.h" #include "virnetservermdns.h" #include "virdbus.h" +#include "virstring.h" #ifndef SA_SIGINFO # define SA_SIGINFO 0 @@ -387,11 +388,8 @@ virNetServerPtr virNetServerNew(size_t min_workers, srv->privileged = geteuid() == 0; srv->autoShutdownInhibitFd = -1; - if (mdnsGroupName && - !(srv->mdnsGroupName = strdup(mdnsGroupName))) { - virReportOOMError(); + if (mdnsGroupName && VIR_STRDUP(srv->mdnsGroupName, mdnsGroupName) < 0) goto error; - } if (srv->mdnsGroupName) { if (!(srv->mdns = virNetServerMDNSNew())) goto error; diff --git a/src/rpc/virnetserverclient.c b/src/rpc/virnetserverclient.c index 2bde5c7..fcc3f5c 100644 --- a/src/rpc/virnetserverclient.c +++ b/src/rpc/virnetserverclient.c @@ -681,22 +681,16 @@ virNetServerClientCreateIdentity(virNetServerClientPtr client) #if WITH_SASL if (client->sasl) { const char *identity = virNetSASLSessionGetIdentity(client->sasl); - if (identity && - !(saslname = strdup(identity))) { - virReportOOMError(); + if (identity && VIR_STRDUP(saslname, identity) < 0) goto cleanup; - } } #endif #if WITH_GNUTLS if (client->tls) { const char *identity = virNetTLSSessionGetX509DName(client->tls); - if (identity && - !(x509dname = strdup(identity))) { - virReportOOMError(); + if (identity && VIR_STRDUP(x509dname, identity) < 0) goto cleanup; - } } #endif diff --git a/src/rpc/virnetservermdns.c b/src/rpc/virnetservermdns.c index 26e24d5..68d5e4e 100644 --- a/src/rpc/virnetservermdns.c +++ b/src/rpc/virnetservermdns.c @@ -479,9 +479,8 @@ virNetServerMDNSGroupPtr virNetServerMDNSAddGroup(virNetServerMDNS *mdns, return NULL; } - if (!(group->name = strdup(name))) { + if (VIR_STRDUP(group->name, name) < 0) { VIR_FREE(group); - virReportOOMError(); return NULL; } group->mdns = mdns; @@ -525,9 +524,8 @@ virNetServerMDNSEntryPtr virNetServerMDNSAddEntry(virNetServerMDNSGroupPtr group } entry->port = port; - if (!(entry->type = strdup(type))) { + if (VIR_STRDUP(entry->type, type) < 0) { VIR_FREE(entry); - virReportOOMError(); return NULL; } entry->next = group->entry; diff --git a/src/rpc/virnetsocket.c b/src/rpc/virnetsocket.c index e950d7f..c1fa3f3 100644 --- a/src/rpc/virnetsocket.c +++ b/src/rpc/virnetsocket.c @@ -800,10 +800,10 @@ virNetSocketNewConnectLibSSH2(const char *host, if (virNetSSHSessionSetChannelCommand(sess, command) != 0) goto error; - if (!(authMethodNext = authMethodsCopy = strdup(authMethods))) { - virReportOOMError(); + if (VIR_STRDUP(authMethodsCopy, authMethods) < 0) goto error; - } + + authMethodNext = authMethodsCopy; while ((authMethod = strsep(&authMethodNext, ","))) { if (STRCASEEQ(authMethod, "keyboard-interactive")) @@ -1180,10 +1180,8 @@ int virNetSocketGetSecurityContext(virNetSocketPtr sock, goto cleanup; } - if (!(*context = strdup(seccon))) { - virReportOOMError(); + if (VIR_STRDUP(*context, seccon) < 0) goto cleanup; - } ret = 0; cleanup: diff --git a/src/rpc/virnetsshsession.c b/src/rpc/virnetsshsession.c index 27750fc..a10868d 100644 --- a/src/rpc/virnetsshsession.c +++ b/src/rpc/virnetsshsession.c @@ -233,7 +233,7 @@ virNetSSHKbIntCb(const char *name ATTRIBUTE_UNUSED, /* fill data structures for auth callback */ for (i = 0; i < num_prompts; i++) { - if (!(askcred[i].prompt = strdup(prompts[i].text))) { + if (VIR_STRDUP(askcred[i].prompt, prompts[i].text) < 0) { priv->authCbErr = VIR_NET_SSH_AUTHCB_OOM; goto cleanup; } @@ -959,12 +959,14 @@ virNetSSHSessionAuthAddPasswordAuth(virNetSSHSessionPtr sess, virObjectLock(sess); - if (!(user = strdup(username)) || - !(pass = strdup(password))) - goto no_memory; + if (VIR_STRDUP(user, username) < 0 || + VIR_STRDUP(pass, password) < 0) + goto error; - if (!(auth = virNetSSHSessionAuthMethodNew(sess))) - goto no_memory; + if (!(auth = virNetSSHSessionAuthMethodNew(sess))) { + virReportOOMError(); + goto error; + } auth->username = user; auth->password = pass; @@ -973,10 +975,9 @@ virNetSSHSessionAuthAddPasswordAuth(virNetSSHSessionPtr sess, virObjectUnlock(sess); return 0; -no_memory: +error: VIR_FREE(user); VIR_FREE(pass); - virReportOOMError(); virObjectUnlock(sess); return -1; } @@ -997,11 +998,13 @@ virNetSSHSessionAuthAddAgentAuth(virNetSSHSessionPtr sess, virObjectLock(sess); - if (!(user = strdup(username))) - goto no_memory; + if (VIR_STRDUP(user, username) < 0) + goto error; - if (!(auth = virNetSSHSessionAuthMethodNew(sess))) - goto no_memory; + if (!(auth = virNetSSHSessionAuthMethodNew(sess))) { + virReportOOMError(); + goto error; + } auth->username = user; auth->method = VIR_NET_SSH_AUTH_AGENT; @@ -1009,9 +1012,8 @@ virNetSSHSessionAuthAddAgentAuth(virNetSSHSessionPtr sess, virObjectUnlock(sess); return 0; -no_memory: +error: VIR_FREE(user); - virReportOOMError(); virObjectUnlock(sess); return -1; } @@ -1037,15 +1039,17 @@ virNetSSHSessionAuthAddPrivKeyAuth(virNetSSHSessionPtr sess, virObjectLock(sess); - if (!(user = strdup(username)) || - !(file = strdup(keyfile))) - goto no_memory; + if (VIR_STRDUP(user, username) < 0 || + VIR_STRDUP(file, keyfile) < 0) + goto error; - if (password && !(pass = strdup(password))) - goto no_memory; + if (password && VIR_STRDUP(pass, password) < 0) + goto error; - if (!(auth = virNetSSHSessionAuthMethodNew(sess))) - goto no_memory; + if (!(auth = virNetSSHSessionAuthMethodNew(sess))) { + virReportOOMError(); + goto error; + } auth->username = user; auth->password = pass; @@ -1055,11 +1059,10 @@ virNetSSHSessionAuthAddPrivKeyAuth(virNetSSHSessionPtr sess, virObjectUnlock(sess); return 0; -no_memory: +error: VIR_FREE(user); VIR_FREE(pass); VIR_FREE(file); - virReportOOMError(); virObjectUnlock(sess); return -1; } @@ -1081,11 +1084,13 @@ virNetSSHSessionAuthAddKeyboardAuth(virNetSSHSessionPtr sess, virObjectLock(sess); - if (!(user = strdup(username))) - goto no_memory; + if (VIR_STRDUP(user, username) < 0) + goto error; - if (!(auth = virNetSSHSessionAuthMethodNew(sess))) - goto no_memory; + if (!(auth = virNetSSHSessionAuthMethodNew(sess))) { + virReportOOMError(); + goto error; + } auth->username = user; auth->tries = tries; @@ -1094,9 +1099,8 @@ virNetSSHSessionAuthAddKeyboardAuth(virNetSSHSessionPtr sess, virObjectUnlock(sess); return 0; -no_memory: +error: VIR_FREE(user); - virReportOOMError(); virObjectUnlock(sess); return -1; @@ -1111,10 +1115,8 @@ virNetSSHSessionSetChannelCommand(virNetSSHSessionPtr sess, VIR_FREE(sess->channelCommand); - if (command && !(sess->channelCommand = strdup(command))) { - virReportOOMError(); + if (command && VIR_STRDUP(sess->channelCommand, command) < 0) ret = -1; - } virObjectUnlock(sess); return ret; @@ -1137,8 +1139,8 @@ virNetSSHSessionSetHostKeyVerification(virNetSSHSessionPtr sess, VIR_FREE(sess->hostname); - if (hostname && !(sess->hostname = strdup(hostname))) - goto no_memory; + if (hostname && VIR_STRDUP(sess->hostname, hostname) < 0) + goto error; /* load the known hosts file */ if (hostsfile) { @@ -1162,16 +1164,14 @@ virNetSSHSessionSetHostKeyVerification(virNetSSHSessionPtr sess, /* set filename only if writing to the known hosts file is requested */ if (!(flags & VIR_NET_SSH_HOSTKEY_FILE_READONLY)) { VIR_FREE(sess->knownHostsFile); - if (!(sess->knownHostsFile = strdup(hostsfile))) - goto no_memory; + if (VIR_STRDUP(sess->knownHostsFile, hostsfile) < 0) + goto error; } } virObjectUnlock(sess); return 0; -no_memory: - virReportOOMError(); error: virObjectUnlock(sess); return -1; diff --git a/src/rpc/virnettlscontext.c b/src/rpc/virnettlscontext.c index 7f5975d..fcfeebb 100644 --- a/src/rpc/virnettlscontext.c +++ b/src/rpc/virnettlscontext.c @@ -836,23 +836,23 @@ static int virNetTLSContextLocateCredentials(const char *pkipath, */ if (!*cacert) { VIR_DEBUG("Using default TLS CA certificate path"); - if (!(*cacert = strdup(LIBVIRT_CACERT))) - goto out_of_memory; + if (VIR_STRDUP(*cacert, LIBVIRT_CACERT) < 0) + goto error; } if (!*cacrl) { VIR_DEBUG("Using default TLS CA revocation list path"); - if (!(*cacrl = strdup(LIBVIRT_CACRL))) - goto out_of_memory; + if (VIR_STRDUP(*cacrl, LIBVIRT_CACRL) < 0) + goto error; } if (!*key && !*cert) { VIR_DEBUG("Using default TLS key/certificate path"); - if (!(*key = strdup(isServer ? LIBVIRT_SERVERKEY : LIBVIRT_CLIENTKEY))) - goto out_of_memory; + if (VIR_STRDUP(*key, isServer ? LIBVIRT_SERVERKEY : LIBVIRT_CLIENTKEY) < 0) + goto error; - if (!(*cert = strdup(isServer ? LIBVIRT_SERVERCERT : LIBVIRT_CLIENTCERT))) - goto out_of_memory; + if (VIR_STRDUP(*cert, isServer ? LIBVIRT_SERVERCERT : LIBVIRT_CLIENTCERT) < 0) + goto error; } VIR_FREE(user_pki_path); @@ -862,6 +862,7 @@ static int virNetTLSContextLocateCredentials(const char *pkipath, out_of_memory: virReportOOMError(); +error: VIR_FREE(*cacert); VIR_FREE(*cacrl); VIR_FREE(*key); @@ -1028,10 +1029,8 @@ static int virNetTLSContextValidCertificate(virNetTLSContextPtr ctxt, "[session]", gnutls_strerror(ret)); goto authfail; } - if (!(sess->x509dname = strdup(dname))) { - virReportOOMError(); + if (VIR_STRDUP(sess->x509dname, dname) < 0) goto authfail; - } VIR_DEBUG("Peer DN is %s", dname); if (virNetTLSContextCheckCertDN(cert, "[session]", sess->hostname, dname, @@ -1168,11 +1167,8 @@ virNetTLSSessionPtr virNetTLSSessionNew(virNetTLSContextPtr ctxt, if (!(sess = virObjectLockableNew(virNetTLSSessionClass))) return NULL; - if (hostname && - !(sess->hostname = strdup(hostname))) { - virReportOOMError(); + if (hostname && VIR_STRDUP(sess->hostname, hostname) < 0) goto error; - } if ((err = gnutls_init(&sess->session, ctxt->isServer ? GNUTLS_SERVER : GNUTLS_CLIENT)) != 0) { -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/rpc/gendispatch.pl | 21 ++++--------
Ah, you DID notice the code generator, so that answers my comment on 18/34.
src/rpc/virnetclient.c | 16 ++++------ src/rpc/virnetmessage.c | 12 ++++--- src/rpc/virnetsaslcontext.c | 6 ++-- src/rpc/virnetserver.c | 6 ++-- src/rpc/virnetserverclient.c | 10 ++---- src/rpc/virnetservermdns.c | 6 ++-- src/rpc/virnetsocket.c | 10 +++--- src/rpc/virnetsshsession.c | 76 ++++++++++++++++++++++---------------------- src/rpc/virnettlscontext.c | 26 +++++++-------- 10 files changed, 82 insertions(+), 107 deletions(-)
+++ b/src/rpc/virnetclient.c @@ -317,17 +318,14 @@ static virNetClientPtr virNetClientNew(virNetSocketPtr sock, client->wakeupSendFD = wakeupFD[1]; wakeupFD[0] = wakeupFD[1] = -1;
- if (hostname && - !(client->hostname = strdup(hostname))) - goto no_memory; + if (hostname && VIR_STRDUP(client->hostname, hostname) < 0) + goto error;
Can simplify with NULL source.
+++ b/src/rpc/virnetmessage.c @@ -485,21 +486,22 @@ void virNetMessageSaveError(virNetMessageErrorPtr rerr) rerr->code = verr->code; rerr->domain = verr->domain; if (verr->message && VIR_ALLOC(rerr->message) == 0) - *rerr->message = strdup(verr->message); + ignore_value(VIR_STRDUP_QUIET(*rerr->message, verr->message));
Correct use of VIR_STRDUP_QUIET here. Hmm - wonder if there is a pre-existing bug. If VIR_ALLOC succeeds but strdup fails, rerr->message points to a NULL pointer. The intent was that we _try_ to copy the string, but if it fails, we are okay for the RPC message to go out with a loss of information - but that should be done with rerr->message being a NULL pointer, not pointing to a NULL pointer. That is, I think this code should read: if (verr->message && VIR_ALLOC(rerr->message) == 0 && VIR_STRDUP_QUIET(*rerr->message, verr->message) < 0) VIR_FREE(rerr->message);
rerr->level = verr->level; if (verr->str1 && VIR_ALLOC(rerr->str1) == 0) - *rerr->str1 = strdup(verr->str1); + ignore_value(VIR_STRDUP_QUIET(*rerr->str1, verr->str1)); if (verr->str2 && VIR_ALLOC(rerr->str2) == 0) - *rerr->str2 = strdup(verr->str2); + ignore_value(VIR_STRDUP_QUIET(*rerr->str2, verr->str2)); if (verr->str3 && VIR_ALLOC(rerr->str3) == 0) - *rerr->str3 = strdup(verr->str3); + ignore_value(VIR_STRDUP_QUIET(*rerr->str3, verr->str3));
Likewise for these three best-effort strings.
rerr->int1 = verr->int1; rerr->int2 = verr->int2; } else { rerr->code = VIR_ERR_INTERNAL_ERROR; rerr->domain = VIR_FROM_RPC; if (VIR_ALLOC(rerr->message) == 0) - *rerr->message = strdup(_("Library function returned error but did not set virError")); + ignore_value(VIR_STRDUP_QUIET(*rerr->message, + _("Library function returned error but did not set virError")));
And another case where I think we should free rerr->message if strdup fails.
+++ b/src/rpc/virnetserver.c @@ -387,11 +388,8 @@ virNetServerPtr virNetServerNew(size_t min_workers, srv->privileged = geteuid() == 0; srv->autoShutdownInhibitFd = -1;
- if (mdnsGroupName && - !(srv->mdnsGroupName = strdup(mdnsGroupName))) { - virReportOOMError(); + if (mdnsGroupName && VIR_STRDUP(srv->mdnsGroupName, mdnsGroupName) < 0)
Can be simplified.
+++ b/src/rpc/virnetserverclient.c @@ -681,22 +681,16 @@ virNetServerClientCreateIdentity(virNetServerClientPtr client) #if WITH_SASL if (client->sasl) { const char *identity = virNetSASLSessionGetIdentity(client->sasl); - if (identity && - !(saslname = strdup(identity))) { - virReportOOMError(); + if (identity && VIR_STRDUP(saslname, identity) < 0)
Can be simplified.
goto cleanup; - } } #endif
#if WITH_GNUTLS if (client->tls) { const char *identity = virNetTLSSessionGetX509DName(client->tls); - if (identity && - !(x509dname = strdup(identity))) { - virReportOOMError(); + if (identity && VIR_STRDUP(x509dname, identity) < 0)
and again.
+++ b/src/rpc/virnetsocket.c @@ -800,10 +800,10 @@ virNetSocketNewConnectLibSSH2(const char *host, if (virNetSSHSessionSetChannelCommand(sess, command) != 0) goto error;
- if (!(authMethodNext = authMethodsCopy = strdup(authMethods))) { - virReportOOMError(); + if (VIR_STRDUP(authMethodsCopy, authMethods) < 0) goto error; - } + + authMethodNext = authMethodsCopy;
while ((authMethod = strsep(&authMethodNext, ","))) {
Wonder if we should use virStringSplit instead of strsep().
+++ b/src/rpc/virnetsshsession.c @@ -233,7 +233,7 @@ virNetSSHKbIntCb(const char *name ATTRIBUTE_UNUSED,
/* fill data structures for auth callback */ for (i = 0; i < num_prompts; i++) { - if (!(askcred[i].prompt = strdup(prompts[i].text))) { + if (VIR_STRDUP(askcred[i].prompt, prompts[i].text) < 0) { priv->authCbErr = VIR_NET_SSH_AUTHCB_OOM; goto cleanup;
Double-oom, unless you fix line 741 in virNetSSHAuthenticateKeyboardInteractive()'s switch statement to stop reporting oom when authCbErr says it has already been reported.
@@ -1037,15 +1039,17 @@ virNetSSHSessionAuthAddPrivKeyAuth(virNetSSHSessionPtr sess,
virObjectLock(sess);
- if (!(user = strdup(username)) || - !(file = strdup(keyfile))) - goto no_memory; + if (VIR_STRDUP(user, username) < 0 || + VIR_STRDUP(file, keyfile) < 0) + goto error;
- if (password && !(pass = strdup(password))) - goto no_memory; + if (password && VIR_STRDUP(pass, password) < 0) + goto error;
Can be simplified, and merged in with previous 'if'.
@@ -1111,10 +1115,8 @@ virNetSSHSessionSetChannelCommand(virNetSSHSessionPtr sess,
VIR_FREE(sess->channelCommand);
- if (command && !(sess->channelCommand = strdup(command))) { - virReportOOMError(); + if (command && VIR_STRDUP(sess->channelCommand, command) < 0) ret = -1;
Can be simplified.
- }
virObjectUnlock(sess); return ret; @@ -1137,8 +1139,8 @@ virNetSSHSessionSetHostKeyVerification(virNetSSHSessionPtr sess,
VIR_FREE(sess->hostname);
- if (hostname && !(sess->hostname = strdup(hostname))) - goto no_memory; + if (hostname && VIR_STRDUP(sess->hostname, hostname) < 0) + goto error;
and again.
+++ b/src/rpc/virnettlscontext.c @@ -1168,11 +1167,8 @@ virNetTLSSessionPtr virNetTLSSessionNew(virNetTLSContextPtr ctxt, if (!(sess = virObjectLockableNew(virNetTLSSessionClass))) return NULL;
- if (hostname && - !(sess->hostname = strdup(hostname))) { - virReportOOMError(); + if (hostname && VIR_STRDUP(sess->hostname, hostname) < 0) goto error;
and again. ACK with minor cleanups. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/secret/secret_driver.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/secret/secret_driver.c b/src/secret/secret_driver.c index 377b9f4..5d1739f 100644 --- a/src/secret/secret_driver.c +++ b/src/secret/secret_driver.c @@ -1097,9 +1097,8 @@ secretStateInitialize(bool privileged, secretDriverLock(driverState); if (privileged) { - base = strdup(SYSCONFDIR "/libvirt"); - if (base == NULL) - goto out_of_memory; + if (VIR_STRDUP(base, SYSCONFDIR "/libvirt") < 0) + goto error; } else { base = virGetUserConfigDirectory(); if (!base) -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/secret/secret_driver.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
Nice and short! ACK.
diff --git a/src/secret/secret_driver.c b/src/secret/secret_driver.c index 377b9f4..5d1739f 100644 --- a/src/secret/secret_driver.c +++ b/src/secret/secret_driver.c @@ -1097,9 +1097,8 @@ secretStateInitialize(bool privileged, secretDriverLock(driverState);
if (privileged) { - base = strdup(SYSCONFDIR "/libvirt"); - if (base == NULL) - goto out_of_memory; + if (VIR_STRDUP(base, SYSCONFDIR "/libvirt") < 0) + goto error; } else { base = virGetUserConfigDirectory(); if (!base)
-- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/security/security_apparmor.c | 20 ++-------- src/security/security_dac.c | 23 ++++-------- src/security/security_nop.c | 7 +--- src/security/security_selinux.c | 79 +++++++++++----------------------------- src/security/virt-aa-helper.c | 4 +- 5 files changed, 37 insertions(+), 96 deletions(-) diff --git a/src/security/security_apparmor.c b/src/security/security_apparmor.c index 5fb5db3..84faebd 100644 --- a/src/security/security_apparmor.c +++ b/src/security/security_apparmor.c @@ -446,24 +446,15 @@ AppArmorGenSecurityLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED, if ((profile_name = get_profile_name(def)) == NULL) return rc; - secdef->label = strndup(profile_name, strlen(profile_name)); - if (!secdef->label) { - virReportOOMError(); + if (VIR_STRDUP(secdef->label, profile_name) < 0) goto clean; - } /* set imagelabel the same as label (but we won't use it) */ - secdef->imagelabel = strndup(profile_name, - strlen(profile_name)); - if (!secdef->imagelabel) { - virReportOOMError(); + if (VIR_STRDUP(secdef->imagelabel, profile_name) < 0) goto err; - } - if (!secdef->model && !(secdef->model = strdup(SECURITY_APPARMOR_NAME))) { - virReportOOMError(); + if (!secdef->model && VIR_STRDUP(secdef->model, SECURITY_APPARMOR_NAME) < 0) goto err; - } /* Now that we have a label, load the profile into the kernel. */ if (load_profile(mgr, secdef->label, def, NULL, false) < 0) { @@ -933,10 +924,7 @@ AppArmorGetMountOptions(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED, { char *opts; - if (!(opts = strdup(""))) { - virReportOOMError(); - return NULL; - } + ignore_value(VIR_STRDUP(opts, "")); return opts; } diff --git a/src/security/security_dac.c b/src/security/security_dac.c index cd214d8..c894517 100644 --- a/src/security/security_dac.c +++ b/src/security/security_dac.c @@ -76,11 +76,8 @@ int parseIds(const char *label, uid_t *uidPtr, gid_t *gidPtr) char *owner = NULL; char *group = NULL; - tmp_label = strdup(label); - if (tmp_label == NULL) { - virReportOOMError(); + if (VIR_STRDUP(tmp_label, label) < 0) goto cleanup; - } /* Split label */ sep = strchr(tmp_label, ':'); @@ -1051,18 +1048,12 @@ virSecurityDACGenLabel(virSecurityManagerPtr mgr, return rc; } - if (!seclabel->norelabel) { - if (seclabel->imagelabel == NULL && seclabel->label != NULL) { - seclabel->imagelabel = strdup(seclabel->label); - if (seclabel->imagelabel == NULL) { - virReportError(VIR_ERR_INTERNAL_ERROR, - _("cannot generate dac user and group id " - "for domain %s"), def->name); - VIR_FREE(seclabel->label); - seclabel->label = NULL; - return rc; - } - } + if (!seclabel->norelabel && + seclabel->imagelabel == NULL && seclabel->label != NULL && + VIR_STRDUP(seclabel->imagelabel, seclabel->label) < 0) { + VIR_FREE(seclabel->label); + seclabel->label = NULL; + return rc; } return 0; diff --git a/src/security/security_nop.c b/src/security/security_nop.c index 2b9767e..233404c 100644 --- a/src/security/security_nop.c +++ b/src/security/security_nop.c @@ -20,7 +20,7 @@ #include <config.h> #include "security_nop.h" - +#include "virstring.h" #include "virerror.h" #define VIR_FROM_THIS VIR_FROM_SECURITY @@ -182,10 +182,7 @@ static char *virSecurityDomainGetMountOptionsNop(virSecurityManagerPtr mgr ATTRI { char *opts; - if (!(opts = strdup(""))) { - virReportOOMError(); - return NULL; - } + ignore_value(VIR_STRDUP(opts, "")); return opts; } diff --git a/src/security/security_selinux.c b/src/security/security_selinux.c index a85f0a3..dcec32b 100644 --- a/src/security/security_selinux.c +++ b/src/security/security_selinux.c @@ -202,10 +202,8 @@ virSecuritySELinuxMCSGetProcessRange(char **sens, goto cleanup; } - if (!(*sens = strdup(context_range_get(ourContext)))) { - virReportOOMError(); + if (VIR_STRDUP(*sens, context_range_get(ourContext)) < 0) goto cleanup; - } /* Find and blank out the category part (if any) */ tmp = strchr(*sens, ':'); @@ -312,10 +310,7 @@ virSecuritySELinuxContextAddRange(security_context_t src, goto cleanup; } - if (!(ret = strdup(str))) { - virReportOOMError(); - goto cleanup; - } + ignore_value(VIR_STRDUP(ret, str)); cleanup: if (srccon) context_free(srccon); @@ -385,10 +380,8 @@ virSecuritySELinuxGenNewContext(const char *basecontext, _("Unable to format SELinux context")); goto cleanup; } - if (!(ret = strdup(str))) { - virReportOOMError(); + if (VIR_STRDUP(ret, str) < 0) goto cleanup; - } VIR_DEBUG("Generated context '%s'", ret); cleanup: freecon(ourSecContext); @@ -451,17 +444,10 @@ virSecuritySELinuxLXCInitialize(virSecurityManagerPtr mgr) goto error; } - data->domain_context = strdup(scon->str); - data->file_context = strdup(tcon->str); - data->content_context = strdup(dcon->str); - if (!data->domain_context || - !data->file_context || - !data->content_context) { - virReportSystemError(errno, - _("cannot allocate memory for LXC SELinux contexts '%s'"), - selinux_lxc_contexts_path()); + if (VIR_STRDUP(data->domain_context, scon->str) < 0 || + VIR_STRDUP(data->file_context, tcon->str) < 0 || + VIR_STRDUP(data->content_context, dcon->str) < 0) goto error; - } if (!(data->mcs = virHashCreate(10, NULL))) goto error; @@ -520,11 +506,8 @@ virSecuritySELinuxQEMUInitialize(virSecurityManagerPtr mgr) *ptr = '\0'; ptr++; if (*ptr != '\0') { - data->alt_domain_context = strdup(ptr); - if (!data->alt_domain_context) { - virReportOOMError(); + if (VIR_STRDUP(data->alt_domain_context, ptr) < 0) goto error; - } ptr = strchrnul(data->alt_domain_context, '\n'); if (ptr && *ptr == '\n') *ptr = '\0'; @@ -544,11 +527,8 @@ virSecuritySELinuxQEMUInitialize(virSecurityManagerPtr mgr) ptr = strchrnul(data->file_context, '\n'); if (ptr && *ptr == '\n') { *ptr = '\0'; - data->content_context = strdup(ptr+1); - if (!data->content_context) { - virReportOOMError(); + if (VIR_STRDUP(data->content_context, ptr+1) < 0) goto error; - } ptr = strchrnul(data->content_context, '\n'); if (ptr && *ptr == '\n') *ptr = '\0'; @@ -643,11 +623,12 @@ virSecuritySELinuxGenSecurityLabel(virSecurityManagerPtr mgr, } range = context_range_get(ctx); - if (!range || - !(mcs = strdup(range))) { + if (!range) { virReportOOMError(); goto cleanup; } + if (VIR_STRDUP(mcs, range) < 0) + goto cleanup; break; case VIR_DOMAIN_SECLABEL_DYNAMIC: @@ -711,10 +692,8 @@ virSecuritySELinuxGenSecurityLabel(virSecurityManagerPtr mgr, } if (!seclabel->model && - !(seclabel->model = strdup(SECURITY_SELINUX_NAME))) { - virReportOOMError(); + VIR_STRDUP(seclabel->model, SECURITY_SELINUX_NAME) < 0) goto cleanup; - } rc = 0; @@ -1391,10 +1370,8 @@ virSecuritySELinuxSetSecurityHostdevCapsLabel(virDomainDefPtr def, return -1; } } else { - if (!(path = strdup(dev->source.caps.u.storage.block))) { - virReportOOMError(); + if (VIR_STRDUP(path, dev->source.caps.u.storage.block) < 0) return -1; - } } ret = virSecuritySELinuxSetFilecon(path, secdef->imagelabel); VIR_FREE(path); @@ -1409,10 +1386,8 @@ virSecuritySELinuxSetSecurityHostdevCapsLabel(virDomainDefPtr def, return -1; } } else { - if (!(path = strdup(dev->source.caps.u.misc.chardev))) { - virReportOOMError(); + if (VIR_STRDUP(path, dev->source.caps.u.misc.chardev) < 0) return -1; - } } ret = virSecuritySELinuxSetFilecon(path, secdef->imagelabel); VIR_FREE(path); @@ -1559,10 +1534,8 @@ virSecuritySELinuxRestoreSecurityHostdevCapsLabel(virSecurityManagerPtr mgr, return -1; } } else { - if (!(path = strdup(dev->source.caps.u.storage.block))) { - virReportOOMError(); + if (VIR_STRDUP(path, dev->source.caps.u.storage.block) < 0) return -1; - } } ret = virSecuritySELinuxRestoreSecurityFileLabel(mgr, path); VIR_FREE(path); @@ -1577,10 +1550,8 @@ virSecuritySELinuxRestoreSecurityHostdevCapsLabel(virSecurityManagerPtr mgr, return -1; } } else { - if (!(path = strdup(dev->source.caps.u.misc.chardev))) { - virReportOOMError(); + if (VIR_STRDUP(path, dev->source.caps.u.misc.chardev) < 0) return -1; - } } ret = virSecuritySELinuxRestoreSecurityFileLabel(mgr, path); VIR_FREE(path); @@ -2366,7 +2337,7 @@ virSecuritySELinuxGenImageLabel(virSecurityManagerPtr mgr, const char *range; context_t ctx = NULL; char *label = NULL; - const char *mcs = NULL; + char *mcs = NULL; secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME); if (secdef == NULL) @@ -2380,11 +2351,8 @@ virSecuritySELinuxGenImageLabel(virSecurityManagerPtr mgr, } range = context_range_get(ctx); if (range) { - mcs = strdup(range); - if (!mcs) { - virReportOOMError(); + if (VIR_STRDUP(mcs, range) < 0) goto cleanup; - } if (!(label = virSecuritySELinuxGenNewContext(data->file_context, mcs, true))) goto cleanup; @@ -2392,9 +2360,9 @@ virSecuritySELinuxGenImageLabel(virSecurityManagerPtr mgr, } cleanup: - context_free(ctx); - VIR_FREE(mcs); - return label; + context_free(ctx); + VIR_FREE(mcs); + return label; } static char * @@ -2417,11 +2385,8 @@ virSecuritySELinuxGetSecurityMountOptions(virSecurityManagerPtr mgr, } } - if (!opts && - !(opts = strdup(""))) { - virReportOOMError(); + if (!opts && VIR_STRDUP(opts, "") < 0) return NULL; - } VIR_DEBUG("imageLabel=%s opts=%s", secdef ? secdef->imagelabel : "(null)", opts); diff --git a/src/security/virt-aa-helper.c b/src/security/virt-aa-helper.c index b526919..63594ce 100644 --- a/src/security/virt-aa-helper.c +++ b/src/security/virt-aa-helper.c @@ -773,7 +773,7 @@ vah_add_file(virBufferPtr buf, const char *path, const char *perms) return rc; } } else - if ((tmp = strdup(path)) == NULL) + if (VIR_STRDUP_QUIET(tmp, path) < 0) return rc; if (strchr(perms, 'w') != NULL) @@ -1103,7 +1103,7 @@ vahParseArgv(vahControl * ctl, int argc, char **argv) break; case 'f': case 'F': - if ((ctl->newfile = strdup(optarg)) == NULL) + if (VIR_STRDUP_QUIET(ctl->newfile, optarg) < 0) vah_error(ctl, 1, _("could not allocate memory for disk")); ctl->append = arg == 'F'; break; -- 1.8.1.5

--- src/storage/parthelper.c | 5 ++--- src/storage/storage_backend.c | 22 ++++++---------------- src/storage/storage_backend_disk.c | 26 +++++++------------------- src/storage/storage_backend_fs.c | 34 ++++++++++------------------------ src/storage/storage_backend_iscsi.c | 17 ++++------------- src/storage/storage_backend_logical.c | 32 ++++++++++---------------------- src/storage/storage_backend_mpath.c | 5 +---- src/storage/storage_backend_rbd.c | 5 ++--- src/storage/storage_backend_scsi.c | 19 +++++++------------ src/storage/storage_backend_sheepdog.c | 6 +----- src/storage/storage_driver.c | 18 ++++++------------ 11 files changed, 56 insertions(+), 133 deletions(-) diff --git a/src/storage/parthelper.c b/src/storage/parthelper.c index c4af48f..038487a 100644 --- a/src/storage/parthelper.c +++ b/src/storage/parthelper.c @@ -44,6 +44,7 @@ #include "virutil.h" #include "c-ctype.h" #include "configmake.h" +#include "virstring.h" /* we don't need to include the full internal.h just for this */ #define STREQ(a,b) (strcmp(a,b) == 0) @@ -86,10 +87,8 @@ int main(int argc, char **argv) path = argv[1]; if (virIsDevMapperDevice(path)) { partsep = "p"; - canonical_path = strdup(path); - if (canonical_path == NULL) { + if (VIR_STRDUP_QUIET(canonical_path, path) < 0) return 2; - } } else { if (virFileResolveLink(path, &canonical_path) != 0) { return 2; diff --git a/src/storage/storage_backend.c b/src/storage/storage_backend.c index b85a5a9..7a728e0 100644 --- a/src/storage/storage_backend.c +++ b/src/storage/storage_backend.c @@ -486,11 +486,8 @@ virStorageGenerateQcowEncryption(virConnectPtr conn, goto cleanup; def->usage_type = VIR_SECRET_USAGE_TYPE_VOLUME; - def->usage.volume = strdup(vol->target.path); - if (def->usage.volume == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->usage.volume, vol->target.path) < 0) goto cleanup; - } xml = virSecretDefFormat(def); virSecretDefFree(def); def = NULL; @@ -1261,12 +1258,11 @@ virStorageBackendUpdateVolTargetInfoFD(virStorageVolTargetPtr target, target->perms.label = NULL; } } else { - target->perms.label = strdup(filecon); - freecon(filecon); - if (target->perms.label == NULL) { - virReportOOMError(); + if (VIR_STRDUP(target->perms.label, filecon) < 0) { + freecon(filecon); return -1; } + freecon(filecon); } #else target->perms.label = NULL; @@ -1451,10 +1447,7 @@ virStorageBackendStablePath(virStoragePoolObjPtr pool, * the original non-stable dev path */ - stablepath = strdup(devpath); - - if (stablepath == NULL) - virReportOOMError(); + ignore_value(VIR_STRDUP(stablepath, devpath)); return stablepath; } @@ -1556,11 +1549,8 @@ virStorageBackendRunProgRegex(virStoragePoolObjPtr pool, for (j = 0 ; j < nvars[i] ; j++) { /* NB vars[0] is the full pattern, so we offset j by 1 */ p[vars[j+1].rm_eo] = '\0'; - if ((groups[ngroup++] = - strdup(p + vars[j+1].rm_so)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(groups[ngroup++], p + vars[j+1].rm_so) < 0) goto cleanup; - } } /* We're matching on the last regex, so callback time */ diff --git a/src/storage/storage_backend_disk.c b/src/storage/storage_backend_disk.c index 6da2d12..52bd572 100644 --- a/src/storage/storage_backend_disk.c +++ b/src/storage/storage_backend_disk.c @@ -66,17 +66,13 @@ virStorageBackendDiskMakeDataVol(virStoragePoolObjPtr pool, * strip the path to form a reasonable pool-unique name */ tmp = strrchr(groups[0], '/'); - if ((vol->name = strdup(tmp ? tmp + 1 : groups[0])) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(vol->name, tmp ? tmp + 1 : groups[0]) < 0) return -1; - } } if (vol->target.path == NULL) { - if ((devpath = strdup(groups[0])) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(devpath, groups[0]) < 0) return -1; - } /* Now figure out the stable path * @@ -92,10 +88,8 @@ virStorageBackendDiskMakeDataVol(virStoragePoolObjPtr pool, if (vol->key == NULL) { /* XXX base off a unique key of the underlying disk */ - if ((vol->key = strdup(vol->target.path)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(vol->key, vol->target.path) < 0) return -1; - } } if (vol->source.extents == NULL) { @@ -119,11 +113,9 @@ virStorageBackendDiskMakeDataVol(virStoragePoolObjPtr pool, return -1; } - if ((vol->source.extents[0].path = - strdup(pool->def->source.devices[0].path)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(vol->source.extents[0].path, + pool->def->source.devices[0].path) < 0) return -1; - } } /* Refresh allocation/capacity/perms */ @@ -485,10 +477,8 @@ virStorageBackendDiskPartFormat(virStoragePoolObjPtr pool, return -1; } } - if ((*partFormat = strdup(partedFormat)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(*partFormat, partedFormat) < 0) return -1; - } } else { /* create primary partition as long as it is possible and after that check if an extended partition exists @@ -527,10 +517,8 @@ virStorageBackendDiskPartFormat(virStoragePoolObjPtr pool, } } } else { - if ((*partFormat = strdup("primary")) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(*partFormat, "primary") < 0) return -1; - } } return 0; } diff --git a/src/storage/storage_backend_fs.c b/src/storage/storage_backend_fs.c index 8288b1e..9b83e57 100644 --- a/src/storage/storage_backend_fs.c +++ b/src/storage/storage_backend_fs.c @@ -207,11 +207,9 @@ virStorageBackendFileSystemNetFindPoolSourcesFunc(virStoragePoolObjPtr pool ATTR } src->nhost = 1; - if (!(src->hosts[0].name = strdup(state->host)) || - !(src->dir = strdup(path))) { - virReportOOMError(); + if (VIR_STRDUP(src->hosts[0].name, state->host) < 0 || + VIR_STRDUP(src->dir, path) < 0) goto cleanup; - } src->format = VIR_STORAGE_POOL_NETFS_NFS; ret = 0; @@ -395,10 +393,8 @@ virStorageBackendFileSystemMount(virStoragePoolObjPtr pool) { } } else { - if ((src = strdup(pool->def->source.devices[0].path)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(src, pool->def->source.devices[0].path) < 0) return -1; - } } if (netauto) @@ -571,10 +567,8 @@ virStorageBackendFileSystemProbe(const char *device, goto error; } - if ((libblkid_format = strdup(format)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(libblkid_format, format) < 0) goto error; - } names[0] = libblkid_format; names[1] = NULL; @@ -749,10 +743,8 @@ virStorageBackendFileSystemBuild(virConnectPtr conn ATTRIBUTE_UNUSED, goto error; } - if ((parent = strdup(pool->def->target.path)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(parent, pool->def->target.path) < 0) goto error; - } if (!(p = strrchr(parent, '/'))) { virReportError(VIR_ERR_INVALID_ARG, _("path '%s' is not absolute"), @@ -833,8 +825,8 @@ virStorageBackendFileSystemRefresh(virConnectPtr conn ATTRIBUTE_UNUSED, if (VIR_ALLOC(vol) < 0) goto no_memory; - if ((vol->name = strdup(ent->d_name)) == NULL) - goto no_memory; + if (VIR_STRDUP(vol->name, ent->d_name) < 0) + goto cleanup; vol->type = VIR_STORAGE_VOL_FILE; vol->target.format = VIR_STORAGE_FILE_RAW; /* Real value is filled in during probe */ @@ -843,8 +835,8 @@ virStorageBackendFileSystemRefresh(virConnectPtr conn ATTRIBUTE_UNUSED, vol->name) == -1) goto no_memory; - if ((vol->key = strdup(vol->target.path)) == NULL) - goto no_memory; + if (VIR_STRDUP(vol->key, vol->target.path) < 0) + goto cleanup; if ((ret = virStorageBackendProbeTarget(&vol->target, &backingStore, @@ -1011,13 +1003,7 @@ virStorageBackendFileSystemVolCreate(virConnectPtr conn ATTRIBUTE_UNUSED, } VIR_FREE(vol->key); - vol->key = strdup(vol->target.path); - if (vol->key == NULL) { - virReportOOMError(); - return -1; - } - - return 0; + return VIR_STRDUP(vol->key, vol->target.path); } static int createFileDir(virConnectPtr conn ATTRIBUTE_UNUSED, diff --git a/src/storage/storage_backend_iscsi.c b/src/storage/storage_backend_iscsi.c index cf25919..a38f6ff 100644 --- a/src/storage/storage_backend_iscsi.c +++ b/src/storage/storage_backend_iscsi.c @@ -125,13 +125,8 @@ virStorageBackendISCSIExtractSession(virStoragePoolObjPtr pool, { char **session = data; - if (STREQ(groups[1], pool->def->source.devices[0].path)) { - if ((*session = strdup(groups[0])) == NULL) { - virReportOOMError(); - return -1; - } - } - + if (STREQ(groups[1], pool->def->source.devices[0].path)) + return VIR_STRDUP(*session, groups[0]); return 0; } @@ -247,10 +242,8 @@ virStorageBackendIQNFound(const char *initiatoriqn, "of '%s'"), ISCSIADM); goto out; } - *ifacename = strndup(line, token - line); - if (*ifacename == NULL) { + if (VIR_STRNDUP(*ifacename, line, token - line) < 0) { ret = IQN_ERROR; - virReportOOMError(); goto out; } VIR_DEBUG("Found interface '%s' with IQN '%s'", *ifacename, iqn); @@ -499,10 +492,8 @@ virStorageBackendISCSIGetTargets(virStoragePoolObjPtr pool ATTRIBUTE_UNUSED, struct virStorageBackendISCSITargetList *list = data; char *target; - if (!(target = strdup(groups[1]))) { - virReportOOMError(); + if (VIR_STRDUP(target, groups[1]) < 0) return -1; - } if (VIR_REALLOC_N(list->targets, list->ntargets + 1) < 0) { VIR_FREE(target); diff --git a/src/storage/storage_backend_logical.c b/src/storage/storage_backend_logical.c index 316043f..aceb650 100644 --- a/src/storage/storage_backend_logical.c +++ b/src/storage/storage_backend_logical.c @@ -100,10 +100,8 @@ virStorageBackendLogicalMakeVol(virStoragePoolObjPtr pool, is_new_vol = true; vol->type = VIR_STORAGE_VOL_BLOCK; - if ((vol->name = strdup(groups[0])) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(vol->name, groups[0]) < 0) goto cleanup; - } if (VIR_REALLOC_N(pool->volumes.objs, pool->volumes.count + 1)) { @@ -137,11 +135,8 @@ virStorageBackendLogicalMakeVol(virStoragePoolObjPtr pool, vol->backingStore.format = VIR_STORAGE_POOL_LOGICAL_LVM2; } - if (vol->key == NULL && - (vol->key = strdup(groups[2])) == NULL) { - virReportOOMError(); + if (!vol->key && VIR_STRDUP(vol->key, groups[2]) < 0) goto cleanup; - } if (virStorageBackendUpdateVolInfo(vol, 1) < 0) goto cleanup; @@ -179,7 +174,8 @@ virStorageBackendLogicalMakeVol(virStoragePoolObjPtr pool, } /* Now parse the "devices" field separately */ - regex = strdup(regex_unit); + if (VIR_STRDUP(regex, regex_unit) < 0) + goto cleanup; for (i = 1; i < nextents; i++) { if (VIR_REALLOC_N(regex, strlen(regex) + strlen(regex_unit) + 2) < 0) { @@ -229,23 +225,19 @@ virStorageBackendLogicalMakeVol(virStoragePoolObjPtr pool, /* vars[0] is skipped */ for (i = 0; i < nextents; i++) { int j, len; - const char *offset_str = NULL; + char *offset_str = NULL; j = (i * 2) + 1; len = vars[j].rm_eo - vars[j].rm_so; p[vars[j].rm_eo] = '\0'; - if ((vol->source.extents[vol->source.nextent].path = - strndup(p + vars[j].rm_so, len)) == NULL) { - virReportOOMError(); + if (VIR_STRNDUP(vol->source.extents[vol->source.nextent].path, + p + vars[j].rm_so, len) < 0) goto cleanup; - } len = vars[j + 1].rm_eo - vars[j + 1].rm_so; - if (!(offset_str = strndup(p + vars[j + 1].rm_so, len))) { - virReportOOMError(); + if (VIR_STRNDUP(offset_str, p + vars[j + 1].rm_so, len) < 0) goto cleanup; - } if (virStrToLong_ull(offset_str, NULL, 10, &offset) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", @@ -358,13 +350,9 @@ virStorageBackendLogicalFindPoolSourcesFunc(virStoragePoolObjPtr pool ATTRIBUTE_ virStoragePoolSourceDevicePtr dev; virStoragePoolSource *thisSource; - pvname = strdup(groups[0]); - vgname = strdup(groups[1]); - - if (pvname == NULL || vgname == NULL) { - virReportOOMError(); + if (VIR_STRDUP(pvname, groups[0]) < 0 || + VIR_STRDUP(vgname, groups[1]) < 0) goto err_no_memory; - } thisSource = NULL; for (i = 0 ; i < sourceList->nsources; i++) { diff --git a/src/storage/storage_backend_mpath.c b/src/storage/storage_backend_mpath.c index 6e742f7..357c346 100644 --- a/src/storage/storage_backend_mpath.c +++ b/src/storage/storage_backend_mpath.c @@ -99,11 +99,8 @@ virStorageBackendMpathNewVol(virStoragePoolObjPtr pool, } /* XXX should use logical unit's UUID instead */ - vol->key = strdup(vol->target.path); - if (vol->key == NULL) { - virReportOOMError(); + if (VIR_STRDUP(vol->key, vol->target.path) < 0) goto cleanup; - } if (VIR_REALLOC_N(pool->volumes.objs, pool->volumes.count + 1) < 0) { diff --git a/src/storage/storage_backend_rbd.c b/src/storage/storage_backend_rbd.c index 99024e3..953a8ee 100644 --- a/src/storage/storage_backend_rbd.c +++ b/src/storage/storage_backend_rbd.c @@ -334,10 +334,9 @@ static int virStorageBackendRBDRefreshPool(virConnectPtr conn ATTRIBUTE_UNUSED, if (VIR_ALLOC(vol) < 0) goto out_of_memory; - vol->name = strdup(name); - if (vol->name == NULL) { + if (VIR_STRDUP(vol->name, name) < 0) { VIR_FREE(vol); - goto out_of_memory; + goto cleanup; } name += strlen(name) + 1; diff --git a/src/storage/storage_backend_scsi.c b/src/storage/storage_backend_scsi.c index 154a56a..bd6a2a9 100644 --- a/src/storage/storage_backend_scsi.c +++ b/src/storage/storage_backend_scsi.c @@ -188,8 +188,7 @@ virStorageBackendSCSISerial(const char *dev) *nl = '\0'; } else { VIR_FREE(serial); - if (!(serial = strdup(dev))) - virReportOOMError(); + ignore_value(VIR_STRDUP(serial, dev)); } #ifdef WITH_UDEV @@ -333,10 +332,7 @@ getNewStyleBlockDevice(const char *lun_path, continue; } - *block_device = strdup(block_dirent->d_name); - - if (*block_device == NULL) { - virReportOOMError(); + if (VIR_STRDUP(*block_device, block_dirent->d_name) < 0) { closedir(block_dir); retval = -1; goto out; @@ -373,10 +369,7 @@ getOldStyleBlockDevice(const char *lun_path ATTRIBUTE_UNUSED, retval = -1; } else { blockp++; - *block_device = strdup(blockp); - - if (*block_device == NULL) { - virReportOOMError(); + if (VIR_STRDUP(*block_device, blockp) < 0) { retval = -1; goto out; } @@ -630,8 +623,10 @@ getAdapterName(virStoragePoolSourceAdapter adapter) { char *name = NULL; - if (adapter.type != VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST) - return strdup(adapter.data.name); + if (adapter.type != VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST) { + ignore_value(VIR_STRDUP(name, adapter.data.name)); + return name; + } if (!(name = virGetFCHostNameByWWN(NULL, adapter.data.fchost.wwnn, diff --git a/src/storage/storage_backend_sheepdog.c b/src/storage/storage_backend_sheepdog.c index 2e62e6d..b4d7b8e 100644 --- a/src/storage/storage_backend_sheepdog.c +++ b/src/storage/storage_backend_sheepdog.c @@ -269,11 +269,7 @@ virStorageBackendSheepdogRefreshVol(virConnectPtr conn ATTRIBUTE_UNUSED, } VIR_FREE(vol->target.path); - if (!(vol->target.path = strdup(vol->name))) { - virReportOOMError(); - goto cleanup; - } - + ignore_value(VIR_STRDUP(vol->target.path, vol->name)); cleanup: virCommandFree(cmd); return ret; diff --git a/src/storage/storage_driver.c b/src/storage/storage_driver.c index 990f0b1..7cf8193 100644 --- a/src/storage/storage_driver.c +++ b/src/storage/storage_driver.c @@ -144,8 +144,8 @@ storageStateInitialize(bool privileged, storageDriverLock(driverState); if (privileged) { - if ((base = strdup(SYSCONFDIR "/libvirt")) == NULL) - goto out_of_memory; + if (VIR_STRDUP(base, SYSCONFDIR "/libvirt") < 0) + goto error; } else { base = virGetUserConfigDirectory(); if (!base) @@ -336,9 +336,8 @@ storageConnectListStoragePools(virConnectPtr conn, for (i = 0 ; i < driver->pools.count && got < nnames ; i++) { virStoragePoolObjLock(driver->pools.objs[i]); if (virStoragePoolObjIsActive(driver->pools.objs[i])) { - if (!(names[got] = strdup(driver->pools.objs[i]->def->name))) { + if (VIR_STRDUP(names[got], driver->pools.objs[i]->def->name) < 0) { virStoragePoolObjUnlock(driver->pools.objs[i]); - virReportOOMError(); goto cleanup; } got++; @@ -384,9 +383,8 @@ storageConnectListDefinedStoragePools(virConnectPtr conn, for (i = 0 ; i < driver->pools.count && got < nnames ; i++) { virStoragePoolObjLock(driver->pools.objs[i]); if (!virStoragePoolObjIsActive(driver->pools.objs[i])) { - if (!(names[got] = strdup(driver->pools.objs[i]->def->name))) { + if (VIR_STRDUP(names[got], driver->pools.objs[i]->def->name) < 0) { virStoragePoolObjUnlock(driver->pools.objs[i]); - virReportOOMError(); goto cleanup; } got++; @@ -1117,10 +1115,8 @@ storagePoolListVolumes(virStoragePoolPtr obj, } for (i = 0 ; i < pool->volumes.count && n < maxnames ; i++) { - if ((names[n++] = strdup(pool->volumes.objs[i]->name)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(names[n++], pool->volumes.objs[i]->name) < 0) goto cleanup; - } } virStoragePoolObjUnlock(pool); @@ -2340,9 +2336,7 @@ storageVolGetPath(virStorageVolPtr obj) { goto cleanup; } - ret = strdup(vol->target.path); - if (ret == NULL) - virReportOOMError(); + ignore_value(VIR_STRDUP(ret, vol->target.path)); cleanup: if (pool) -- 1.8.1.5

On 05/03/2013 04:53 PM, Michal Privoznik wrote:
--- src/storage/parthelper.c | 5 ++--- src/storage/storage_backend.c | 22 ++++++---------------- src/storage/storage_backend_disk.c | 26 +++++++------------------- src/storage/storage_backend_fs.c | 34 ++++++++++------------------------ src/storage/storage_backend_iscsi.c | 17 ++++------------- src/storage/storage_backend_logical.c | 32 ++++++++++---------------------- src/storage/storage_backend_mpath.c | 5 +---- src/storage/storage_backend_rbd.c | 5 ++--- src/storage/storage_backend_scsi.c | 19 +++++++------------ src/storage/storage_backend_sheepdog.c | 6 +----- src/storage/storage_driver.c | 18 ++++++------------ 11 files changed, 56 insertions(+), 133 deletions(-)
diff --git a/src/storage/storage_backend_logical.c b/src/storage/storage_backend_logical.c index 316043f..aceb650 100644 --- a/src/storage/storage_backend_logical.c +++ b/src/storage/storage_backend_logical.c @@ -358,13 +350,9 @@ virStorageBackendLogicalFindPoolSourcesFunc(virStoragePoolObjPtr pool ATTRIBUTE_ virStoragePoolSourceDevicePtr dev; virStoragePoolSource *thisSource;
- pvname = strdup(groups[0]); - vgname = strdup(groups[1]); - - if (pvname == NULL || vgname == NULL) { - virReportOOMError(); + if (VIR_STRDUP(pvname, groups[0]) < 0 || + VIR_STRDUP(vgname, groups[1]) < 0) goto err_no_memory;
err_no_memory should be renamed to error. But that's pre-existing.
- }
thisSource = NULL; for (i = 0 ; i < sourceList->nsources; i++) {
ACK Jan

--- src/test/test_driver.c | 144 ++++++++++++++++++------------------------------- 1 file changed, 52 insertions(+), 92 deletions(-) diff --git a/src/test/test_driver.c b/src/test/test_driver.c index f60f106..32b200c 100644 --- a/src/test/test_driver.c +++ b/src/test/test_driver.c @@ -219,18 +219,17 @@ testBuildCapabilities(virConnectPtr conn) { caps->host.nsecModels = 1; if (VIR_ALLOC_N(caps->host.secModels, caps->host.nsecModels) < 0) goto no_memory; - caps->host.secModels[0].model = strdup("testSecurity"); - if (!caps->host.secModels[0].model) - goto no_memory; + if (VIR_STRDUP(caps->host.secModels[0].model, "testSecurity") < 0) + goto error; - caps->host.secModels[0].doi = strdup(""); - if (!caps->host.secModels[0].doi) - goto no_memory; + if (VIR_STRDUP(caps->host.secModels[0].doi, "") < 0) + goto error; return caps; no_memory: virReportOOMError(); +error: virObjectUnref(caps); return NULL; } @@ -673,10 +672,14 @@ static char *testBuildFilename(const char *relativeTo, const char *filename) { char *offset; int baseLen; + char *ret; + if (!filename || filename[0] == '\0') return NULL; - if (filename[0] == '/') - return strdup(filename); + if (filename[0] == '/') { + ignore_value(VIR_STRDUP(ret, filename)); + return ret; + } offset = strrchr(relativeTo, '/'); if ((baseLen = (offset-relativeTo+1))) { @@ -691,7 +694,8 @@ static char *testBuildFilename(const char *relativeTo, strcat(absFile, filename); return absFile; } else { - return strdup(filename); + ignore_value(VIR_STRDUP(ret, filename)); + return ret; } } @@ -754,13 +758,8 @@ static int testOpenVolumesForPool(xmlDocPtr xml, } } - if (def->key == NULL) { - def->key = strdup(def->target.path); - if (def->key == NULL) { - virReportOOMError(); - goto error; - } - } + if (!def->key && VIR_STRDUP(def->key, def->target.path) < 0) + goto error; pool->def->allocation += def->allocation; pool->def->available = (pool->def->capacity - @@ -826,10 +825,8 @@ static int testOpenFromFile(virConnectPtr conn, privconn->nextDomID = 1; privconn->numCells = 0; - if ((privconn->path = strdup(file)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(privconn->path, file) < 0) goto error; - } memmove(&privconn->nodeInfo, &defaultNodeInfo, sizeof(defaultNodeInfo)); nodeInfo = &privconn->nodeInfo; @@ -2060,9 +2057,9 @@ cleanup: } static char *testDomainGetOSType(virDomainPtr dom ATTRIBUTE_UNUSED) { - char *ret = strdup("linux"); - if (!ret) - virReportOOMError(); + char *ret; + + ignore_value(VIR_STRDUP_QUIET(ret, "linux")); return ret; } @@ -2720,9 +2717,7 @@ static char *testDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, if (nparams) *nparams = 1; - type = strdup("fair"); - if (!type) - virReportOOMError(); + ignore_value(VIR_STRDUP_QUIET(type, "fair")); return type; } @@ -3020,9 +3015,9 @@ static int testConnectListNetworks(virConnectPtr conn, char **const names, int n for (i = 0 ; i < privconn->networks.count && n < nnames ; i++) { virNetworkObjLock(privconn->networks.objs[i]); if (virNetworkObjIsActive(privconn->networks.objs[i]) && - !(names[n++] = strdup(privconn->networks.objs[i]->def->name))) { + VIR_STRDUP(names[n++], privconn->networks.objs[i]->def->name) < 0) { virNetworkObjUnlock(privconn->networks.objs[i]); - goto no_memory; + goto error; } virNetworkObjUnlock(privconn->networks.objs[i]); } @@ -3030,8 +3025,7 @@ static int testConnectListNetworks(virConnectPtr conn, char **const names, int n return n; -no_memory: - virReportOOMError(); +error: for (n = 0 ; n < nnames ; n++) VIR_FREE(names[n]); testDriverUnlock(privconn); @@ -3063,9 +3057,9 @@ static int testConnectListDefinedNetworks(virConnectPtr conn, char **const names for (i = 0 ; i < privconn->networks.count && n < nnames ; i++) { virNetworkObjLock(privconn->networks.objs[i]); if (!virNetworkObjIsActive(privconn->networks.objs[i]) && - !(names[n++] = strdup(privconn->networks.objs[i]->def->name))) { + VIR_STRDUP(names[n++], privconn->networks.objs[i]->def->name) < 0) { virNetworkObjUnlock(privconn->networks.objs[i]); - goto no_memory; + goto error; } virNetworkObjUnlock(privconn->networks.objs[i]); } @@ -3073,8 +3067,7 @@ static int testConnectListDefinedNetworks(virConnectPtr conn, char **const names return n; -no_memory: - virReportOOMError(); +error: for (n = 0 ; n < nnames ; n++) VIR_FREE(names[n]); testDriverUnlock(privconn); @@ -3381,10 +3374,7 @@ static char *testNetworkGetBridgeName(virNetworkPtr network) { goto cleanup; } - if (!(bridge = strdup(privnet->def->bridge))) { - virReportOOMError(); - goto cleanup; - } + ignore_value(VIR_STRDUP(bridge, privnet->def->bridge)); cleanup: if (privnet) @@ -3494,9 +3484,9 @@ static int testConnectListInterfaces(virConnectPtr conn, char **const names, int for (i = 0 ; (i < privconn->ifaces.count) && (n < nnames); i++) { virInterfaceObjLock(privconn->ifaces.objs[i]); if (virInterfaceObjIsActive(privconn->ifaces.objs[i])) { - if (!(names[n++] = strdup(privconn->ifaces.objs[i]->def->name))) { + if (VIR_STRDUP(names[n++], privconn->ifaces.objs[i]->def->name) < 0) { virInterfaceObjUnlock(privconn->ifaces.objs[i]); - goto no_memory; + goto error; } } virInterfaceObjUnlock(privconn->ifaces.objs[i]); @@ -3505,8 +3495,7 @@ static int testConnectListInterfaces(virConnectPtr conn, char **const names, int return n; -no_memory: - virReportOOMError(); +error: for (n = 0 ; n < nnames ; n++) VIR_FREE(names[n]); testDriverUnlock(privconn); @@ -3540,9 +3529,9 @@ static int testConnectListDefinedInterfaces(virConnectPtr conn, char **const nam for (i = 0 ; (i < privconn->ifaces.count) && (n < nnames); i++) { virInterfaceObjLock(privconn->ifaces.objs[i]); if (!virInterfaceObjIsActive(privconn->ifaces.objs[i])) { - if (!(names[n++] = strdup(privconn->ifaces.objs[i]->def->name))) { + if (VIR_STRDUP(names[n++], privconn->ifaces.objs[i]->def->name) < 0) { virInterfaceObjUnlock(privconn->ifaces.objs[i]); - goto no_memory; + goto error; } } virInterfaceObjUnlock(privconn->ifaces.objs[i]); @@ -3551,7 +3540,7 @@ static int testConnectListDefinedInterfaces(virConnectPtr conn, char **const nam return n; -no_memory: +error: virReportOOMError(); for (n = 0 ; n < nnames ; n++) VIR_FREE(names[n]); @@ -3880,13 +3869,7 @@ static int testStoragePoolObjSetDefaults(virStoragePoolObjPtr pool) { pool->def->allocation = defaultPoolAlloc; pool->def->available = defaultPoolCap - defaultPoolAlloc; - pool->configFile = strdup("\0"); - if (!pool->configFile) { - virReportOOMError(); - return -1; - } - - return 0; + return VIR_STRDUP(pool->configFile, "\0"); } static virDrvOpenStatus testStorageOpen(virConnectPtr conn, @@ -3989,9 +3972,9 @@ testConnectListStoragePools(virConnectPtr conn, for (i = 0 ; i < privconn->pools.count && n < nnames ; i++) { virStoragePoolObjLock(privconn->pools.objs[i]); if (virStoragePoolObjIsActive(privconn->pools.objs[i]) && - !(names[n++] = strdup(privconn->pools.objs[i]->def->name))) { + VIR_STRDUP(names[n++], privconn->pools.objs[i]->def->name) < 0) { virStoragePoolObjUnlock(privconn->pools.objs[i]); - goto no_memory; + goto error; } virStoragePoolObjUnlock(privconn->pools.objs[i]); } @@ -3999,8 +3982,7 @@ testConnectListStoragePools(virConnectPtr conn, return n; -no_memory: - virReportOOMError(); +error: for (n = 0 ; n < nnames ; n++) VIR_FREE(names[n]); testDriverUnlock(privconn); @@ -4036,9 +4018,9 @@ testConnectListDefinedStoragePools(virConnectPtr conn, for (i = 0 ; i < privconn->pools.count && n < nnames ; i++) { virStoragePoolObjLock(privconn->pools.objs[i]); if (!virStoragePoolObjIsActive(privconn->pools.objs[i]) && - !(names[n++] = strdup(privconn->pools.objs[i]->def->name))) { + VIR_STRDUP(names[n++], privconn->pools.objs[i]->def->name) < 0) { virStoragePoolObjUnlock(privconn->pools.objs[i]); - goto no_memory; + goto error; } virStoragePoolObjUnlock(privconn->pools.objs[i]); } @@ -4046,8 +4028,7 @@ testConnectListDefinedStoragePools(virConnectPtr conn, return n; -no_memory: - virReportOOMError(); +error: for (n = 0 ; n < nnames ; n++) VIR_FREE(names[n]); testDriverUnlock(privconn); @@ -4178,9 +4159,7 @@ testConnectFindStoragePoolSources(virConnectPtr conn ATTRIBUTE_UNUSED, switch (pool_type) { case VIR_STORAGE_POOL_LOGICAL: - ret = strdup(defaultPoolSourcesLogicalXML); - if (!ret) - virReportOOMError(); + ignore_value(VIR_STRDUP(ret, defaultPoolSourcesLogicalXML)); break; case VIR_STORAGE_POOL_NETFS: @@ -4648,10 +4627,8 @@ testStoragePoolListVolumes(virStoragePoolPtr pool, } for (i = 0 ; i < privpool->volumes.count && n < maxnames ; i++) { - if ((names[n++] = strdup(privpool->volumes.objs[i]->name)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(names[n++], privpool->volumes.objs[i]->name) < 0) goto cleanup; - } } virStoragePoolObjUnlock(privpool); @@ -4910,11 +4887,8 @@ testStorageVolCreateXML(virStoragePoolPtr pool, goto cleanup; } - privvol->key = strdup(privvol->target.path); - if (privvol->key == NULL) { - virReportOOMError(); + if (VIR_STRDUP(privvol->key, privvol->target.path) < 0) goto cleanup; - } privpool->def->allocation += privvol->allocation; privpool->def->available = (privpool->def->capacity - @@ -5005,11 +4979,8 @@ testStorageVolCreateXMLFrom(virStoragePoolPtr pool, goto cleanup; } - privvol->key = strdup(privvol->target.path); - if (privvol->key == NULL) { - virReportOOMError(); + if (VIR_STRDUP(privvol->key, privvol->target.path) < 0) goto cleanup; - } privpool->def->allocation += privvol->allocation; privpool->def->available = (privpool->def->capacity - @@ -5233,9 +5204,7 @@ testStorageVolGetPath(virStorageVolPtr vol) { goto cleanup; } - ret = strdup(privvol->target.path); - if (ret == NULL) - virReportOOMError(); + ignore_value(VIR_STRDUP_QUIET(ret, privvol->target.path)); cleanup: if (privpool) @@ -5302,7 +5271,7 @@ testNodeListDevices(virConnectPtr conn, virNodeDeviceObjLock(driver->devs.objs[i]); if (cap == NULL || virNodeDeviceHasCap(driver->devs.objs[i], cap)) { - if ((names[ndevs++] = strdup(driver->devs.objs[i]->def->name)) == NULL) { + if (VIR_STRDUP(names[ndevs++], driver->devs.objs[i]->def->name) < 0) { virNodeDeviceObjUnlock(driver->devs.objs[i]); goto failure; } @@ -5393,9 +5362,7 @@ testNodeDeviceGetParent(virNodeDevicePtr dev) } if (obj->def->parent) { - ret = strdup(obj->def->parent); - if (!ret) - virReportOOMError(); + ignore_value(VIR_STRDUP_QUIET(ret, obj->def->parent)); } else { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("no parent for this device")); @@ -5460,9 +5427,9 @@ testNodeDeviceListCaps(virNodeDevicePtr dev, char **const names, int maxnames) } for (caps = obj->def->caps; caps && ncaps < maxnames; caps = caps->next) { - names[ncaps] = strdup(virNodeDevCapTypeToString(caps->type)); - if (names[ncaps++] == NULL) + if (VIR_STRDUP(names[ncaps], virNodeDevCapTypeToString(caps->type)) < 0) goto cleanup; + ncaps++; } ret = ncaps; @@ -5514,10 +5481,8 @@ testNodeDeviceCreateXML(virConnectPtr conn, /* 'name' is supposed to be filled in by the node device backend, which * we don't have. Use WWPN instead. */ VIR_FREE(def->name); - if (!(def->name = strdup(wwpn))) { - virReportOOMError(); + if (VIR_STRDUP(def->name, wwpn) < 0) goto cleanup; - } /* Fill in a random 'host' value, since this would also come from * the backend */ @@ -5568,11 +5533,8 @@ testNodeDeviceDestroy(virNodeDevicePtr dev) goto out; } - parent_name = strdup(obj->def->parent); - if (parent_name == NULL) { - virReportOOMError(); + if (VIR_STRDUP(parent_name, obj->def->parent) < 0) goto out; - } /* virNodeDeviceGetParentHost will cause the device object's lock to be * taken, so we have to dup the parent's name and drop the lock @@ -5778,10 +5740,8 @@ testDomainScreenshot(virDomainPtr dom ATTRIBUTE_UNUSED, virCheckFlags(0, NULL); - if (!(ret = strdup("image/png"))) { - virReportOOMError(); + if (VIR_STRDUP(ret, "image/png") < 0) return NULL; - } if (virFDStreamOpenFile(st, PKGDATADIR "/libvirtLogo.png", 0, 0, O_RDONLY < 0)) VIR_FREE(ret); -- 1.8.1.5

On 05/03/2013 04:53 PM, Michal Privoznik wrote:
--- src/test/test_driver.c | 144 ++++++++++++++++++------------------------------- 1 file changed, 52 insertions(+), 92 deletions(-)
@@ -2060,9 +2057,9 @@ cleanup: }
static char *testDomainGetOSType(virDomainPtr dom ATTRIBUTE_UNUSED) { - char *ret = strdup("linux"); - if (!ret) - virReportOOMError(); + char *ret; + + ignore_value(VIR_STRDUP_QUIET(ret, "linux"));
s/_QUIET//
return ret; }
@@ -2720,9 +2717,7 @@ static char *testDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, if (nparams) *nparams = 1;
- type = strdup("fair"); - if (!type) - virReportOOMError(); + ignore_value(VIR_STRDUP_QUIET(type, "fair"));
return type; }
s/_QUIET//
@@ -3551,7 +3540,7 @@ static int testConnectListDefinedInterfaces(virConnectPtr conn, char **const nam
return n;
-no_memory: +error: virReportOOMError();
extra virReportOOMError()
for (n = 0 ; n < nnames ; n++) VIR_FREE(names[n]); @@ -3880,13 +3869,7 @@ static int testStoragePoolObjSetDefaults(virStoragePoolObjPtr pool) { pool->def->allocation = defaultPoolAlloc; pool->def->available = defaultPoolCap - defaultPoolAlloc;
- pool->configFile = strdup("\0"); - if (!pool->configFile) { - virReportOOMError(); - return -1; - } - - return 0; + return VIR_STRDUP(pool->configFile, "\0");
Change "\0" to "".
}
static virDrvOpenStatus testStorageOpen(virConnectPtr conn, @@ -5233,9 +5204,7 @@ testStorageVolGetPath(virStorageVolPtr vol) { goto cleanup; }
- ret = strdup(privvol->target.path); - if (ret == NULL) - virReportOOMError(); + ignore_value(VIR_STRDUP_QUIET(ret, privvol->target.path));
s/_QUIET//
cleanup: if (privpool) @@ -5393,9 +5362,7 @@ testNodeDeviceGetParent(virNodeDevicePtr dev) }
if (obj->def->parent) { - ret = strdup(obj->def->parent); - if (!ret) - virReportOOMError(); + ignore_value(VIR_STRDUP_QUIET(ret, obj->def->parent)); } else { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("no parent for this device"));
s/_QUIET//
@@ -5460,9 +5427,9 @@ testNodeDeviceListCaps(virNodeDevicePtr dev, char **const names, int maxnames) }
for (caps = obj->def->caps; caps && ncaps < maxnames; caps = caps->next) { - names[ncaps] = strdup(virNodeDevCapTypeToString(caps->type)); - if (names[ncaps++] == NULL) + if (VIR_STRDUP(names[ncaps], virNodeDevCapTypeToString(caps->type)) < 0) goto cleanup; + ncaps++; } ret = ncaps;
You should either keep the increment in the VIR_STRDUP call or delete '--ncaps' from the cleanup section. ACK Jan

--- src/uml/uml_conf.c | 10 ++++------ src/uml/uml_driver.c | 8 +++----- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/src/uml/uml_conf.c b/src/uml/uml_conf.c index a55b5b1..52b705c 100644 --- a/src/uml/uml_conf.c +++ b/src/uml/uml_conf.c @@ -114,8 +114,8 @@ umlConnectTapDevice(virConnectPtr conn, STRPREFIX(net->ifname, VIR_NET_GENERATED_PREFIX) || strchr(net->ifname, '%')) { VIR_FREE(net->ifname); - if (!(net->ifname = strdup(VIR_NET_GENERATED_PREFIX "%d"))) - goto no_memory; + if (VIR_STRDUP(net->ifname, VIR_NET_GENERATED_PREFIX "%d") < 0) + goto error; /* avoid exposing vnet%d in getXMLDesc or error outputs */ template_ifname = true; } @@ -141,8 +141,6 @@ umlConnectTapDevice(virConnectPtr conn, return 0; -no_memory: - virReportOOMError(); error: return -1; } @@ -463,8 +461,8 @@ virCommandPtr umlBuildCommandLine(virConnectPtr conn, if (vm->def->os.cmdline) { char *args, *next_arg; char *cmdline; - if ((cmdline = strdup(vm->def->os.cmdline)) == NULL) - goto no_memory; + if (VIR_STRDUP(cmdline, vm->def->os.cmdline) < 0) + goto error; args = cmdline; while (*args == ' ') diff --git a/src/uml/uml_driver.c b/src/uml/uml_driver.c index 66c00b2..c658a42 100644 --- a/src/uml/uml_driver.c +++ b/src/uml/uml_driver.c @@ -248,8 +248,7 @@ requery: if (res && STRPREFIX(res, "pts:")) { VIR_FREE(def->source.data.file.path); - if ((def->source.data.file.path = strdup(res + 4)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->source.data.file.path, res + 4) < 0) { VIR_FREE(res); VIR_FREE(cmd); return -1; @@ -491,7 +490,7 @@ umlStateInitialize(bool privileged, "%s/log/libvirt/uml", LOCALSTATEDIR) == -1) goto out_of_memory; - if ((base = strdup(SYSCONFDIR "/libvirt")) == NULL) + if (VIR_STRDUP_QUIET(base, SYSCONFDIR "/libvirt") < 0) goto out_of_memory; if (virAsprintf(¨_driver->monitorDir, @@ -1665,8 +1664,7 @@ static char *umlDomainGetOSType(virDomainPtr dom) { goto cleanup; } - if (!(type = strdup(vm->def->os.type))) - virReportOOMError(); + ignore_value(VIR_STRDUP(type, vm->def->os.type)); cleanup: if (vm) -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/uml/uml_conf.c | 10 ++++------ src/uml/uml_driver.c | 8 +++----- 2 files changed, 7 insertions(+), 11 deletions(-)
/me needs to go to bed before my eyes glaze over...
+++ b/src/uml/uml_driver.c @@ -491,7 +490,7 @@ umlStateInitialize(bool privileged, "%s/log/libvirt/uml", LOCALSTATEDIR) == -1) goto out_of_memory;
- if ((base = strdup(SYSCONFDIR "/libvirt")) == NULL) + if (VIR_STRDUP_QUIET(base, SYSCONFDIR "/libvirt") < 0)
Why VIR_STRDUP_QUIET here? Ah, this function was using VIR_ERROR instead of normal virReportOOMError(). I think this is another case where changing from quiet->noisy is probably better. ACK. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/util/virauth.c | 17 +-- src/util/virauthconfig.c | 8 +- src/util/virbitmap.c | 9 +- src/util/vircgroup.c | 36 ++--- src/util/vircommand.c | 33 ++--- src/util/virconf.c | 34 ++--- src/util/virdnsmasq.c | 22 +-- src/util/virebtables.c | 34 ++--- src/util/virebtables.h | 2 +- src/util/virerror.c | 19 +-- src/util/virhash.c | 5 +- src/util/viridentity.c | 15 +- src/util/virinitctl.c | 4 +- src/util/viriptables.c | 4 +- src/util/virjson.c | 18 ++- src/util/virkeyfile.c | 13 +- src/util/virlockspace.c | 25 ++-- src/util/virlog.c | 25 ++-- src/util/virnetdevmacvlan.c | 16 +-- src/util/virnetdevtap.c | 11 +- src/util/virnetdevvportprofile.c | 4 +- src/util/virobject.c | 16 ++- src/util/virpci.c | 14 +- src/util/virsexpr.c | 37 ++--- src/util/virsocketaddr.c | 9 +- src/util/virstoragefile.c | 18 +-- src/util/virstring.c | 17 +-- src/util/virsysinfo.c | 290 ++++++++++++++++----------------------- src/util/virtypedparam.c | 14 +- src/util/viruri.c | 58 ++++---- src/util/virutil.c | 91 +++++------- src/util/virxml.c | 5 +- 32 files changed, 356 insertions(+), 567 deletions(-) diff --git a/src/util/virauth.c b/src/util/virauth.c index fdcefe1..0888c37 100644 --- a/src/util/virauth.c +++ b/src/util/virauth.c @@ -51,8 +51,8 @@ int virAuthGetConfigFilePath(virConnectPtr conn, if (authenv) { VIR_DEBUG("Using path from env '%s'", authenv); - if (!(*path = strdup(authenv))) - goto no_memory; + if (VIR_STRDUP(*path, authenv) < 0) + goto cleanup; return 0; } @@ -62,8 +62,8 @@ int virAuthGetConfigFilePath(virConnectPtr conn, conn->uri->params[i].value) { VIR_DEBUG("Using path from URI '%s'", conn->uri->params[i].value); - if (!(*path = strdup(conn->uri->params[i].value))) - goto no_memory; + if (VIR_STRDUP(*path, conn->uri->params[i].value) < 0) + goto cleanup; return 0; } } @@ -81,8 +81,8 @@ int virAuthGetConfigFilePath(virConnectPtr conn, VIR_FREE(*path); - if (!(*path = strdup(SYSCONFDIR "/libvirt/auth.conf"))) - goto no_memory; + if (VIR_STRDUP(*path, SYSCONFDIR "/libvirt/auth.conf") < 0) + goto cleanup; VIR_DEBUG("Checking for readability of '%s'", *path); if (access(*path, R_OK) == 0) @@ -136,11 +136,8 @@ virAuthGetCredential(virConnectPtr conn, &tmp) < 0) goto cleanup; - if (tmp && - !(*value = strdup(tmp))) { - virReportOOMError(); + if (tmp && VIR_STRDUP(*value, tmp) < 0) goto cleanup; - } ret = 0; diff --git a/src/util/virauthconfig.c b/src/util/virauthconfig.c index 4259cb3..c9f6046 100644 --- a/src/util/virauthconfig.c +++ b/src/util/virauthconfig.c @@ -47,10 +47,8 @@ virAuthConfigPtr virAuthConfigNew(const char *path) goto error; } - if (!(auth->path = strdup(path))) { - virReportOOMError(); + if (VIR_STRDUP(auth->path, path) < 0) goto error; - } if (!(auth->keyfile = virKeyFileNew())) goto error; @@ -77,10 +75,8 @@ virAuthConfigPtr virAuthConfigNewData(const char *path, goto error; } - if (!(auth->path = strdup(path))) { - virReportOOMError(); + if (VIR_STRDUP(auth->path, path) < 0) goto error; - } if (!(auth->keyfile = virKeyFileNew())) goto error; diff --git a/src/util/virbitmap.c b/src/util/virbitmap.c index c81555a..cf6a099 100644 --- a/src/util/virbitmap.c +++ b/src/util/virbitmap.c @@ -37,6 +37,8 @@ #include "count-one-bits.h" #include "virstring.h" +#define VIR_FROM_THIS VIR_FROM_NONE + struct _virBitmap { size_t max_bit; size_t map_len; @@ -226,8 +228,11 @@ char *virBitmapFormat(virBitmapPtr bitmap) return NULL; cur = virBitmapNextSetBit(bitmap, -1); - if (cur < 0) - return strdup(""); + if (cur < 0) { + char *ret; + ignore_value(VIR_STRDUP(ret, "")); + return ret; + } start = prev = cur; while (prev >= 0) { diff --git a/src/util/vircgroup.c b/src/util/vircgroup.c index 473d2fc..b3845ea 100644 --- a/src/util/vircgroup.c +++ b/src/util/vircgroup.c @@ -116,19 +116,14 @@ static int virCgroupCopyMounts(virCgroupPtr group, if (!parent->controllers[i].mountPoint) continue; - group->controllers[i].mountPoint = - strdup(parent->controllers[i].mountPoint); - - if (!group->controllers[i].mountPoint) + if (VIR_STRDUP(group->controllers[i].mountPoint, + parent->controllers[i].mountPoint) < 0) return -ENOMEM; - if (parent->controllers[i].linkPoint) { - group->controllers[i].linkPoint = - strdup(parent->controllers[i].linkPoint); - - if (!group->controllers[i].linkPoint) - return -ENOMEM; - } + if (parent->controllers[i].linkPoint && + VIR_STRDUP(group->controllers[i].linkPoint, + parent->controllers[i].linkPoint) < 0) + return -ENOMEM; } return 0; } @@ -177,8 +172,8 @@ static int virCgroupDetectMounts(virCgroupPtr group) struct stat sb; char *tmp2; - if (!(group->controllers[i].mountPoint = strdup(entry.mnt_dir))) - goto no_memory; + if (VIR_STRDUP(group->controllers[i].mountPoint, entry.mnt_dir) < 0) + goto error; tmp2 = strrchr(entry.mnt_dir, '/'); if (!tmp2) { @@ -239,7 +234,7 @@ static int virCgroupCopyPlacement(virCgroupPtr group, continue; if (path[0] == '/') { - if (!(group->controllers[i].placement = strdup(path))) + if (VIR_STRDUP(group->controllers[i].placement, path) < 0) return -ENOMEM; } else { /* @@ -821,7 +816,7 @@ static int virCgroupNew(const char *path, } if (path[0] == '/' || !parent) { - if (!((*group)->path = strdup(path))) { + if (VIR_STRDUP((*group)->path, path) < 0) { rc = -ENOMEM; goto err; } @@ -1027,7 +1022,7 @@ static int virCgroupAddTaskStrController(virCgroupPtr group, int rc = 0; char *endp; - if (!(str = strdup(pidstr))) + if (VIR_STRDUP(str, pidstr) < 0) return -1; cur = str; @@ -1253,7 +1248,7 @@ int virCgroupNewPartition(const char *path, if (STRNEQ(newpath, "/")) { char *tmp; - if (!(parentPath = strdup(newpath))) { + if (VIR_STRDUP(parentPath, newpath) < 0) { rc = -ENOMEM; goto cleanup; } @@ -2543,12 +2538,11 @@ static char *virCgroupIdentifyRoot(virCgroupPtr group) } tmp[0] = '\0'; - ret = strdup(group->controllers[i].mountPoint); - tmp[0] = '/'; - if (!ret) { - virReportOOMError(); + if (VIR_STRDUP(ret, group->controllers[i].mountPoint) < 0) { + tmp[0] = '/'; return NULL; } + tmp[0] = '/'; return ret; } diff --git a/src/util/vircommand.c b/src/util/vircommand.c index f6f27d9..eecda58 100644 --- a/src/util/vircommand.c +++ b/src/util/vircommand.c @@ -946,9 +946,8 @@ virCommandSetPidFile(virCommandPtr cmd, const char *pidfile) return; VIR_FREE(cmd->pidfile); - if (!(cmd->pidfile = strdup(pidfile))) { + if (VIR_STRDUP(cmd->pidfile, pidfile) < 0) cmd->has_error = ENOMEM; - } } @@ -1049,7 +1048,7 @@ virCommandSetSELinuxLabel(virCommandPtr cmd, #if defined(WITH_SECDRIVER_SELINUX) VIR_FREE(cmd->seLinuxLabel); - if (label && !(cmd->seLinuxLabel = strdup(label))) + if (label && VIR_STRDUP(cmd->seLinuxLabel, label) < 0) cmd->has_error = ENOMEM; #endif return; @@ -1074,7 +1073,7 @@ virCommandSetAppArmorProfile(virCommandPtr cmd, #if defined(WITH_SECDRIVER_APPARMOR) VIR_FREE(cmd->appArmorProfile); - if (profile && !(cmd->appArmorProfile = strdup(profile))) + if (profile && VIR_STRDUP(cmd->appArmorProfile, profile) < 0) cmd->has_error = ENOMEM; #endif return; @@ -1205,7 +1204,7 @@ virCommandAddEnvString(virCommandPtr cmd, const char *str) if (!cmd || cmd->has_error) return; - if (!(env = strdup(str))) { + if (VIR_STRDUP(env, str) < 0) { cmd->has_error = ENOMEM; return; } @@ -1309,7 +1308,7 @@ virCommandAddArg(virCommandPtr cmd, const char *val) if (!cmd || cmd->has_error) return; - if (!(arg = strdup(val))) { + if (VIR_STRDUP(arg, val) < 0) { cmd->has_error = ENOMEM; return; } @@ -1350,11 +1349,11 @@ virCommandAddArgBuffer(virCommandPtr cmd, virBufferPtr buf) } cmd->args[cmd->nargs] = virBufferContentAndReset(buf); - if (!cmd->args[cmd->nargs]) - cmd->args[cmd->nargs] = strdup(""); if (!cmd->args[cmd->nargs]) { - cmd->has_error = ENOMEM; - return; + if (VIR_STRDUP(cmd->args[cmd->nargs], "") < 0) { + cmd->has_error = ENOMEM; + return; + } } cmd->nargs++; } @@ -1440,8 +1439,9 @@ virCommandAddArgSet(virCommandPtr cmd, const char *const*vals) narg = 0; while (vals[narg] != NULL) { - char *arg = strdup(vals[narg++]); - if (!arg) { + char *arg; + + if (VIR_STRDUP(arg, vals[narg++]) < 0) { cmd->has_error = ENOMEM; return; } @@ -1481,8 +1481,7 @@ virCommandAddArgList(virCommandPtr cmd, ...) char *arg = va_arg(list, char *); if (!arg) break; - arg = strdup(arg); - if (!arg) { + if (VIR_STRDUP(arg, arg) < 0) { cmd->has_error = ENOMEM; va_end(list); return; @@ -1511,8 +1510,7 @@ virCommandSetWorkingDirectory(virCommandPtr cmd, const char *pwd) cmd->has_error = -1; VIR_DEBUG("cannot set directory twice"); } else { - cmd->pwd = strdup(pwd); - if (!cmd->pwd) + if (VIR_STRDUP(cmd->pwd, pwd) < 0) cmd->has_error = ENOMEM; } } @@ -1539,8 +1537,7 @@ virCommandSetInputBuffer(virCommandPtr cmd, const char *inbuf) return; } - cmd->inbuf = strdup(inbuf); - if (!cmd->inbuf) + if (VIR_STRDUP(cmd->inbuf, inbuf) < 0) cmd->has_error = ENOMEM; } diff --git a/src/util/virconf.c b/src/util/virconf.c index 16f074a..c578bf4 100644 --- a/src/util/virconf.c +++ b/src/util/virconf.c @@ -23,7 +23,6 @@ #include <config.h> #include <string.h> - #include <stdio.h> #include <unistd.h> #include <sys/types.h> @@ -38,6 +37,7 @@ #include "virlog.h" #include "viralloc.h" #include "virfile.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_CONF @@ -397,11 +397,8 @@ virConfParseString(virConfParserCtxtPtr ctxt) virConfError(ctxt, VIR_ERR_CONF_SYNTAX, _("unterminated string")); return NULL; } - ret = strndup(base, ctxt->cur - base); - if (ret == NULL) { - virReportOOMError(); + if (VIR_STRNDUP(ret, base, ctxt->cur - base) < 0) return NULL; - } NEXT; } else if ((ctxt->cur + 6 < ctxt->end) && (STRPREFIX(ctxt->cur, "\"\"\""))) { @@ -421,11 +418,8 @@ virConfParseString(virConfParserCtxtPtr ctxt) virConfError(ctxt, VIR_ERR_CONF_SYNTAX, _("unterminated string")); return NULL; } - ret = strndup(base, ctxt->cur - base); - if (ret == NULL) { - virReportOOMError(); + if (VIR_STRNDUP(ret, base, ctxt->cur - base) < 0) return NULL; - } ctxt->cur += 3; } else if (CUR == '"') { NEXT; @@ -436,11 +430,8 @@ virConfParseString(virConfParserCtxtPtr ctxt) virConfError(ctxt, VIR_ERR_CONF_SYNTAX, _("unterminated string")); return NULL; } - ret = strndup(base, ctxt->cur - base); - if (ret == NULL) { - virReportOOMError(); + if (VIR_STRNDUP(ret, base, ctxt->cur - base) < 0) return NULL; - } NEXT; } return ret; @@ -577,11 +568,8 @@ virConfParseName(virConfParserCtxtPtr ctxt) ((ctxt->conf->flags & VIR_CONF_FLAG_VMX_FORMAT) && ((CUR == ':') || (CUR == '.') || (CUR == '-'))))) NEXT; - ret = strndup(base, ctxt->cur - base); - if (ret == NULL) { - virReportOOMError(); + if (VIR_STRNDUP(ret, base, ctxt->cur - base) < 0) return NULL; - } return ret; } @@ -604,11 +592,8 @@ virConfParseComment(virConfParserCtxtPtr ctxt) NEXT; base = ctxt->cur; while ((ctxt->cur < ctxt->end) && (!IS_EOL(CUR))) NEXT; - comm = strndup(base, ctxt->cur - base); - if (comm == NULL) { - virReportOOMError(); + if (VIR_STRNDUP(comm, base, ctxt->cur - base) < 0) return -1; - } virConfAddEntry(ctxt->conf, NULL, NULL, comm); return 0; } @@ -680,9 +665,7 @@ virConfParseStatement(virConfParserCtxtPtr ctxt) NEXT; base = ctxt->cur; while ((ctxt->cur < ctxt->end) && (!IS_EOL(CUR))) NEXT; - comm = strndup(base, ctxt->cur - base); - if (comm == NULL) { - virReportOOMError(); + if (VIR_STRNDUP(comm, base, ctxt->cur - base) < 0) { VIR_FREE(name); virConfFreeValue(value); return -1; @@ -905,8 +888,7 @@ virConfSetValue(virConfPtr conf, return -1; } cur->comment = NULL; - if (!(cur->name = strdup(setting))) { - virReportOOMError(); + if (VIR_STRDUP(cur->name, setting) < 0) { virConfFreeValue(value); VIR_FREE(cur); return -1; diff --git a/src/util/virdnsmasq.c b/src/util/virdnsmasq.c index 36f31d2..d37ee3e 100644 --- a/src/util/virdnsmasq.c +++ b/src/util/virdnsmasq.c @@ -118,8 +118,8 @@ addnhostsAdd(dnsmasqAddnHostsfile *addnhostsfile, if (VIR_ALLOC(addnhostsfile->hosts[idx].hostnames) < 0) goto alloc_error; - if (!(addnhostsfile->hosts[idx].ip = strdup(ipstr))) - goto alloc_error; + if (VIR_STRDUP(addnhostsfile->hosts[idx].ip, ipstr) < 0) + goto error; addnhostsfile->hosts[idx].nhostnames = 0; addnhostsfile->nhosts++; @@ -128,9 +128,9 @@ addnhostsAdd(dnsmasqAddnHostsfile *addnhostsfile, if (VIR_REALLOC_N(addnhostsfile->hosts[idx].hostnames, addnhostsfile->hosts[idx].nhostnames + 1) < 0) goto alloc_error; - if (!(addnhostsfile->hosts[idx].hostnames[addnhostsfile->hosts[idx].nhostnames] - = strdup(name))) - goto alloc_error; + if (VIR_STRDUP(addnhostsfile->hosts[idx].hostnames[addnhostsfile->hosts[idx].nhostnames], + name) < 0) + goto error; VIR_FREE(ipstr); @@ -140,6 +140,7 @@ addnhostsAdd(dnsmasqAddnHostsfile *addnhostsfile, alloc_error: virReportOOMError(); + error: VIR_FREE(ipstr); return -1; } @@ -470,10 +471,8 @@ dnsmasqContextNew(const char *network_name, return NULL; } - if (!(ctx->config_dir = strdup(config_dir))) { - virReportOOMError(); + if (VIR_STRDUP(ctx->config_dir, config_dir) < 0) goto error; - } if (!(ctx->hostsfile = hostsfileNew(network_name, config_dir))) goto error; @@ -797,14 +796,15 @@ dnsmasqCapsNewEmpty(const char *binaryPath) return NULL; if (!(caps = virObjectNew(dnsmasqCapsClass))) return NULL; - if (!(caps->flags = virBitmapNew(DNSMASQ_CAPS_LAST))) + if (!(caps->flags = virBitmapNew(DNSMASQ_CAPS_LAST))) { + virReportOOMError(); goto error; - if (!(caps->binaryPath = strdup(binaryPath ? binaryPath : DNSMASQ))) + } + if (VIR_STRDUP(caps->binaryPath, binaryPath ? binaryPath : DNSMASQ) < 0) goto error; return caps; error: - virReportOOMError(); virObjectUnref(caps); return NULL; } diff --git a/src/util/virebtables.c b/src/util/virebtables.c index 6bc6fed..1ac0bd0 100644 --- a/src/util/virebtables.c +++ b/src/util/virebtables.c @@ -51,6 +51,8 @@ #include "virstring.h" #include "virutil.h" +#define VIR_FROM_THIS VIR_FROM_NONE + #if HAVE_FIREWALLD static char *firewall_cmd_path = NULL; @@ -113,7 +115,7 @@ ebtRuleFree(ebtRule *rule) static int ebtRulesAppend(ebtRules *rules, char *rule, - const char **argv, + char **argv, int command_idx) { if (VIR_REALLOC_N(rules->rules, rules->nrules+1) < 0) { @@ -186,10 +188,10 @@ ebtRulesNew(const char *table, if (VIR_ALLOC(rules) < 0) return NULL; - if (!(rules->table = strdup(table))) + if (VIR_STRDUP(rules->table, table) < 0) goto error; - if (!(rules->chain = strdup(chain))) + if (VIR_STRDUP(rules->chain, chain) < 0) goto error; rules->rules = NULL; @@ -207,7 +209,7 @@ ebtablesAddRemoveRule(ebtRules *rules, int action, const char *arg, ...) { va_list args; int retval = ENOMEM; - const char **argv; + char **argv; char *rule = NULL; const char *s; int n, command_idx; @@ -236,36 +238,36 @@ ebtablesAddRemoveRule(ebtRules *rules, int action, const char *arg, ...) #if HAVE_FIREWALLD if (firewall_cmd_path) { - if (!(argv[n++] = strdup(firewall_cmd_path))) + if (VIR_STRDUP(argv[n++], firewall_cmd_path) < 0) goto error; - if (!(argv[n++] = strdup("--direct"))) + if (VIR_STRDUP(argv[n++], "--direct") < 0) goto error; - if (!(argv[n++] = strdup("--passthrough"))) + if (VIR_STRDUP(argv[n++], "--passthrough") < 0) goto error; - if (!(argv[n++] = strdup("eb"))) + if (VIR_STRDUP(argv[n++], "eb") < 0) goto error; } else #endif - if (!(argv[n++] = strdup(EBTABLES_PATH))) + if (VIR_STRDUP(argv[n++], EBTABLES_PATH) < 0) goto error; command_idx = n; if (action == ADD || action == REMOVE) { - if (!(argv[n++] = strdup("--insert"))) + if (VIR_STRDUP(argv[n++], "--insert") < 0) goto error; - if (!(argv[n++] = strdup(rules->chain))) + if (VIR_STRDUP(argv[n++], rules->chain) < 0) goto error; } - if (!(argv[n++] = strdup(arg))) + if (VIR_STRDUP(argv[n++], arg) < 0) goto error; va_start(args, arg); while ((s = va_arg(args, const char *))) { - if (!(argv[n++] = strdup(s))) { + if (VIR_STRDUP(argv[n++], s) < 0) { va_end(args); goto error; } @@ -273,16 +275,16 @@ ebtablesAddRemoveRule(ebtRules *rules, int action, const char *arg, ...) va_end(args); - if (!(rule = virArgvToString(&argv[command_idx]))) + if (!(rule = virArgvToString((const char **) &argv[command_idx]))) goto error; if (action == REMOVE) { VIR_FREE(argv[command_idx]); - if (!(argv[command_idx] = strdup("--delete"))) + if (VIR_STRDUP(argv[command_idx], "--delete") < 0) goto error; } - if (virRun(argv, NULL) < 0) { + if (virRun((const char **)argv, NULL) < 0) { retval = errno; goto error; } diff --git a/src/util/virebtables.h b/src/util/virebtables.h index 671d9dc..3dfe32b 100644 --- a/src/util/virebtables.h +++ b/src/util/virebtables.h @@ -31,7 +31,7 @@ typedef struct { char *rule; - const char **argv; + char **argv; int command_idx; } ebtRule; diff --git a/src/util/virerror.c b/src/util/virerror.c index af4da8c..9b888e5 100644 --- a/src/util/virerror.c +++ b/src/util/virerror.c @@ -164,7 +164,8 @@ virErrorGenericFailure(virErrorPtr err) err->code = VIR_ERR_INTERNAL_ERROR; err->domain = VIR_FROM_NONE; err->level = VIR_ERR_ERROR; - err->message = strdup(_("An error occurred, but the cause is unknown")); + ignore_value(VIR_STRDUP_QUIET(err->message, + _("An error occurred, but the cause is unknown"))); } @@ -184,13 +185,13 @@ virCopyError(virErrorPtr from, to->code = from->code; to->domain = from->domain; to->level = from->level; - if (from->message && !(to->message = strdup(from->message))) + if (from->message && VIR_STRDUP_QUIET(to->message, from->message) < 0) ret = -1; - if (from->str1 && !(to->str1 = strdup(from->str1))) + if (from->str1 && VIR_STRDUP_QUIET(to->str1, from->str1) < 0) ret = -1; - if (from->str2 && !(to->str2 = strdup(from->str2))) + if (from->str2 && VIR_STRDUP_QUIET(to->str2, from->str2) < 0) ret = -1; - if (from->str3 && !(to->str3 = strdup(from->str3))) + if (from->str3 && VIR_STRDUP_QUIET(to->str3, from->str3) < 0) ret = -1; to->int1 = from->int1; to->int2 = from->int2; @@ -646,7 +647,7 @@ virRaiseErrorFull(const char *filename ATTRIBUTE_UNUSED, * formats the message; drop message on OOM situations */ if (fmt == NULL) { - str = strdup(_("No error message provided")); + ignore_value(VIR_STRDUP_QUIET(str, _("No error message provided"))); } else { va_list ap; va_start(ap, fmt); @@ -666,11 +667,11 @@ virRaiseErrorFull(const char *filename ATTRIBUTE_UNUSED, to->message = str; to->level = level; if (str1 != NULL) - to->str1 = strdup(str1); + ignore_value(VIR_STRDUP_QUIET(to->str1, str1)); if (str2 != NULL) - to->str2 = strdup(str2); + ignore_value(VIR_STRDUP_QUIET(to->str2, str2)); if (str3 != NULL) - to->str3 = strdup(str3); + ignore_value(VIR_STRDUP_QUIET(to->str3, str3)); to->int1 = int1; to->int2 = int2; diff --git a/src/util/virhash.c b/src/util/virhash.c index 2fe8751..bb708fc 100644 --- a/src/util/virhash.c +++ b/src/util/virhash.c @@ -30,6 +30,7 @@ #include "virlog.h" #include "virhashcode.h" #include "virrandom.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_NONE @@ -85,7 +86,9 @@ static bool virHashStrEqual(const void *namea, const void *nameb) static void *virHashStrCopy(const void *name) { - return strdup(name); + char *ret; + ignore_value(VIR_STRDUP(ret, name)); + return ret; } static void virHashStrFree(void *name) diff --git a/src/util/viridentity.c b/src/util/viridentity.c index c9efd3f..e2dc048 100644 --- a/src/util/viridentity.c +++ b/src/util/viridentity.c @@ -34,6 +34,7 @@ #include "virobject.h" #include "virthread.h" #include "virutil.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_IDENTITY @@ -150,12 +151,11 @@ virIdentityPtr virIdentityGetSystem(void) _("Unable to lookup SELinux process context")); goto cleanup; } - seccontext = strdup(con); - freecon(con); - if (!seccontext) { - virReportOOMError(); + if (VIR_STRDUP(seccontext, con) < 0) { + freecon(con); goto cleanup; } + freecon(con); #endif if (!(ret = virIdentityNew())) @@ -246,12 +246,7 @@ int virIdentitySetAttr(virIdentityPtr ident, goto cleanup; } - if (!(ident->attrs[attr] = strdup(value))) { - virReportOOMError(); - goto cleanup; - } - - ret = 0; + ret = VIR_STRDUP(ident->attrs[attr], value); cleanup: return ret; diff --git a/src/util/virinitctl.c b/src/util/virinitctl.c index 59db057..b980952 100644 --- a/src/util/virinitctl.c +++ b/src/util/virinitctl.c @@ -137,10 +137,8 @@ int virInitctlSetRunLevel(virInitctlRunLevel level, return -1; } } else { - if (!(path = strdup(VIR_INITCTL_FIFO))) { - virReportOOMError(); + if (VIR_STRDUP(path, VIR_INITCTL_FIFO) < 0) return -1; - } } if ((fd = open(path, O_WRONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY)) < 0) { diff --git a/src/util/viriptables.c b/src/util/viriptables.c index 06a1356..88c3bcd 100644 --- a/src/util/viriptables.c +++ b/src/util/viriptables.c @@ -118,10 +118,10 @@ iptRulesNew(const char *table, if (VIR_ALLOC(rules) < 0) return NULL; - if (!(rules->table = strdup(table))) + if (VIR_STRDUP(rules->table, table) < 0) goto error; - if (!(rules->chain = strdup(chain))) + if (VIR_STRDUP(rules->chain, chain) < 0) goto error; return rules; diff --git a/src/util/virjson.c b/src/util/virjson.c index 92138d3..66376c1 100644 --- a/src/util/virjson.c +++ b/src/util/virjson.c @@ -107,7 +107,7 @@ virJSONValuePtr virJSONValueNewString(const char *data) return NULL; val->type = VIR_JSON_TYPE_STRING; - if (!(val->data.string = strdup(data))) { + if (VIR_STRDUP(val->data.string, data) < 0) { VIR_FREE(val); return NULL; } @@ -126,7 +126,7 @@ virJSONValuePtr virJSONValueNewStringLen(const char *data, size_t length) return NULL; val->type = VIR_JSON_TYPE_STRING; - if (!(val->data.string = strndup(data, length))) { + if (VIR_STRNDUP(val->data.string, data, length) < 0) { VIR_FREE(val); return NULL; } @@ -142,7 +142,7 @@ static virJSONValuePtr virJSONValueNewNumber(const char *data) return NULL; val->type = VIR_JSON_TYPE_NUMBER; - if (!(val->data.number = strdup(data))) { + if (VIR_STRDUP(val->data.number, data) < 0) { VIR_FREE(val); return NULL; } @@ -269,7 +269,7 @@ int virJSONValueObjectAppend(virJSONValuePtr object, const char *key, virJSONVal if (virJSONValueObjectHasKey(object, key)) return -1; - if (!(newkey = strdup(key))) + if (VIR_STRDUP(newkey, key) < 0) return -1; if (VIR_REALLOC_N(object->data.object.pairs, @@ -751,10 +751,10 @@ static int virJSONParserHandleNumber(void *ctx, yajl_size_t l) { virJSONParserPtr parser = ctx; - char *str = strndup(s, l); + char *str; virJSONValuePtr value; - if (!str) + if (VIR_STRNDUP(str, s, l) < 0) return -1; value = virJSONValueNewNumber(str); VIR_FREE(str); @@ -808,8 +808,7 @@ static int virJSONParserHandleMapKey(void *ctx, state = &parser->state[parser->nstate-1]; if (state->key) return 0; - state->key = strndup((const char *)stringVal, stringLen); - if (!state->key) + if (VIR_STRNDUP(state->key, (const char *)stringVal, stringLen) < 0) return 0; return 1; } @@ -1094,8 +1093,7 @@ char *virJSONValueToString(virJSONValuePtr object, goto cleanup; } - if (!(ret = strdup((const char *)str))) - virReportOOMError(); + ignore_value(VIR_STRDUP(ret, (const char *)str)); cleanup: yajl_gen_free(g); diff --git a/src/util/virkeyfile.c b/src/util/virkeyfile.c index d77e95d..c589ab2 100644 --- a/src/util/virkeyfile.c +++ b/src/util/virkeyfile.c @@ -32,6 +32,7 @@ #include "virhash.h" #include "virkeyfile.h" #include "virerror.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_CONF @@ -121,10 +122,8 @@ static int virKeyFileParseGroup(virKeyFileParserCtxtPtr ctxt) return -1; } - if (!(ctxt->groupname = strndup(name, ctxt->cur - name))) { - virReportOOMError(); + if (VIR_STRNDUP(ctxt->groupname, name, ctxt->cur - name) < 0) return -1; - } NEXT; @@ -167,10 +166,8 @@ static int virKeyFileParseValue(virKeyFileParserCtxtPtr ctxt) return -1; } - if (!(key = strndup(keystart, ctxt->cur - keystart))) { - virReportOOMError(); + if (VIR_STRNDUP(key, keystart, ctxt->cur - keystart) < 0) return -1; - } NEXT; valuestart = ctxt->cur; @@ -183,10 +180,8 @@ static int virKeyFileParseValue(virKeyFileParserCtxtPtr ctxt) len = ctxt->cur - valuestart; if (IS_EOF && !IS_EOL(CUR)) len++; - if (!(value = strndup(valuestart, len))) { - virReportOOMError(); + if (VIR_STRNDUP(value, valuestart, len) < 0) goto cleanup; - } if (virHashAddEntry(ctxt->group, key, value) < 0) { VIR_FREE(value); diff --git a/src/util/virlockspace.c b/src/util/virlockspace.c index 620a460..060ac2f 100644 --- a/src/util/virlockspace.c +++ b/src/util/virlockspace.c @@ -70,10 +70,8 @@ static char *virLockSpaceGetResourcePath(virLockSpacePtr lockspace, return NULL; } } else { - if (!(ret = strdup(resname))) { - virReportOOMError(); + if (VIR_STRDUP(ret, resname) < 0) return NULL; - } } return ret; @@ -132,8 +130,8 @@ virLockSpaceResourceNew(virLockSpacePtr lockspace, res->fd = -1; res->flags = flags; - if (!(res->name = strdup(resname))) - goto no_memory; + if (VIR_STRDUP(res->name, resname) < 0) + goto error; if (!(res->path = virLockSpaceGetResourcePath(lockspace, resname))) goto no_memory; @@ -262,9 +260,8 @@ virLockSpacePtr virLockSpaceNew(const char *directory) return NULL; } - if (directory && - !(lockspace->dir = strdup(directory))) - goto no_memory; + if (directory && VIR_STRDUP(lockspace->dir, directory) < 0) + goto error; if (!(lockspace->resources = virHashCreate(VIR_LOCKSPACE_TABLE_SIZE, virLockSpaceResourceDataFree))) @@ -290,8 +287,6 @@ virLockSpacePtr virLockSpaceNew(const char *directory) return lockspace; -no_memory: - virReportOOMError(); error: virLockSpaceFree(lockspace); return NULL; @@ -324,10 +319,8 @@ virLockSpacePtr virLockSpaceNewPostExecRestart(virJSONValuePtr object) if (virJSONValueObjectHasKey(object, "directory")) { const char *dir = virJSONValueObjectGetString(object, "directory"); - if (!(lockspace->dir = strdup(dir))) { - virReportOOMError(); + if (VIR_STRDUP(lockspace->dir, dir) < 0) goto error; - } } if (!(resources = virJSONValueObjectGet(object, "resources"))) { @@ -362,8 +355,7 @@ virLockSpacePtr virLockSpaceNewPostExecRestart(virJSONValuePtr object) virLockSpaceResourceFree(res); goto error; } - if (!(res->name = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(res->name, tmp) < 0) { virLockSpaceResourceFree(res); goto error; } @@ -374,8 +366,7 @@ virLockSpacePtr virLockSpaceNewPostExecRestart(virJSONValuePtr object) virLockSpaceResourceFree(res); goto error; } - if (!(res->path = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(res->path, tmp) < 0) { virLockSpaceResourceFree(res); goto error; } diff --git a/src/util/virlog.c b/src/util/virlog.c index eee9ddc..2ed0b10 100644 --- a/src/util/virlog.c +++ b/src/util/virlog.c @@ -557,8 +557,7 @@ virLogDefineFilter(const char *match, } } - mdup = strdup(match); - if (mdup == NULL) { + if (VIR_STRDUP(mdup, match) < 0) { i = -1; goto cleanup; } @@ -664,13 +663,9 @@ virLogDefineOutput(virLogOutputFunc f, if (f == NULL) return -1; - if (dest == VIR_LOG_TO_SYSLOG || dest == VIR_LOG_TO_FILE) { - if (name == NULL) - return -1; - ndup = strdup(name); - if (ndup == NULL) - return -1; - } + if ((dest == VIR_LOG_TO_SYSLOG || dest == VIR_LOG_TO_FILE) && + (!name || VIR_STRDUP(ndup, name) < 0)) + return -1; virLogLock(); if (VIR_REALLOC_N(virLogOutputs, virLogNbOutputs + 1)) { @@ -1047,8 +1042,7 @@ virLogAddOutputToSyslog(virLogPriority priority, * ident needs to be kept around on Solaris */ VIR_FREE(current_ident); - current_ident = strdup(ident); - if (current_ident == NULL) + if (VIR_STRDUP(current_ident, ident) < 0) return -1; openlog(current_ident, 0, 0); @@ -1329,8 +1323,7 @@ virLogParseOutputs(const char *outputs) if (str == cur) goto cleanup; #if HAVE_SYSLOG_H - name = strndup(str, cur - str); - if (name == NULL) + if (VIR_STRNDUP(name, str, cur - str) < 0) goto cleanup; if (virLogAddOutputToSyslog(prio, name) == 0) count++; @@ -1346,8 +1339,7 @@ virLogParseOutputs(const char *outputs) cur++; if (str == cur) goto cleanup; - name = strndup(str, cur - str); - if (name == NULL) + if (VIR_STRNDUP(name, str, cur - str) < 0) goto cleanup; if (virFileAbsPath(name, &abspath) < 0) { VIR_FREE(name); @@ -1424,8 +1416,7 @@ virLogParseFilters(const char *filters) cur++; if (str == cur) goto cleanup; - name = strndup(str, cur - str); - if (name == NULL) + if (VIR_STRNDUP(name, str, cur - str) < 0) goto cleanup; if (virLogDefineFilter(name, prio, flags) >= 0) count++; diff --git a/src/util/virnetdevmacvlan.c b/src/util/virnetdevmacvlan.c index 0c4fcbd..93bf798 100644 --- a/src/util/virnetdevmacvlan.c +++ b/src/util/virnetdevmacvlan.c @@ -31,6 +31,7 @@ #include "virmacaddr.h" #include "virerror.h" #include "virthread.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_NET @@ -764,14 +765,14 @@ virNetDevMacVLanVPortProfileRegisterCallback(const char *ifname, if (virtPortProfile && virNetlinkEventServiceIsRunning(NETLINK_ROUTE)) { if (VIR_ALLOC(calld) < 0) goto memory_error; - if ((calld->cr_ifname = strdup(ifname)) == NULL) - goto memory_error; + if (VIR_STRDUP(calld->cr_ifname, ifname) < 0) + goto error; if (VIR_ALLOC(calld->virtPortProfile) < 0) goto memory_error; memcpy(calld->virtPortProfile, virtPortProfile, sizeof(*virtPortProfile)); virMacAddrSet(&calld->macaddress, macaddress); - if ((calld->linkdev = strdup(linkdev)) == NULL) - goto memory_error; + if (VIR_STRDUP(calld->linkdev, linkdev) < 0) + goto error; memcpy(calld->vmuuid, vmuuid, sizeof(calld->vmuuid)); calld->vmOp = vmOp; @@ -927,16 +928,13 @@ create_name: VIR_FORCE_CLOSE(rc); /* sets rc to -1 */ goto disassociate_exit; } - if (!(*res_ifname = strdup(cr_ifname))) { + if (VIR_STRDUP(*res_ifname, cr_ifname) < 0) { VIR_FORCE_CLOSE(rc); /* sets rc to -1 */ - virReportOOMError(); goto disassociate_exit; } } else { - if (!(*res_ifname = strdup(cr_ifname))) { - virReportOOMError(); + if (VIR_STRDUP(*res_ifname, cr_ifname) < 0) goto disassociate_exit; - } rc = 0; } diff --git a/src/util/virnetdevtap.c b/src/util/virnetdevtap.c index 75599db..08a5599 100644 --- a/src/util/virnetdevtap.c +++ b/src/util/virnetdevtap.c @@ -64,12 +64,7 @@ virNetDevTapGetName(int tapfd ATTRIBUTE_UNUSED, char **ifname ATTRIBUTE_UNUSED) return -1; } - *ifname = strdup(ifr.ifr_name); - if (*ifname == NULL) { - virReportOOMError(); - return -1; - } - return 0; + return VIR_STRDUP(*ifname, ifr.ifr_name); #else return -1; #endif @@ -204,10 +199,8 @@ int virNetDevTapCreate(char **ifname, } VIR_FREE(*ifname); - if (!(*ifname = strdup(ifr.ifr_name))) { - virReportOOMError(); + if (VIR_STRDUP(*ifname, ifr.ifr_name) < 0) goto cleanup; - } if (tapfd) *tapfd = fd; else diff --git a/src/util/virnetdevvportprofile.c b/src/util/virnetdevvportprofile.c index 883aa46..c337fb3 100644 --- a/src/util/virnetdevvportprofile.c +++ b/src/util/virnetdevvportprofile.c @@ -1034,9 +1034,7 @@ virNetDevVPortProfileOp8021Qbh(const char *ifname, goto cleanup; } } else { - physfndev = strdup(ifname); - if (!physfndev) { - virReportOOMError(); + if (VIR_STRDUP(physfndev, ifname) < 0) { rc = -1; goto cleanup; } diff --git a/src/util/virobject.c b/src/util/virobject.c index 93e37e4..72a5248 100644 --- a/src/util/virobject.c +++ b/src/util/virobject.c @@ -28,6 +28,7 @@ #include "viratomic.h" #include "virerror.h" #include "virlog.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_NONE @@ -37,7 +38,7 @@ struct _virClass { virClassPtr parent; unsigned int magic; - const char *name; + char *name; size_t objectSize; virObjectDisposeCallback dispose; @@ -131,21 +132,22 @@ virClassPtr virClassNew(virClassPtr parent, return NULL; } - if (VIR_ALLOC(klass) < 0) - goto no_memory; + if (VIR_ALLOC(klass) < 0) { + virReportOOMError(); + goto error; + } klass->parent = parent; - if (!(klass->name = strdup(name))) - goto no_memory; + if (VIR_STRDUP(klass->name, name) < 0) + goto error; klass->magic = virAtomicIntInc(&magicCounter); klass->objectSize = objectSize; klass->dispose = dispose; return klass; -no_memory: +error: VIR_FREE(klass); - virReportOOMError(); return NULL; } diff --git a/src/util/virpci.c b/src/util/virpci.c index 5865613..1f19d3f 100644 --- a/src/util/virpci.c +++ b/src/util/virpci.c @@ -947,10 +947,8 @@ virPCIDeviceUnbindFromStub(virPCIDevicePtr dev) goto cleanup; } /* drvdir = "/sys/bus/pci/drivers/${drivername}" */ - if (!(driver = strdup(last_component(drvdir)))) { - virReportOOMError(); + if (VIR_STRDUP(driver, last_component(drvdir)) < 0) goto cleanup; - } if (!dev->unbind_from_stub) goto remove_slot; @@ -1392,10 +1390,8 @@ virPCIGetAddrString(unsigned int domain, dev = virPCIDeviceNew(domain, bus, slot, function); if (dev != NULL) { - if ((*pciConfigAddr = strdup(dev->name)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(*pciConfigAddr, dev->name) < 0) goto cleanup; - } ret = 0; } @@ -2268,11 +2264,7 @@ virPCIGetNetName(char *device_link_sysfs_path, char **netname) continue; /* Assume a single directory entry */ - *netname = strdup(entry->d_name); - if (!*netname) - virReportOOMError(); - else - ret = 0; + ret = VIR_STRDUP(*netname, entry->d_name); break; } diff --git a/src/util/virsexpr.c b/src/util/virsexpr.c index 23b6781..b17c0d4 100644 --- a/src/util/virsexpr.c +++ b/src/util/virsexpr.c @@ -119,16 +119,10 @@ sexpr_string(const char *str, ssize_t len) if (ret == NULL) return ret; ret->kind = SEXPR_VALUE; - if (len > 0) { - ret->u.value = strndup(str, len); - } else { - ret->u.value = strdup(str); - } - if (ret->u.value == NULL) { + if ((len > 0 && VIR_STRNDUP(ret->u.value, str, len) < 0) || + (len <= 0 && VIR_STRDUP(ret->u.value, str) < 0)) VIR_FREE(ret); - return NULL; - } return ret; } @@ -325,11 +319,8 @@ _string2sexpr(const char *buffer, size_t * end) ptr++; } - ret->u.value = strndup(start, ptr - start); - if (ret->u.value == NULL) { - virReportOOMError(); + if (VIR_STRNDUP(ret->u.value, start, ptr - start) < 0) goto error; - } if (*ptr == '\'') ptr++; @@ -341,11 +332,8 @@ _string2sexpr(const char *buffer, size_t * end) ptr++; } - ret->u.value = strndup(start, ptr - start); - if (ret->u.value == NULL) { - virReportOOMError(); + if (VIR_STRNDUP(ret->u.value, start, ptr - start) < 0) goto error; - } } ret->kind = SEXPR_VALUE; @@ -403,12 +391,8 @@ sexpr_lookup_key(const struct sexpr *sexpr, const char *node) if ((node == NULL) || (sexpr == NULL)) return NULL; - buffer = strdup(node); - - if (buffer == NULL) { - virReportOOMError(); + if (VIR_STRDUP(buffer, node) < 0) return NULL; - } ptr = buffer; token = strsep(&ptr, "/"); @@ -527,13 +511,10 @@ int sexpr_node_copy(const struct sexpr *sexpr, const char *node, char **dst) { const char *val = sexpr_node(sexpr, node); - if (val && *val) { - *dst = strdup(val); - if (!(*dst)) - return -1; - } else { - *dst = NULL; - } + if (val && *val) + return VIR_STRDUP(*dst, val); + + *dst = NULL; return 0; } diff --git a/src/util/virsocketaddr.c b/src/util/virsocketaddr.c index d6a0d93..1a6714e 100644 --- a/src/util/virsocketaddr.c +++ b/src/util/virsocketaddr.c @@ -272,8 +272,8 @@ virSocketAddrFormatFull(virSocketAddrPtr addr, separator ? separator : ":") < 0) goto no_memory; } else { - if (!(addrstr = strdup("127.0.0.1"))) - goto no_memory; + if (VIR_STRDUP(addrstr, "127.0.0.1") < 0) + goto error; } return addrstr; } @@ -293,14 +293,15 @@ virSocketAddrFormatFull(virSocketAddrPtr addr, if (virAsprintf(&addrstr, "%s%s%s", host, separator, port) == -1) goto no_memory; } else { - if (!(addrstr = strdup(host))) - goto no_memory; + if (VIR_STRDUP(addrstr, host) < 0) + goto error; } return addrstr; no_memory: virReportOOMError(); +error: return NULL; } diff --git a/src/util/virstoragefile.c b/src/util/virstoragefile.c index c7bb85a..125f014 100644 --- a/src/util/virstoragefile.c +++ b/src/util/virstoragefile.c @@ -228,11 +228,8 @@ cowGetBackingStore(char **res, return BACKING_STORE_OK; } - *res = strndup((const char*)buf + 4+4, COW_FILENAME_MAXLEN); - if (*res == NULL) { - virReportOOMError(); + if (VIR_STRNDUP(*res, (const char*)buf + 4+4, COW_FILENAME_MAXLEN) < 0) return BACKING_STORE_ERROR; - } return BACKING_STORE_OK; } @@ -440,11 +437,8 @@ vmdk4GetBackingStore(char **res, goto cleanup; } *end = '\0'; - *res = strdup(start); - if (*res == NULL) { - virReportOOMError(); + if (VIR_STRDUP(*res, start) < 0) goto cleanup; - } ret = BACKING_STORE_OK; @@ -775,9 +769,7 @@ virStorageFileGetMetadataInternal(const char *path, meta->backingStoreIsFile = false; if (backing != NULL) { - meta->backingStore = strdup(backing); - if (meta->backingStore == NULL) { - virReportOOMError(); + if (VIR_STRDUP(meta->backingStore, backing) < 0) { VIR_FREE(backing); goto cleanup; } @@ -1096,10 +1088,8 @@ int virStorageFileIsSharedFSType(const char *path, struct statfs sb; int statfs_ret; - if ((dirpath = strdup(path)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(dirpath, path) < 0) return -1; - } do { diff --git a/src/util/virstring.c b/src/util/virstring.c index 394a558..13c2420 100644 --- a/src/util/virstring.c +++ b/src/util/virstring.c @@ -85,8 +85,8 @@ char **virStringSplit(const char *string, if (VIR_RESIZE_N(tokens, maxtokens, ntokens, 1) < 0) goto no_memory; - if (!(tokens[ntokens] = strndup(remainder, len))) - goto no_memory; + if (VIR_STRNDUP(tokens[ntokens], remainder, len) < 0) + goto error; ntokens++; remainder = tmp + delimlen; tmp = strstr(remainder, delim); @@ -96,8 +96,8 @@ char **virStringSplit(const char *string, if (VIR_RESIZE_N(tokens, maxtokens, ntokens, 1) < 0) goto no_memory; - if (!(tokens[ntokens] = strdup(remainder))) - goto no_memory; + if (VIR_STRDUP(tokens[ntokens], remainder) < 0) + goto error; ntokens++; } @@ -109,6 +109,7 @@ char **virStringSplit(const char *string, no_memory: virReportOOMError(); +error: for (i = 0 ; i < ntokens ; i++) VIR_FREE(tokens[i]); VIR_FREE(tokens); @@ -144,12 +145,8 @@ char *virStringJoin(const char **strings, return NULL; } ret = virBufferContentAndReset(&buf); - if (!ret) { - if (!(ret = strdup(""))) { - virReportOOMError(); - return NULL; - } - } + if (!ret) + ignore_value(VIR_STRDUP(ret, "")); return ret; } diff --git a/src/util/virsysinfo.c b/src/util/virsysinfo.c index 2efe634..7fd2537 100644 --- a/src/util/virsysinfo.c +++ b/src/util/virsysinfo.c @@ -144,32 +144,26 @@ virSysinfoParseSystem(const char *base, virSysinfoDefPtr ret) cur = strchr(cur, ':') + 1; eol = strchr(cur, '\n'); virSkipSpaces(&cur); - if (eol && - ((ret->system_family = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_family, cur, eol - cur) < 0) + return -1; if ((cur = strstr(base, "model")) != NULL) { cur = strchr(cur, ':') + 1; eol = strchr(cur, '\n'); virSkipSpaces(&cur); - if (eol && ((ret->system_serial = strndup(cur, eol - cur)) - == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_serial, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "machine")) != NULL) { cur = strchr(cur, ':') + 1; eol = strchr(cur, '\n'); virSkipSpaces(&cur); - if (eol && ((ret->system_version = strndup(cur, eol - cur)) - == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_version, cur, eol - cur) < 0) + return -1; } return 0; - -no_memory: - return -1; } static int @@ -185,34 +179,31 @@ virSysinfoParseProcessor(const char *base, virSysinfoDefPtr ret) cur = strchr(base, ':') + 1; if (VIR_EXPAND_N(ret->processor, ret->nprocessor, 1) < 0) { - goto no_memory; + return -1; } processor = &ret->processor[ret->nprocessor - 1]; virSkipSpaces(&cur); - if (eol && - ((processor->processor_socket_destination = strndup - (cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor->processor_socket_destination, + cur, eol - cur) < 0) + return -1; if ((cur = strstr(base, "cpu")) != NULL) { cur = strchr(cur, ':') + 1; eol = strchr(cur, '\n'); virSkipSpaces(&cur); - if (eol && - ((processor->processor_type = strndup(cur, eol - cur)) - == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor->processor_type, + cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "revision")) != NULL) { cur = strchr(cur, ':') + 1; eol = strchr(cur, '\n'); virSkipSpaces(&cur); - if (eol && - ((processor->processor_version = strndup(cur, eol - cur)) - == NULL)) - goto no_memory; + if (eol && VIR_STRNUDP(processor->processor_version, + cur, eol - cur) < 0) + return -1; } base = cur; @@ -270,32 +261,26 @@ virSysinfoParseSystem(const char *base, virSysinfoDefPtr ret) cur = strchr(cur, ':') + 1; eol = strchr(cur, '\n'); virSkipSpaces(&cur); - if (eol && - ((ret->system_family = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_family, cur, eol - cur) < 0) + return -1; if ((cur = strstr(base, "model")) != NULL) { cur = strchr(cur, ':') + 1; eol = strchr(cur, '\n'); virSkipSpaces(&cur); - if (eol && ((ret->system_serial = strndup(cur, eol - cur)) - == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_serial, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "machine")) != NULL) { cur = strchr(cur, ':') + 1; eol = strchr(cur, '\n'); virSkipSpaces(&cur); - if (eol && ((ret->system_version = strndup(cur, eol - cur)) - == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_version, cur, eol - cur) < 0) + return -1; } return 0; - -no_memory: - return -1; } static int @@ -313,10 +298,8 @@ virSysinfoParseProcessor(const char *base, virSysinfoDefPtr ret) eol = strchr(base, '\n'); cur = strchr(base, ':') + 1; virSkipSpaces(&cur); - if (eol && - ((processor_type = strndup(cur, eol - cur)) - == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor_type, cur, eol - cur) < 0) + goto error; base = cur; while ((tmp_base = strstr(base, "processor")) != NULL) { @@ -325,19 +308,20 @@ virSysinfoParseProcessor(const char *base, virSysinfoDefPtr ret) cur = strchr(base, ':') + 1; if (VIR_EXPAND_N(ret->processor, ret->nprocessor, 1) < 0) { - goto no_memory; + virReportOOMError(); + goto error; } processor = &ret->processor[ret->nprocessor - 1]; virSkipSpaces(&cur); if (eol && - ((processor->processor_socket_destination = strndup - (cur, eol - cur)) == NULL)) - goto no_memory; + VIR_STRNDUP(processor->processor_socket_destination, + cur, eol - cur) < 0) + goto error; if (processor_type && - !(processor->processor_type = strdup(processor_type))) - goto no_memory; + VIR_STRDUP(processor->processor_type, processor_type) < 0) + goto error; base = cur; } @@ -345,7 +329,7 @@ virSysinfoParseProcessor(const char *base, virSysinfoDefPtr ret) VIR_FREE(processor_type); return 0; -no_memory: +error: VIR_FREE(processor_type); return -1; } @@ -408,15 +392,11 @@ virSysinfoParseDelimited(const char *base, const char *name, char **value, start += 1; end = strchrnul(start, delim2); virSkipSpaces(&start); - if (!((*value) = strndup(start, end - start))) { - virReportOOMError(); - goto error; - } + if (VIR_STRNDUP(*value, start, end - start) < 0) + return NULL; virTrimSpaces(*value, NULL); return end; } - -error: return NULL; } @@ -462,7 +442,8 @@ virSysinfoParseProcessor(const char *base, virSysinfoDefPtr ret) goto cleanup; } processor = &ret->processor[ret->nprocessor - 1]; - processor->processor_manufacturer = strdup(manufacturer); + if (VIR_STRDUP(processor->processor_manufacturer, manufacturer) < 0) + goto cleanup; if (!virSysinfoParseDelimited(procline, "version", &processor->processor_version, '=', ',') || @@ -556,32 +537,29 @@ virSysinfoParseBIOS(const char *base, virSysinfoDefPtr ret) if ((cur = strstr(base, "Vendor: ")) != NULL) { cur += 8; eol = strchr(cur, '\n'); - if ((eol) && ((ret->bios_vendor = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->bios_vendor, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Version: ")) != NULL) { cur += 9; eol = strchr(cur, '\n'); - if ((eol) && ((ret->bios_version = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->bios_version, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Release Date: ")) != NULL) { cur += 14; eol = strchr(cur, '\n'); - if ((eol) && ((ret->bios_date = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->bios_date, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "BIOS Revision: ")) != NULL) { cur += 15; eol = strchr(cur, '\n'); - if ((eol) && ((ret->bios_release = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->bios_release, cur, eol - cur) < 0) + return -1; } return 0; - -no_memory: - return -1; } static int @@ -596,51 +574,47 @@ virSysinfoParseSystem(const char *base, virSysinfoDefPtr ret) if ((cur = strstr(base, "Manufacturer: ")) != NULL) { cur += 14; eol = strchr(cur, '\n'); - if ((eol) && - ((ret->system_manufacturer = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_manufacturer, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Product Name: ")) != NULL) { cur += 14; eol = strchr(cur, '\n'); - if ((eol) && ((ret->system_product = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_product, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Version: ")) != NULL) { cur += 9; eol = strchr(cur, '\n'); - if ((eol) && ((ret->system_version = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_version, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Serial Number: ")) != NULL) { cur += 15; eol = strchr(cur, '\n'); - if ((eol) && ((ret->system_serial = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_serial, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "UUID: ")) != NULL) { cur += 6; eol = strchr(cur, '\n'); - if ((eol) && ((ret->system_uuid = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_uuid, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "SKU Number: ")) != NULL) { cur += 12; eol = strchr(cur, '\n'); - if ((eol) && ((ret->system_sku = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_sku, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Family: ")) != NULL) { cur += 8; eol = strchr(cur, '\n'); - if ((eol) && ((ret->system_family = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_family, cur, eol - cur) < 0) + return -1; } return 0; - -no_memory: - return -1; } static int @@ -654,117 +628,100 @@ virSysinfoParseProcessor(const char *base, virSysinfoDefPtr ret) base = tmp_base; eol = NULL; - if (VIR_EXPAND_N(ret->processor, ret->nprocessor, 1) < 0) { - goto no_memory; - } + if (VIR_EXPAND_N(ret->processor, ret->nprocessor, 1) < 0) + return -1; processor = &ret->processor[ret->nprocessor - 1]; if ((cur = strstr(base, "Socket Designation: ")) != NULL) { cur += 20; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((processor->processor_socket_destination - = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor->processor_socket_destination, + cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Type: ")) != NULL) { cur += 6; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((processor->processor_type = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor->processor_type, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Family: ")) != NULL) { cur += 8; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((processor->processor_family = strndup(cur, - eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor->processor_family, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Manufacturer: ")) != NULL) { cur += 14; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((processor->processor_manufacturer - = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor->processor_manufacturer, + cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Signature: ")) != NULL) { cur += 11; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((processor->processor_signature - = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor->processor_signature, + cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Version: ")) != NULL) { cur += 9; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((processor->processor_version = strndup(cur, - eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor->processor_version, + cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "External Clock: ")) != NULL) { cur += 16; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((processor->processor_external_clock - = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor->processor_external_clock, + cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Max Speed: ")) != NULL) { cur += 11; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((processor->processor_max_speed - = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor->processor_max_speed, + cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Status: ")) != NULL) { cur += 8; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((processor->processor_status = strndup(cur, - eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor->processor_status, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Serial Number: ")) != NULL) { cur += 15; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((processor->processor_serial_number - = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor->processor_serial_number, + cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Part Number: ")) != NULL) { cur += 13; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((processor->processor_part_number - = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor->processor_part_number, + cur, eol - cur) < 0) + return -1; } base += strlen("Processor Information"); } return 0; - -no_memory: - return -1; } static int @@ -778,9 +735,8 @@ virSysinfoParseMemory(const char *base, virSysinfoDefPtr ret) base = tmp_base; eol = NULL; - if (VIR_EXPAND_N(ret->memory, ret->nmemory, 1) < 0) { - goto no_memory; - } + if (VIR_EXPAND_N(ret->memory, ret->nmemory, 1) < 0) + return -1; memory = &ret->memory[ret->nmemory - 1]; if ((cur = strstr(base, "Size: ")) != NULL) { @@ -790,87 +746,74 @@ virSysinfoParseMemory(const char *base, virSysinfoDefPtr ret) goto next; virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((memory->memory_size = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(memory->memory_size, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Form Factor: ")) != NULL) { cur += 13; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((memory->memory_form_factor = strndup(cur, - eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(memory->memory_form_factor, + cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Locator: ")) != NULL) { cur += 9; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((memory->memory_locator = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(memory->memory_locator,cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Bank Locator: ")) != NULL) { cur += 14; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((memory->memory_bank_locator = strndup(cur, - eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(memory->memory_bank_locator, + cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Type: ")) != NULL) { cur += 6; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((memory->memory_type = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(memory->memory_type, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Type Detail: ")) != NULL) { cur += 13; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((memory->memory_type_detail = strndup(cur, - eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(memory->memory_type_detail, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Speed: ")) != NULL) { cur += 7; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((memory->memory_speed = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(memory->memory_speed, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Manufacturer: ")) != NULL) { cur += 14; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((memory->memory_manufacturer = strndup(cur, - eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(memory->memory_manufacturer, cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Serial Number: ")) != NULL) { cur += 15; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((memory->memory_serial_number = strndup(cur, - eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(memory->memory_serial_number, + cur, eol - cur) < 0) + return -1; } if ((cur = strstr(base, "Part Number: ")) != NULL) { cur += 13; eol = strchr(cur, '\n'); virSkipSpacesBackwards(cur, &eol); - if ((eol) && - ((memory->memory_part_number = strndup(cur, - eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(memory->memory_part_number, cur, eol - cur) < 0) + return -1; } next: @@ -878,9 +821,6 @@ virSysinfoParseMemory(const char *base, virSysinfoDefPtr ret) } return 0; - -no_memory: - return -1; } virSysinfoDefPtr diff --git a/src/util/virtypedparam.c b/src/util/virtypedparam.c index a9f8a33..4eb5cd6 100644 --- a/src/util/virtypedparam.c +++ b/src/util/virtypedparam.c @@ -150,12 +150,8 @@ virTypedParameterAssign(virTypedParameterPtr param, const char *name, break; case VIR_TYPED_PARAM_STRING: param->value.s = va_arg(ap, char *); - if (!param->value.s) - param->value.s = strdup(""); - if (!param->value.s) { - virReportOOMError(); + if (!param->value.s && VIR_STRDUP(param->value.s, "") < 0) goto cleanup; - } break; default: virReportError(VIR_ERR_INTERNAL_ERROR, @@ -248,10 +244,8 @@ virTypedParameterAssignFromStr(virTypedParameterPtr param, const char *name, } break; case VIR_TYPED_PARAM_STRING: - if (!(param->value.s = strdup(val))) { - virReportOOMError(); + if (VIR_STRDUP(param->value.s, val) < 0) goto cleanup; - } break; default: virReportError(VIR_ERR_INTERNAL_ERROR, @@ -913,10 +907,8 @@ virTypedParamsAddString(virTypedParameterPtr *params, } *maxparams = max; - if (value && !(str = strdup(value))) { - virReportOOMError(); + if (value && VIR_STRDUP(str, value) < 0) goto error; - } if (virTypedParameterAssign(*params + n, name, VIR_TYPED_PARAM_STRING, str) < 0) { diff --git a/src/util/viruri.c b/src/util/viruri.c index 2a75425..745b978 100644 --- a/src/util/viruri.c +++ b/src/util/viruri.c @@ -37,13 +37,13 @@ virURIParamAppend(virURIPtr uri, char *pname = NULL; char *pvalue = NULL; - if (!(pname = strdup(name))) - goto no_memory; - if (!(pvalue = strdup(value))) - goto no_memory; + if (VIR_STRDUP(pname, name) < 0 || VIR_STRDUP(pvalue, value) < 0) + goto error; - if (VIR_RESIZE_N(uri->params, uri->paramsAlloc, uri->paramsCount, 1) < 0) - goto no_memory; + if (VIR_RESIZE_N(uri->params, uri->paramsAlloc, uri->paramsCount, 1) < 0) { + virReportOOMError(); + goto error; + } uri->params[uri->paramsCount].name = pname; uri->params[uri->paramsCount].value = pvalue; @@ -52,10 +52,9 @@ virURIParamAppend(virURIPtr uri, return 0; -no_memory: +error: VIR_FREE(pname); VIR_FREE(pvalue); - virReportOOMError(); return -1; } @@ -167,34 +166,29 @@ virURIParse(const char *uri) return NULL; } - if (VIR_ALLOC(ret) < 0) - goto no_memory; + if (VIR_ALLOC(ret) < 0) { + virReportOOMError(); + goto error; + } - if (xmluri->scheme && - !(ret->scheme = strdup(xmluri->scheme))) - goto no_memory; - if (xmluri->server && - !(ret->server = strdup(xmluri->server))) - goto no_memory; + if (xmluri->scheme && VIR_STRDUP(ret->scheme, xmluri->scheme) < 0) + goto error; + if (xmluri->server && VIR_STRDUP(ret->server, xmluri->server) < 0) + goto error; ret->port = xmluri->port; - if (xmluri->path && - !(ret->path = strdup(xmluri->path))) - goto no_memory; + if (xmluri->path && VIR_STRDUP(ret->path, xmluri->path) < 0) + goto error; #ifdef HAVE_XMLURI_QUERY_RAW - if (xmluri->query_raw && - !(ret->query = strdup(xmluri->query_raw))) - goto no_memory; + if (xmluri->query_raw && VIR_STRDUP(ret->query, xmluri->query_raw) < 0) + goto error; #else - if (xmluri->query && - !(ret->query = strdup(xmluri->query))) - goto no_memory; + if (xmluri->query && VIR_STRDUP(ret->query, xmluri->query) < 0) + goto error; #endif - if (xmluri->fragment && - !(ret->fragment = strdup(xmluri->fragment))) - goto no_memory; - if (xmluri->user && - !(ret->user = strdup(xmluri->user))) - goto no_memory; + if (xmluri->fragment && VIR_STRDUP(ret->fragment, xmluri->fragment) < 0) + goto error; + if (xmluri->user && VIR_STRDUP(ret->user, xmluri->user) < 0) + goto error; /* First check: does it even make sense to jump inside */ if (ret->server != NULL && @@ -220,8 +214,6 @@ virURIParse(const char *uri) return ret; -no_memory: - virReportOOMError(); error: xmlFreeURI(xmluri); virURIFree(ret); diff --git a/src/util/virutil.c b/src/util/virutil.c index 982d4a3..d3d77b2 100644 --- a/src/util/virutil.c +++ b/src/util/virutil.c @@ -547,11 +547,8 @@ virFileResolveLinkHelper(const char *linkpath, if (lstat(linkpath, &st) < 0) return -1; - if (!S_ISLNK(st.st_mode)) { - if (!(*resultpath = strdup(linkpath))) - return -1; - return 0; - } + if (!S_ISLNK(st.st_mode)) + return VIR_STRDUP(*resultpath, linkpath); } *resultpath = canonicalize_file_name(linkpath); @@ -623,9 +620,11 @@ char *virFindFileInPath(const char *file) * copy of that path, after validating that it is executable */ if (IS_ABSOLUTE_FILE_NAME(file)) { - if (virFileIsExecutable(file)) - return strdup(file); - else + if (virFileIsExecutable(file)) { + char *ret; + ignore_value(VIR_STRDUP(ret, file)); + return ret; + } else return NULL; } @@ -641,7 +640,7 @@ char *virFindFileInPath(const char *file) /* copy PATH env so we can tweak it */ path = getenv("PATH"); - if (path == NULL || (path = strdup(path)) == NULL) + if (!path|| VIR_STRDUP(path, path) < 0) return NULL; /* for each path segment, append the file to search for and test for @@ -1296,7 +1295,7 @@ virFileMakePathWithMode(const char *path, int ret = -1; char *tmp; - if ((tmp = strdup(path)) == NULL) + if (VIR_STRDUP(tmp, path) < 0) goto cleanup; ret = virFileMakePathHelper(tmp, mode); @@ -1503,8 +1502,7 @@ int virFileAbsPath(const char *path, char **abspath) char *buf; if (path[0] == '/') { - if (!(*abspath = strdup(path))) - return -1; + return VIR_STRDUP(*abspath, path); } else { buf = getcwd(NULL, 0); if (buf == NULL) @@ -1528,11 +1526,8 @@ virFileSanitizePath(const char *path) char *cleanpath; int idx = 0; - cleanpath = strdup(path); - if (!cleanpath) { - virReportOOMError(); + if (VIR_STRDUP(cleanpath, path) < 0) return NULL; - } /* Need to sanitize: * // -> // @@ -1963,8 +1958,8 @@ char *virGetHostname(virConnectPtr conn ATTRIBUTE_UNUSED) * string as-is; it's up to callers to check whether "localhost" * is allowed. */ - result = strdup(hostname); - goto check_and_return; + ignore_value(VIR_STRDUP(result, hostname)); + goto cleanup; } /* otherwise, it's a shortened, non-localhost, hostname. Attempt to @@ -1978,8 +1973,8 @@ char *virGetHostname(virConnectPtr conn ATTRIBUTE_UNUSED) if (r != 0) { VIR_WARN("getaddrinfo failed for '%s': %s", hostname, gai_strerror(r)); - result = strdup(hostname); - goto check_and_return; + ignore_value(VIR_STRDUP(result, hostname)); + goto cleanup; } /* Tell static analyzers about getaddrinfo semantics. */ @@ -1991,14 +1986,14 @@ char *virGetHostname(virConnectPtr conn ATTRIBUTE_UNUSED) * localhost. Ignore the canonicalized name and just return the * original hostname */ - result = strdup(hostname); + ignore_value(VIR_STRDUP(result, hostname)); else /* Caller frees this string. */ - result = strdup(info->ai_canonname); + ignore_value(VIR_STRDUP(result, info->ai_canonname)); freeaddrinfo(info); -check_and_return: +cleanup: if (result == NULL) virReportOOMError(); return result; @@ -2052,15 +2047,9 @@ static char *virGetUserEnt(uid_t uid, return NULL; } - if (field == VIR_USER_ENT_DIRECTORY) - ret = strdup(pw->pw_dir); - else - ret = strdup(pw->pw_name); - + ignore_value(VIR_STRDUP(ret, field == VIR_USER_ENT_DIRECTORY ? + pw->pw_dir : pw->pw_name)); VIR_FREE(strbuf); - if (!ret) - virReportOOMError(); - return ret; } @@ -2105,12 +2094,8 @@ static char *virGetGroupEnt(gid_t gid) return NULL; } - ret = strdup(gr->gr_name); - + ignore_value(VIR_STRDUP(ret, gr->gr_name)); VIR_FREE(strbuf); - if (!ret) - virReportOOMError(); - return ret; } @@ -2444,12 +2429,8 @@ virGetWin32SpecialFolder(int csidl, char **path) *path = NULL; if (SHGetSpecialFolderLocation(NULL, csidl, &pidl) == S_OK) { - if (SHGetPathFromIDList(pidl, buf)) { - if (!(*path = strdup(buf))) { - virReportOOMError(); - ret = -1; - } - } + if (SHGetPathFromIDList(pidl, buf) && VIR_STRDUP(*path, buf) < 0) + ret = -1; CoTaskMemFree(pidl); } return ret; @@ -2479,12 +2460,7 @@ virGetWin32DirectoryRoot(char **path) strcpy(windowsdir, "C:\\"); } - if (!(*path = strdup(windowsdir))) { - virReportOOMError(); - ret = -1; - } - - return ret; + return VIR_STRDUP(*path, windowsdir); } @@ -2517,12 +2493,8 @@ virGetUserDirectory(void) /* USERPROFILE is probably the closest equivalent to $HOME? */ dir = getenv("USERPROFILE"); - if (dir) { - if (!(ret = strdup(dir))) { - virReportOOMError(); - return NULL; - } - } + if (dir && VIR_STRDUP(ret, dir) < 0) + return NULL; if (!ret && virGetWin32SpecialFolder(CSIDL_PROFILE, &ret) < 0) @@ -2810,7 +2782,8 @@ char *virFileFindMountPoint(const char *type) while (getmntent_r(f, &mb, mntbuf, sizeof(mntbuf))) { if (STREQ(mb.mnt_type, type)) { - ret = strdup(mb.mnt_dir); + if (VIR_STRDUP(ret, mb.mnt_dir) < 0) + errno = ENOMEM; goto cleanup; } } @@ -3121,10 +3094,8 @@ virReadFCHost(const char *sysfs_prefix, else p = buf; - if (!(*result = strndup(p, sizeof(buf)))) { - virReportOOMError(); + if (VIR_STRNDUP(*result, p, sizeof(buf)) < 0) goto cleanup; - } ret = 0; cleanup: @@ -3348,7 +3319,7 @@ virGetFCHostNameByWWN(const char *sysfs_prefix, continue; } - ret = strdup(entry->d_name); + ignore_value(VIR_STRDUP(ret, entry->d_name)); break; } @@ -3433,7 +3404,7 @@ virFindFCHostCapableVport(const char *sysfs_prefix) if ((strlen(max_vports) >= strlen(vports)) || ((strlen(max_vports) == strlen(vports)) && strcmp(max_vports, vports) > 0)) { - ret = strdup(entry->d_name); + ignore_value(VIR_STRDUP(ret, entry->d_name)); goto cleanup; } diff --git a/src/util/virxml.c b/src/util/virxml.c index 26120b6..f8c595e 100644 --- a/src/util/virxml.c +++ b/src/util/virxml.c @@ -87,11 +87,8 @@ virXPathString(const char *xpath, xmlXPathFreeObject(obj); return NULL; } - ret = strdup((char *) obj->stringval); + ignore_value(VIR_STRDUP(ret, (char *) obj->stringval)); xmlXPathFreeObject(obj); - if (ret == NULL) { - virReportOOMError(); - } return ret; } -- 1.8.1.5

On 05/03/2013 04:53 PM, Michal Privoznik wrote:
--- src/util/virauth.c | 17 +-- src/util/virauthconfig.c | 8 +- src/util/virbitmap.c | 9 +- src/util/vircgroup.c | 36 ++--- src/util/vircommand.c | 33 ++--- src/util/virconf.c | 34 ++--- src/util/virdnsmasq.c | 22 +-- src/util/virebtables.c | 34 ++--- src/util/virebtables.h | 2 +- src/util/virerror.c | 19 +-- src/util/virhash.c | 5 +- src/util/viridentity.c | 15 +- src/util/virinitctl.c | 4 +- src/util/viriptables.c | 4 +- src/util/virjson.c | 18 ++- src/util/virkeyfile.c | 13 +- src/util/virlockspace.c | 25 ++-- src/util/virlog.c | 25 ++-- src/util/virnetdevmacvlan.c | 16 +-- src/util/virnetdevtap.c | 11 +- src/util/virnetdevvportprofile.c | 4 +- src/util/virobject.c | 16 ++- src/util/virpci.c | 14 +- src/util/virsexpr.c | 37 ++--- src/util/virsocketaddr.c | 9 +- src/util/virstoragefile.c | 18 +-- src/util/virstring.c | 17 +-- src/util/virsysinfo.c | 290 ++++++++++++++++----------------------- src/util/virtypedparam.c | 14 +- src/util/viruri.c | 58 ++++---- src/util/virutil.c | 91 +++++------- src/util/virxml.c | 5 +- 32 files changed, 356 insertions(+), 567 deletions(-)
diff --git a/src/util/virbitmap.c b/src/util/virbitmap.c index c81555a..cf6a099 100644 --- a/src/util/virbitmap.c +++ b/src/util/virbitmap.c @@ -37,6 +37,8 @@ #include "count-one-bits.h" #include "virstring.h"
+#define VIR_FROM_THIS VIR_FROM_NONE + struct _virBitmap { size_t max_bit; size_t map_len; @@ -226,8 +228,11 @@ char *virBitmapFormat(virBitmapPtr bitmap) return NULL;
cur = virBitmapNextSetBit(bitmap, -1); - if (cur < 0) - return strdup(""); + if (cur < 0) { + char *ret; + ignore_value(VIR_STRDUP(ret, ""));
VIR_STRDUP_QUIET (and drop the #define), otherwise the function will report an error on OOM in VIR_STRDUP and it won't report it on OOM in the virBuffer code. (unless you plan to convert those as well)
+ return ret; + }
start = prev = cur; while (prev >= 0) { diff --git a/src/util/vircgroup.c b/src/util/vircgroup.c index 473d2fc..b3845ea 100644 --- a/src/util/vircgroup.c +++ b/src/util/vircgroup.c @@ -116,19 +116,14 @@ static int virCgroupCopyMounts(virCgroupPtr group, if (!parent->controllers[i].mountPoint) continue;
- group->controllers[i].mountPoint = - strdup(parent->controllers[i].mountPoint); - - if (!group->controllers[i].mountPoint) + if (VIR_STRDUP(group->controllers[i].mountPoint, + parent->controllers[i].mountPoint) < 0)
VIR_STRDUP_QUIET
return -ENOMEM;
- if (parent->controllers[i].linkPoint) { - group->controllers[i].linkPoint = - strdup(parent->controllers[i].linkPoint); - - if (!group->controllers[i].linkPoint) - return -ENOMEM; - } + if (parent->controllers[i].linkPoint && + VIR_STRDUP(group->controllers[i].linkPoint, + parent->controllers[i].linkPoint) < 0)
here too
+ return -ENOMEM; } return 0; } @@ -177,8 +172,8 @@ static int virCgroupDetectMounts(virCgroupPtr group) struct stat sb; char *tmp2;
- if (!(group->controllers[i].mountPoint = strdup(entry.mnt_dir))) - goto no_memory; + if (VIR_STRDUP(group->controllers[i].mountPoint, entry.mnt_dir) < 0) + goto error;
VIR_STRDUP_QUIET and goto no_memory; no_memory doesn't report an error here, it sets errno.
tmp2 = strrchr(entry.mnt_dir, '/'); if (!tmp2) { @@ -239,7 +234,7 @@ static int virCgroupCopyPlacement(virCgroupPtr group, continue;
if (path[0] == '/') { - if (!(group->controllers[i].placement = strdup(path))) + if (VIR_STRDUP(group->controllers[i].placement, path) < 0) return -ENOMEM; } else { /* @@ -821,7 +816,7 @@ static int virCgroupNew(const char *path, }
if (path[0] == '/' || !parent) { - if (!((*group)->path = strdup(path))) { + if (VIR_STRDUP((*group)->path, path) < 0) { rc = -ENOMEM; goto err; }
VIR_STRDUP_QUIET in both hunks above.
@@ -1027,7 +1022,7 @@ static int virCgroupAddTaskStrController(virCgroupPtr group, int rc = 0; char *endp;
- if (!(str = strdup(pidstr))) + if (VIR_STRDUP(str, pidstr) < 0) return -1;
VIR_STRDUP_QUIET return -ENOMEM;
cur = str; @@ -1253,7 +1248,7 @@ int virCgroupNewPartition(const char *path,
if (STRNEQ(newpath, "/")) { char *tmp; - if (!(parentPath = strdup(newpath))) { + if (VIR_STRDUP(parentPath, newpath) < 0) {
VIR_STRDUP_QUIET
rc = -ENOMEM; goto cleanup; }
@@ -2543,12 +2538,11 @@ static char *virCgroupIdentifyRoot(virCgroupPtr group) }
All this:
tmp[0] = '\0'; - ret = strdup(group->controllers[i].mountPoint); - tmp[0] = '/'; - if (!ret) { - virReportOOMError(); + if (VIR_STRDUP(ret, group->controllers[i].mountPoint) < 0) { + tmp[0] = '/'; return NULL; } + tmp[0] = '/';
can be replaced by: ignore_value(VIR_STRNDUP(ret, group->controllers[i].mountPoint, tmp - group->controllers[i].mountPoint)); althought that would probably work better as a separate patch.
return ret; }
diff --git a/src/util/vircommand.c b/src/util/vircommand.c index f6f27d9..eecda58 100644 --- a/src/util/vircommand.c +++ b/src/util/vircommand.c @@ -946,9 +946,8 @@ virCommandSetPidFile(virCommandPtr cmd, const char *pidfile) return;
VIR_FREE(cmd->pidfile); - if (!(cmd->pidfile = strdup(pidfile))) { + if (VIR_STRDUP(cmd->pidfile, pidfile) < 0) cmd->has_error = ENOMEM; - } }
@@ -1049,7 +1048,7 @@ virCommandSetSELinuxLabel(virCommandPtr cmd,
#if defined(WITH_SECDRIVER_SELINUX) VIR_FREE(cmd->seLinuxLabel); - if (label && !(cmd->seLinuxLabel = strdup(label))) + if (label && VIR_STRDUP(cmd->seLinuxLabel, label) < 0) cmd->has_error = ENOMEM; #endif return; @@ -1074,7 +1073,7 @@ virCommandSetAppArmorProfile(virCommandPtr cmd,
#if defined(WITH_SECDRIVER_APPARMOR) VIR_FREE(cmd->appArmorProfile); - if (profile && !(cmd->appArmorProfile = strdup(profile))) + if (profile && VIR_STRDUP(cmd->appArmorProfile, profile) < 0) cmd->has_error = ENOMEM; #endif return; @@ -1205,7 +1204,7 @@ virCommandAddEnvString(virCommandPtr cmd, const char *str) if (!cmd || cmd->has_error) return;
- if (!(env = strdup(str))) { + if (VIR_STRDUP(env, str) < 0) { cmd->has_error = ENOMEM; return; } @@ -1309,7 +1308,7 @@ virCommandAddArg(virCommandPtr cmd, const char *val) if (!cmd || cmd->has_error) return;
- if (!(arg = strdup(val))) { + if (VIR_STRDUP(arg, val) < 0) { cmd->has_error = ENOMEM; return; } @@ -1350,11 +1349,11 @@ virCommandAddArgBuffer(virCommandPtr cmd, virBufferPtr buf) }
cmd->args[cmd->nargs] = virBufferContentAndReset(buf); - if (!cmd->args[cmd->nargs]) - cmd->args[cmd->nargs] = strdup(""); if (!cmd->args[cmd->nargs]) { - cmd->has_error = ENOMEM; - return; + if (VIR_STRDUP(cmd->args[cmd->nargs], "") < 0) { + cmd->has_error = ENOMEM; + return; + } } cmd->nargs++; } @@ -1440,8 +1439,9 @@ virCommandAddArgSet(virCommandPtr cmd, const char *const*vals)
narg = 0; while (vals[narg] != NULL) { - char *arg = strdup(vals[narg++]); - if (!arg) { + char *arg; + + if (VIR_STRDUP(arg, vals[narg++]) < 0) { cmd->has_error = ENOMEM; return; } @@ -1481,8 +1481,7 @@ virCommandAddArgList(virCommandPtr cmd, ...) char *arg = va_arg(list, char *); if (!arg) break; - arg = strdup(arg); - if (!arg) { + if (VIR_STRDUP(arg, arg) < 0) { cmd->has_error = ENOMEM; va_end(list); return; @@ -1511,8 +1510,7 @@ virCommandSetWorkingDirectory(virCommandPtr cmd, const char *pwd) cmd->has_error = -1; VIR_DEBUG("cannot set directory twice"); } else { - cmd->pwd = strdup(pwd); - if (!cmd->pwd) + if (VIR_STRDUP(cmd->pwd, pwd) < 0) cmd->has_error = ENOMEM; } } @@ -1539,8 +1537,7 @@ virCommandSetInputBuffer(virCommandPtr cmd, const char *inbuf) return; }
- cmd->inbuf = strdup(inbuf); - if (!cmd->inbuf) + if (VIR_STRDUP(cmd->inbuf, inbuf) < 0) cmd->has_error = ENOMEM; }
VIR_STRDUP_QUIET for all of the above. OOM Error for these is reported in virCommandRun.
diff --git a/src/util/virhash.c b/src/util/virhash.c index 2fe8751..bb708fc 100644 --- a/src/util/virhash.c +++ b/src/util/virhash.c @@ -85,7 +86,9 @@ static bool virHashStrEqual(const void *namea, const void *nameb)
static void *virHashStrCopy(const void *name) { - return strdup(name); + char *ret; + ignore_value(VIR_STRDUP(ret, name)); + return ret; }
VIR_STRDUP_QUIET, as the error gets reported in virHashAddOrUpdateEntry.
static void virHashStrFree(void *name)
diff --git a/src/util/viriptables.c b/src/util/viriptables.c index 06a1356..88c3bcd 100644 --- a/src/util/viriptables.c +++ b/src/util/viriptables.c @@ -118,10 +118,10 @@ iptRulesNew(const char *table, if (VIR_ALLOC(rules) < 0) return NULL;
- if (!(rules->table = strdup(table))) + if (VIR_STRDUP(rules->table, table) < 0) goto error;
- if (!(rules->chain = strdup(chain))) + if (VIR_STRDUP(rules->chain, chain) < 0) goto error;
return rules;
VIR_STRDUP_QUIET, unless you plan to adjust the comment for iptablesContextNew and remove the extra OOMError from bridge_driver.c
diff --git a/src/util/virjson.c b/src/util/virjson.c index 92138d3..66376c1 100644 --- a/src/util/virjson.c +++ b/src/util/virjson.c @@ -107,7 +107,7 @@ virJSONValuePtr virJSONValueNewString(const char *data) return NULL;
val->type = VIR_JSON_TYPE_STRING; - if (!(val->data.string = strdup(data))) { + if (VIR_STRDUP(val->data.string, data) < 0) { VIR_FREE(val); return NULL; } @@ -126,7 +126,7 @@ virJSONValuePtr virJSONValueNewStringLen(const char *data, size_t length) return NULL;
val->type = VIR_JSON_TYPE_STRING; - if (!(val->data.string = strndup(data, length))) { + if (VIR_STRNDUP(val->data.string, data, length) < 0) { VIR_FREE(val); return NULL; } @@ -142,7 +142,7 @@ static virJSONValuePtr virJSONValueNewNumber(const char *data) return NULL;
val->type = VIR_JSON_TYPE_NUMBER; - if (!(val->data.number = strdup(data))) { + if (VIR_STRDUP(val->data.number, data) < 0) { VIR_FREE(val); return NULL; } @@ -269,7 +269,7 @@ int virJSONValueObjectAppend(virJSONValuePtr object, const char *key, virJSONVal if (virJSONValueObjectHasKey(object, key)) return -1;
- if (!(newkey = strdup(key))) + if (VIR_STRDUP(newkey, key) < 0) return -1;
if (VIR_REALLOC_N(object->data.object.pairs, @@ -751,10 +751,10 @@ static int virJSONParserHandleNumber(void *ctx, yajl_size_t l) { virJSONParserPtr parser = ctx; - char *str = strndup(s, l); + char *str; virJSONValuePtr value;
- if (!str) + if (VIR_STRNDUP(str, s, l) < 0) return -1; value = virJSONValueNewNumber(str); VIR_FREE(str); @@ -808,8 +808,7 @@ static int virJSONParserHandleMapKey(void *ctx, state = &parser->state[parser->nstate-1]; if (state->key) return 0; - state->key = strndup((const char *)stringVal, stringLen); - if (!state->key) + if (VIR_STRNDUP(state->key, (const char *)stringVal, stringLen) < 0) return 0; return 1; }
All these are expected by the callers to be quiet.
@@ -1094,8 +1093,7 @@ char *virJSONValueToString(virJSONValuePtr object, goto cleanup; }
- if (!(ret = strdup((const char *)str))) - virReportOOMError(); + ignore_value(VIR_STRDUP(ret, (const char *)str));
cleanup: yajl_gen_free(g);
diff --git a/src/util/virlog.c b/src/util/virlog.c index eee9ddc..2ed0b10 100644 --- a/src/util/virlog.c +++ b/src/util/virlog.c @@ -557,8 +557,7 @@ virLogDefineFilter(const char *match, } }
- mdup = strdup(match); - if (mdup == NULL) { + if (VIR_STRDUP(mdup, match) < 0) { i = -1; goto cleanup; } @@ -664,13 +663,9 @@ virLogDefineOutput(virLogOutputFunc f, if (f == NULL) return -1;
- if (dest == VIR_LOG_TO_SYSLOG || dest == VIR_LOG_TO_FILE) { - if (name == NULL) - return -1; - ndup = strdup(name); - if (ndup == NULL) - return -1; - } + if ((dest == VIR_LOG_TO_SYSLOG || dest == VIR_LOG_TO_FILE) && + (!name || VIR_STRDUP(ndup, name) < 0)) + return -1;
virLogLock(); if (VIR_REALLOC_N(virLogOutputs, virLogNbOutputs + 1)) { @@ -1047,8 +1042,7 @@ virLogAddOutputToSyslog(virLogPriority priority, * ident needs to be kept around on Solaris */ VIR_FREE(current_ident); - current_ident = strdup(ident); - if (current_ident == NULL) + if (VIR_STRDUP(current_ident, ident) < 0) return -1;
openlog(current_ident, 0, 0); @@ -1329,8 +1323,7 @@ virLogParseOutputs(const char *outputs) if (str == cur) goto cleanup; #if HAVE_SYSLOG_H - name = strndup(str, cur - str); - if (name == NULL) + if (VIR_STRNDUP(name, str, cur - str) < 0) goto cleanup; if (virLogAddOutputToSyslog(prio, name) == 0) count++; @@ -1346,8 +1339,7 @@ virLogParseOutputs(const char *outputs) cur++; if (str == cur) goto cleanup; - name = strndup(str, cur - str); - if (name == NULL) + if (VIR_STRNDUP(name, str, cur - str) < 0) goto cleanup; if (virFileAbsPath(name, &abspath) < 0) { VIR_FREE(name); @@ -1424,8 +1416,7 @@ virLogParseFilters(const char *filters) cur++; if (str == cur) goto cleanup; - name = strndup(str, cur - str); - if (name == NULL) + if (VIR_STRNDUP(name, str, cur - str) < 0) goto cleanup; if (virLogDefineFilter(name, prio, flags) >= 0) count++;
All the calls in this file should be quiet too.
diff --git a/src/util/virnetdevmacvlan.c b/src/util/virnetdevmacvlan.c index 0c4fcbd..93bf798 100644 --- a/src/util/virnetdevmacvlan.c +++ b/src/util/virnetdevmacvlan.c @@ -764,14 +765,14 @@ virNetDevMacVLanVPortProfileRegisterCallback(const char *ifname, if (virtPortProfile && virNetlinkEventServiceIsRunning(NETLINK_ROUTE)) { if (VIR_ALLOC(calld) < 0) goto memory_error; - if ((calld->cr_ifname = strdup(ifname)) == NULL) - goto memory_error; + if (VIR_STRDUP(calld->cr_ifname, ifname) < 0) + goto error; if (VIR_ALLOC(calld->virtPortProfile) < 0) goto memory_error; memcpy(calld->virtPortProfile, virtPortProfile, sizeof(*virtPortProfile)); virMacAddrSet(&calld->macaddress, macaddress); - if ((calld->linkdev = strdup(linkdev)) == NULL) - goto memory_error; + if (VIR_STRDUP(calld->linkdev, linkdev) < 0) + goto error;
double space ^^
memcpy(calld->vmuuid, vmuuid, sizeof(calld->vmuuid));
calld->vmOp = vmOp;
diff --git a/src/util/virobject.c b/src/util/virobject.c index 93e37e4..72a5248 100644 --- a/src/util/virobject.c +++ b/src/util/virobject.c @@ -28,6 +28,7 @@ #include "viratomic.h" #include "virerror.h" #include "virlog.h" +#include "virstring.h"
#define VIR_FROM_THIS VIR_FROM_NONE
@@ -37,7 +38,7 @@ struct _virClass { virClassPtr parent;
unsigned int magic; - const char *name; + char *name; size_t objectSize;
virObjectDisposeCallback dispose; @@ -131,21 +132,22 @@ virClassPtr virClassNew(virClassPtr parent, return NULL; }
- if (VIR_ALLOC(klass) < 0) - goto no_memory; + if (VIR_ALLOC(klass) < 0) { + virReportOOMError(); + goto error; + }
klass->parent = parent; - if (!(klass->name = strdup(name))) - goto no_memory; + if (VIR_STRDUP(klass->name, name) < 0) + goto error;
Wouldn't it be nicer to do it with a temporary variable, so we can keep the const?
klass->magic = virAtomicIntInc(&magicCounter); klass->objectSize = objectSize; klass->dispose = dispose;
return klass;
-no_memory: +error: VIR_FREE(klass); - virReportOOMError(); return NULL; }
diff --git a/src/util/virsexpr.c b/src/util/virsexpr.c index 23b6781..b17c0d4 100644 --- a/src/util/virsexpr.c +++ b/src/util/virsexpr.c @@ -119,16 +119,10 @@ sexpr_string(const char *str, ssize_t len) if (ret == NULL) return ret; ret->kind = SEXPR_VALUE; - if (len > 0) { - ret->u.value = strndup(str, len); - } else { - ret->u.value = strdup(str); - }
- if (ret->u.value == NULL) { + if ((len > 0 && VIR_STRNDUP(ret->u.value, str, len) < 0) || + (len <= 0 && VIR_STRDUP(ret->u.value, str) < 0)) VIR_FREE(ret); - return NULL; - }
return ret; }
This function was quiet before, but it doesn't seem to be used anywhere.
@@ -527,13 +511,10 @@ int sexpr_node_copy(const struct sexpr *sexpr, const char *node, char **dst) { const char *val = sexpr_node(sexpr, node);
- if (val && *val) { - *dst = strdup(val); - if (!(*dst)) - return -1; - } else { - *dst = NULL; - } + if (val && *val) + return VIR_STRDUP(*dst, val); + + *dst = NULL; return 0; }
Callers report the OOM error for this function, but it seems it would be better to leave it here and clean them up.
diff --git a/src/util/virsysinfo.c b/src/util/virsysinfo.c index 2efe634..7fd2537 100644 --- a/src/util/virsysinfo.c +++ b/src/util/virsysinfo.c @@ -144,32 +144,26 @@ virSysinfoParseSystem(const char *base, virSysinfoDefPtr ret) cur = strchr(cur, ':') + 1; eol = strchr(cur, '\n'); virSkipSpaces(&cur); - if (eol && - ((ret->system_family = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_family, cur, eol - cur) < 0) + return -1;
if ((cur = strstr(base, "model")) != NULL) { cur = strchr(cur, ':') + 1; eol = strchr(cur, '\n'); virSkipSpaces(&cur); - if (eol && ((ret->system_serial = strndup(cur, eol - cur)) - == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_serial, cur, eol - cur) < 0) + return -1; }
if ((cur = strstr(base, "machine")) != NULL) { cur = strchr(cur, ':') + 1; eol = strchr(cur, '\n'); virSkipSpaces(&cur); - if (eol && ((ret->system_version = strndup(cur, eol - cur)) - == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_version, cur, eol - cur) < 0) + return -1; }
return 0; - -no_memory: - return -1; }
static int @@ -185,34 +179,31 @@ virSysinfoParseProcessor(const char *base, virSysinfoDefPtr ret) cur = strchr(base, ':') + 1;
if (VIR_EXPAND_N(ret->processor, ret->nprocessor, 1) < 0) { - goto no_memory; + return -1; } processor = &ret->processor[ret->nprocessor - 1];
virSkipSpaces(&cur); - if (eol && - ((processor->processor_socket_destination = strndup - (cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor->processor_socket_destination, + cur, eol - cur) < 0) + return -1;
if ((cur = strstr(base, "cpu")) != NULL) { cur = strchr(cur, ':') + 1; eol = strchr(cur, '\n'); virSkipSpaces(&cur); - if (eol && - ((processor->processor_type = strndup(cur, eol - cur)) - == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor->processor_type, + cur, eol - cur) < 0) + return -1; }
if ((cur = strstr(base, "revision")) != NULL) { cur = strchr(cur, ':') + 1; eol = strchr(cur, '\n'); virSkipSpaces(&cur); - if (eol && - ((processor->processor_version = strndup(cur, eol - cur)) - == NULL)) - goto no_memory; + if (eol && VIR_STRNUDP(processor->processor_version,
typo ^^
+ cur, eol - cur) < 0) + return -1; }
base = cur;
You have replaced all occurences of goto no_memory with return -1, but you left the no_memory label here.
@@ -270,32 +261,26 @@ virSysinfoParseSystem(const char *base, virSysinfoDefPtr ret) cur = strchr(cur, ':') + 1; eol = strchr(cur, '\n'); virSkipSpaces(&cur); - if (eol && - ((ret->system_family = strndup(cur, eol - cur)) == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_family, cur, eol - cur) < 0) + return -1;
if ((cur = strstr(base, "model")) != NULL) { cur = strchr(cur, ':') + 1; eol = strchr(cur, '\n'); virSkipSpaces(&cur); - if (eol && ((ret->system_serial = strndup(cur, eol - cur)) - == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_serial, cur, eol - cur) < 0) + return -1; }
if ((cur = strstr(base, "machine")) != NULL) { cur = strchr(cur, ':') + 1; eol = strchr(cur, '\n'); virSkipSpaces(&cur); - if (eol && ((ret->system_version = strndup(cur, eol - cur)) - == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(ret->system_version, cur, eol - cur) < 0) + return -1; }
return 0; - -no_memory: - return -1; }
static int @@ -313,10 +298,8 @@ virSysinfoParseProcessor(const char *base, virSysinfoDefPtr ret) eol = strchr(base, '\n'); cur = strchr(base, ':') + 1; virSkipSpaces(&cur); - if (eol && - ((processor_type = strndup(cur, eol - cur)) - == NULL)) - goto no_memory; + if (eol && VIR_STRNDUP(processor_type, cur, eol - cur) < 0) + goto error; base = cur;
while ((tmp_base = strstr(base, "processor")) != NULL) { @@ -325,19 +308,20 @@ virSysinfoParseProcessor(const char *base, virSysinfoDefPtr ret) cur = strchr(base, ':') + 1;
if (VIR_EXPAND_N(ret->processor, ret->nprocessor, 1) < 0) { - goto no_memory; + virReportOOMError();
Unrelated, but missing.
+ goto error; } processor = &ret->processor[ret->nprocessor - 1];
virSkipSpaces(&cur); if (eol && - ((processor->processor_socket_destination = strndup - (cur, eol - cur)) == NULL)) - goto no_memory; + VIR_STRNDUP(processor->processor_socket_destination, + cur, eol - cur) < 0) + goto error;
if (processor_type && - !(processor->processor_type = strdup(processor_type))) - goto no_memory; + VIR_STRDUP(processor->processor_type, processor_type) < 0) + goto error;
base = cur; }
virSysinfoRead for non-windows x86 seems to be the only one reporting OOM errors, which should be deleted after you switch VIR_ALLOC to report errors too and the other architectures might be missing some OOM errors, like arm in the hunk above.
diff --git a/src/util/virutil.c b/src/util/virutil.c index 982d4a3..d3d77b2 100644 --- a/src/util/virutil.c +++ b/src/util/virutil.c @@ -547,11 +547,8 @@ virFileResolveLinkHelper(const char *linkpath, if (lstat(linkpath, &st) < 0) return -1;
- if (!S_ISLNK(st.st_mode)) { - if (!(*resultpath = strdup(linkpath))) - return -1; - return 0; - } + if (!S_ISLNK(st.st_mode)) + return VIR_STRDUP(*resultpath, linkpath); }
*resultpath = canonicalize_file_name(linkpath);
This function should return -1 and set errno on error, not report an error.
@@ -623,9 +620,11 @@ char *virFindFileInPath(const char *file) * copy of that path, after validating that it is executable */ if (IS_ABSOLUTE_FILE_NAME(file)) { - if (virFileIsExecutable(file)) - return strdup(file); - else + if (virFileIsExecutable(file)) { + char *ret; + ignore_value(VIR_STRDUP(ret, file));
VIR_STRDUP_QUIET
+ return ret; + } else return NULL; }
@@ -641,7 +640,7 @@ char *virFindFileInPath(const char *file) /* copy PATH env so we can tweak it */ path = getenv("PATH");
- if (path == NULL || (path = strdup(path)) == NULL) + if (!path|| VIR_STRDUP(path, path) < 0)
missing space; VIR_STRDUP_QUIET
return NULL;
/* for each path segment, append the file to search for and test for @@ -1296,7 +1295,7 @@ virFileMakePathWithMode(const char *path, int ret = -1; char *tmp;
- if ((tmp = strdup(path)) == NULL) + if (VIR_STRDUP(tmp, path) < 0) goto cleanup;
This one should be quiet and set errno.
ret = virFileMakePathHelper(tmp, mode); @@ -1503,8 +1502,7 @@ int virFileAbsPath(const char *path, char **abspath) char *buf;
if (path[0] == '/') { - if (!(*abspath = strdup(path))) - return -1; + return VIR_STRDUP(*abspath, path);
VIR_STRDUP_QUIET
} else { buf = getcwd(NULL, 0); if (buf == NULL)
@@ -2810,7 +2782,8 @@ char *virFileFindMountPoint(const char *type)
while (getmntent_r(f, &mb, mntbuf, sizeof(mntbuf))) { if (STREQ(mb.mnt_type, type)) { - ret = strdup(mb.mnt_dir); + if (VIR_STRDUP(ret, mb.mnt_dir) < 0)
VIR_STRDUP_QUIET
+ errno = ENOMEM; goto cleanup; } }
ACK (but I only compiled it on amd64 linux) Jan

On 05/03/2013 04:53 PM, Michal Privoznik wrote:
32 files changed, 356 insertions(+), 567 deletions(-)
These functions returned 0 on success before and will need to be adjusted since VIR_STRDUP returns 1 on a successful copy now.
diff --git a/src/util/viridentity.c b/src/util/viridentity.c index c9efd3f..e2dc048 100644 --- a/src/util/viridentity.c +++ b/src/util/viridentity.c
@@ -246,12 +246,7 @@ int virIdentitySetAttr(virIdentityPtr ident, goto cleanup; }
- if (!(ident->attrs[attr] = strdup(value))) { - virReportOOMError(); - goto cleanup; - } - - ret = 0; + ret = VIR_STRDUP(ident->attrs[attr], value);
cleanup: return ret;
diff --git a/src/util/virnetdevtap.c b/src/util/virnetdevtap.c index 75599db..08a5599 100644 --- a/src/util/virnetdevtap.c +++ b/src/util/virnetdevtap.c @@ -64,12 +64,7 @@ virNetDevTapGetName(int tapfd ATTRIBUTE_UNUSED, char **ifname ATTRIBUTE_UNUSED) return -1; }
- *ifname = strdup(ifr.ifr_name); - if (*ifname == NULL) { - virReportOOMError(); - return -1; - } - return 0; + return VIR_STRDUP(*ifname, ifr.ifr_name); #else return -1; #endif
diff --git a/src/util/virpci.c b/src/util/virpci.c index 5865613..1f19d3f 100644 --- a/src/util/virpci.c +++ b/src/util/virpci.c @@ -2268,11 +2264,7 @@ virPCIGetNetName(char *device_link_sysfs_path, char **netname) continue;
/* Assume a single directory entry */ - *netname = strdup(entry->d_name); - if (!*netname) - virReportOOMError(); - else - ret = 0; + ret = VIR_STRDUP(*netname, entry->d_name); break; }
diff --git a/src/util/virsexpr.c b/src/util/virsexpr.c index 23b6781..b17c0d4 100644 --- a/src/util/virsexpr.c +++ b/src/util/virsexpr.c @@ -527,13 +511,10 @@ int sexpr_node_copy(const struct sexpr *sexpr, const char *node, char **dst) { const char *val = sexpr_node(sexpr, node);
- if (val && *val) { - *dst = strdup(val); - if (!(*dst)) - return -1; - } else { - *dst = NULL; - } + if (val && *val) + return VIR_STRDUP(*dst, val); + + *dst = NULL; return 0; }
diff --git a/src/util/virutil.c b/src/util/virutil.c index 982d4a3..d3d77b2 100644 --- a/src/util/virutil.c +++ b/src/util/virutil.c @@ -547,11 +547,8 @@ virFileResolveLinkHelper(const char *linkpath, if (lstat(linkpath, &st) < 0) return -1;
- if (!S_ISLNK(st.st_mode)) { - if (!(*resultpath = strdup(linkpath))) - return -1; - return 0; - } + if (!S_ISLNK(st.st_mode)) + return VIR_STRDUP(*resultpath, linkpath); }
*resultpath = canonicalize_file_name(linkpath);
@@ -1503,8 +1502,7 @@ int virFileAbsPath(const char *path, char **abspath) char *buf;
if (path[0] == '/') { - if (!(*abspath = strdup(path))) - return -1; + return VIR_STRDUP(*abspath, path); } else { buf = getcwd(NULL, 0); if (buf == NULL)
@@ -2479,12 +2460,7 @@ virGetWin32DirectoryRoot(char **path) strcpy(windowsdir, "C:\\"); }
- if (!(*path = strdup(windowsdir))) { - virReportOOMError(); - ret = -1; - } - - return ret; + return VIR_STRDUP(*path, windowsdir); }

On 20.05.2013 13:07, Ján Tomko wrote:
On 05/03/2013 04:53 PM, Michal Privoznik wrote:
32 files changed, 356 insertions(+), 567 deletions(-)
These functions returned 0 on success before and will need to be adjusted since VIR_STRDUP returns 1 on a successful copy now.
I don't think so, as long as all callers check for error correctly: if (func() < 0) goto error; Which all callers of these functions do. Michal

On 05/20/2013 01:40 PM, Michal Privoznik wrote:
On 20.05.2013 13:07, Ján Tomko wrote:
On 05/03/2013 04:53 PM, Michal Privoznik wrote:
32 files changed, 356 insertions(+), 567 deletions(-)
These functions returned 0 on success before and will need to be adjusted since VIR_STRDUP returns 1 on a successful copy now.
I don't think so, as long as all callers check for error correctly:
if (func() < 0) goto error;
Which all callers of these functions do.
I've only found one that doesn't: src/storage/parthelper.c: if (virFileResolveLink(path, &canonical_path) != 0) { But you still should update the comments stating that they return 0 on success. Jan

On 20.05.2013 13:54, Ján Tomko wrote:
On 05/20/2013 01:40 PM, Michal Privoznik wrote:
On 20.05.2013 13:07, Ján Tomko wrote:
On 05/03/2013 04:53 PM, Michal Privoznik wrote:
32 files changed, 356 insertions(+), 567 deletions(-)
These functions returned 0 on success before and will need to be adjusted since VIR_STRDUP returns 1 on a successful copy now.
I don't think so, as long as all callers check for error correctly:
if (func() < 0) goto error;
Which all callers of these functions do.
I've only found one that doesn't: src/storage/parthelper.c: if (virFileResolveLink(path, &canonical_path) != 0) {
But you still should update the comments stating that they return 0 on success.
Huh, "Returns 0 or 1 on success" is not nice. So I'd rather change the return value.
Jan

On 05/20/2013 06:12 AM, Michal Privoznik wrote:
I've only found one that doesn't: src/storage/parthelper.c: if (virFileResolveLink(path, &canonical_path) != 0) {
But you still should update the comments stating that they return 0 on success.
Huh, "Returns 0 or 1 on success" is not nice. So I'd rather change the return value.
While the 0/1 distinction makes sense for VIR_STRDUP (as you can argue that knowing whether the caller passed NULL is sometimes useful), most other larger functions that happen to end on a VIR_STRDUP aren't really using the 0/1 as a differentiation on whether the user passed in NULL, but are always dup'ing a non-NULL string. But returning 1 when it conveys no real information seems awkward. Therefore, I think I'd rather see you rewrite code to continue to return explicit 0 on functions that were previously returning 0, instead of optimizing by passing the VIR_STRDUP return value straight through. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/vbox/vbox_XPCOMCGlue.c | 6 +- src/vbox/vbox_tmpl.c | 278 +++++++++++++++++++-------------------------- 2 files changed, 117 insertions(+), 167 deletions(-) diff --git a/src/vbox/vbox_XPCOMCGlue.c b/src/vbox/vbox_XPCOMCGlue.c index e0b606f..016d925 100644 --- a/src/vbox/vbox_XPCOMCGlue.c +++ b/src/vbox/vbox_XPCOMCGlue.c @@ -105,12 +105,8 @@ tryLoadOne(const char *dir, bool setAppHome, bool ignoreMissing, return -1; } } else { - name = strdup(DYNLIB_NAME); - - if (name == NULL) { - virReportOOMError(); + if (VIR_STRDUP(name, DYNLIB_NAME) < 0) return -1; - } } /* diff --git a/src/vbox/vbox_tmpl.c b/src/vbox/vbox_tmpl.c index 43ddac8..4ac7b91 100644 --- a/src/vbox/vbox_tmpl.c +++ b/src/vbox/vbox_tmpl.c @@ -1840,11 +1840,9 @@ static char *vboxDomainGetOSType(virDomainPtr dom ATTRIBUTE_UNUSED) { * is supposed to pass the ABI name and not the domain * operating system driver as I had imagined ;) */ - char *osType = strdup("hvm"); - - if (osType == NULL) - virReportOOMError(); + char *osType; + ignore_value(VIR_STRDUP(osType, "hvm")); return osType; } @@ -2290,7 +2288,8 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) { def->virtType = VIR_DOMAIN_VIRT_VBOX; def->id = dom->id; memcpy(def->uuid, dom->uuid, VIR_UUID_BUFLEN); - def->name = strdup(dom->name); + if (VIR_STRDUP(def->name, dom->name) < 0) + goto cleanup; machine->vtbl->GetMemorySize(machine, &memorySize); def->mem.cur_balloon = memorySize * 1024; @@ -2325,7 +2324,8 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) { /* Skip cpumasklen, cpumask, onReboot, onPoweroff, onCrash */ - def->os.type = strdup("hvm"); + if (VIR_STRDUP(def->os.type, "hvm") < 0) + goto cleanup; def->os.arch = virArchFromHost(); @@ -2460,10 +2460,8 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) { if (STREQ(valueTypeUtf8, "sdl")) { sdlPresent = 1; - if (valueDisplayUtf8) - sdlDisplay = strdup(valueDisplayUtf8); - if (sdlDisplay == NULL) { - virReportOOMError(); + if (valueDisplayUtf8 && + VIR_STRDUP(sdlDisplay, valueDisplayUtf8) < 0) { /* just don't go to cleanup yet as it is ok to have * sdlDisplay as NULL and we check it below if it * exist and then only use it there @@ -2474,10 +2472,8 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) { if (STREQ(valueTypeUtf8, "gui")) { guiPresent = 1; - if (valueDisplayUtf8) - guiDisplay = strdup(valueDisplayUtf8); - if (guiDisplay == NULL) { - virReportOOMError(); + if (valueDisplayUtf8 && + VIR_STRDUP(guiDisplay, valueDisplayUtf8) < 0) { /* just don't go to cleanup yet as it is ok to have * guiDisplay as NULL and we check it below if it * exist and then only use it there @@ -2512,14 +2508,11 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) { if (VIR_ALLOC(def->graphics[def->ngraphics]) >= 0) { def->graphics[def->ngraphics]->type = VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP; tmp = getenv("DISPLAY"); - if (tmp != NULL) { - def->graphics[def->ngraphics]->data.desktop.display = strdup(tmp); - if (def->graphics[def->ngraphics]->data.desktop.display == NULL) { - virReportOOMError(); - /* just don't go to cleanup yet as it is ok to have - * display as NULL - */ - } + if (tmp && + VIR_STRDUP(def->graphics[def->ngraphics]->data.desktop.display, tmp) < 0) { + /* just don't go to cleanup yet as it is ok to have + * display as NULL + */ } totalPresent++; def->ngraphics++; @@ -2649,9 +2642,9 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) { if (hddType == HardDiskType_Immutable) def->disks[hddNum]->readonly = true; - def->disks[hddNum]->src = strdup(hddlocation); - def->disks[hddNum]->dst = strdup("hda"); - hddNum++; + if (VIR_STRDUP(def->disks[hddNum]->src, hddlocation) == 0 && + VIR_STRDUP(def->disks[hddNum]->dst, "hda") == 0) + hddNum++; VBOX_UTF8_FREE(hddlocation); VBOX_UTF16_FREE(hddlocationUtf16); @@ -2670,9 +2663,9 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) { if (hddType == HardDiskType_Immutable) def->disks[hddNum]->readonly = true; - def->disks[hddNum]->src = strdup(hddlocation); - def->disks[hddNum]->dst = strdup("hdb"); - hddNum++; + if (VIR_STRDUP(def->disks[hddNum]->src, hddlocation) == 0 && + VIR_STRDUP(def->disks[hddNum]->dst, "hdb") == 0) + hddNum++; VBOX_UTF8_FREE(hddlocation); VBOX_UTF16_FREE(hddlocationUtf16); @@ -2691,9 +2684,9 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) { if (hddType == HardDiskType_Immutable) def->disks[hddNum]->readonly = true; - def->disks[hddNum]->src = strdup(hddlocation); - def->disks[hddNum]->dst = strdup("hdd"); - hddNum++; + if (VIR_STRDUP_QUIET(def->disks[hddNum]->src, hddlocation) == 0 && + VIR_STRDUP_QUIET(def->disks[hddNum]->dst, "hdd") == 0) + hddNum++; VBOX_UTF8_FREE(hddlocation); VBOX_UTF16_FREE(hddlocationUtf16); @@ -2780,7 +2773,7 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) { medium->vtbl->GetLocation(medium, &mediumLocUtf16); VBOX_UTF16_TO_UTF8(mediumLocUtf16, &mediumLocUtf8); VBOX_UTF16_FREE(mediumLocUtf16); - def->disks[diskCount]->src = strdup(mediumLocUtf8); + ignore_value(VIR_STRDUP(def->disks[diskCount]->src, mediumLocUtf8)); VBOX_UTF8_FREE(mediumLocUtf8); if (!(def->disks[diskCount]->src)) { @@ -2884,25 +2877,23 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) { sharedFolder->vtbl->GetHostPath(sharedFolder, &hostPathUtf16); VBOX_UTF16_TO_UTF8(hostPathUtf16, &hostPath); - def->fss[i]->src = strdup(hostPath); - VBOX_UTF8_FREE(hostPath); - VBOX_UTF16_FREE(hostPathUtf16); - - if (def->fss[i]->src == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->fss[i]->src, hostPath) < 0) { + VBOX_UTF8_FREE(hostPath); + VBOX_UTF16_FREE(hostPathUtf16); goto sharedFoldersCleanup; } + VBOX_UTF8_FREE(hostPath); + VBOX_UTF16_FREE(hostPathUtf16); sharedFolder->vtbl->GetName(sharedFolder, &nameUtf16); VBOX_UTF16_TO_UTF8(nameUtf16, &name); - def->fss[i]->dst = strdup(name); - VBOX_UTF8_FREE(name); - VBOX_UTF16_FREE(nameUtf16); - - if (def->fss[i]->dst == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->fss[i]->dst, name) < 0) { + VBOX_UTF8_FREE(name); + VBOX_UTF16_FREE(nameUtf16); goto sharedFoldersCleanup; } + VBOX_UTF8_FREE(name); + VBOX_UTF16_FREE(nameUtf16); sharedFolder->vtbl->GetWritable(sharedFolder, &writable); def->fss[i]->readonly = !writable; @@ -2976,7 +2967,7 @@ sharedFoldersCleanup: #endif /* VBOX_API_VERSION >= 4001 */ VBOX_UTF16_TO_UTF8(hostIntUtf16, &hostInt); - def->nets[netAdpIncCnt]->data.bridge.brname = strdup(hostInt); + ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->data.bridge.brname, hostInt)); VBOX_UTF8_FREE(hostInt); VBOX_UTF16_FREE(hostIntUtf16); @@ -2990,7 +2981,7 @@ sharedFoldersCleanup: adapter->vtbl->GetInternalNetwork(adapter, &intNetUtf16); VBOX_UTF16_TO_UTF8(intNetUtf16, &intNet); - def->nets[netAdpIncCnt]->data.internal.name = strdup(intNet); + ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->data.internal.name, intNet)); VBOX_UTF8_FREE(intNet); VBOX_UTF16_FREE(intNetUtf16); @@ -3008,7 +2999,7 @@ sharedFoldersCleanup: #endif /* VBOX_API_VERSION >= 4001 */ VBOX_UTF16_TO_UTF8(hostIntUtf16, &hostInt); - def->nets[netAdpIncCnt]->data.network.name = strdup(hostInt); + ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->data.network.name, hostInt)); VBOX_UTF8_FREE(hostInt); VBOX_UTF16_FREE(hostIntUtf16); @@ -3022,18 +3013,18 @@ sharedFoldersCleanup: adapter->vtbl->GetAdapterType(adapter, &adapterType); if (adapterType == NetworkAdapterType_Am79C970A) { - def->nets[netAdpIncCnt]->model = strdup("Am79C970A"); + ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "Am79C970A")); } else if (adapterType == NetworkAdapterType_Am79C973) { - def->nets[netAdpIncCnt]->model = strdup("Am79C973"); + ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "Am79C973")); } else if (adapterType == NetworkAdapterType_I82540EM) { - def->nets[netAdpIncCnt]->model = strdup("82540EM"); + ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "82540EM")); } else if (adapterType == NetworkAdapterType_I82545EM) { - def->nets[netAdpIncCnt]->model = strdup("82545EM"); + ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "82545EM")); } else if (adapterType == NetworkAdapterType_I82543GC) { - def->nets[netAdpIncCnt]->model = strdup("82543GC"); + ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "82543GC")); #if VBOX_API_VERSION >= 3001 } else if (adapterType == NetworkAdapterType_Virtio) { - def->nets[netAdpIncCnt]->model = strdup("virtio"); + ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "virtio")); #endif /* VBOX_API_VERSION >= 3001 */ } @@ -3120,8 +3111,9 @@ sharedFoldersCleanup: def->disks[def->ndisks - 1]->bus = VIR_DOMAIN_DISK_BUS_IDE; def->disks[def->ndisks - 1]->type = VIR_DOMAIN_DISK_TYPE_FILE; def->disks[def->ndisks - 1]->readonly = true; - def->disks[def->ndisks - 1]->src = strdup(location); - def->disks[def->ndisks - 1]->dst = strdup("hdc"); + if (VIR_STRDUP(def->disks[def->ndisks - 1]->src, location) < 0 || + VIR_STRDUP(def->disks[def->ndisks - 1]->dst, "hdc") < 0) + def->ndisks--; } else { def->ndisks--; virReportOOMError(); @@ -3167,8 +3159,9 @@ sharedFoldersCleanup: def->disks[def->ndisks - 1]->bus = VIR_DOMAIN_DISK_BUS_FDC; def->disks[def->ndisks - 1]->type = VIR_DOMAIN_DISK_TYPE_FILE; def->disks[def->ndisks - 1]->readonly = false; - def->disks[def->ndisks - 1]->src = strdup(location); - def->disks[def->ndisks - 1]->dst = strdup("fda"); + if (VIR_STRDUP(def->disks[def->ndisks - 1]->src, location) < 0 || + VIR_STRDUP(def->disks[def->ndisks - 1]->dst, "fda") < 0) + def->ndisks--; } else { def->ndisks--; virReportOOMError(); @@ -3261,7 +3254,7 @@ sharedFoldersCleanup: if (pathUtf16) { VBOX_UTF16_TO_UTF8(pathUtf16, &path); - def->serials[serialPortIncCount]->source.data.file.path = strdup(path); + ignore_value(VIR_STRDUP(def->serials[serialPortIncCount]->source.data.file.path, path)); } serialPortIncCount++; @@ -3331,7 +3324,7 @@ sharedFoldersCleanup: parallelPort->vtbl->GetPath(parallelPort, &pathUtf16); VBOX_UTF16_TO_UTF8(pathUtf16, &path); - def->parallels[parallelPortIncCount]->source.data.file.path = strdup(path); + ignore_value(VIR_STRDUP(def->parallels[parallelPortIncCount]->source.data.file.path, path)); parallelPortIncCount++; @@ -3478,16 +3471,16 @@ static int vboxConnectListDefinedDomains(virConnectPtr conn, char ** const names (state > MachineState_LastOnline)) { machine->vtbl->GetName(machine, &machineNameUtf16); VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineName); - names[j] = strdup(machineName); - VBOX_UTF16_FREE(machineNameUtf16); - VBOX_UTF8_FREE(machineName); - if (!names[j]) { - virReportOOMError(); + if (VIR_STRDUP(names[j], machineName) < 0) { + VBOX_UTF16_FREE(machineNameUtf16); + VBOX_UTF8_FREE(machineName); for (; j >= 0 ; j--) VIR_FREE(names[j]); ret = -1; goto cleanup; } + VBOX_UTF16_FREE(machineNameUtf16); + VBOX_UTF8_FREE(machineName); j++; ret++; } @@ -3584,29 +3577,23 @@ vboxStartMachine(virDomainPtr dom, int i, IMachine *machine, if (STREQ(valueTypeUtf8, "sdl")) { sdlPresent = 1; - if (valueDisplayUtf8) { - sdlDisplay = strdup(valueDisplayUtf8); - if (sdlDisplay == NULL) { - virReportOOMError(); - /* just don't go to cleanup yet as it is ok to have - * sdlDisplay as NULL and we check it below if it - * exist and then only use it there - */ - } + if (valueDisplayUtf8 && + VIR_STRDUP(sdlDisplay, valueDisplayUtf8) < 0) { + /* just don't go to cleanup yet as it is ok to have + * sdlDisplay as NULL and we check it below if it + * exist and then only use it there + */ } } if (STREQ(valueTypeUtf8, "gui")) { guiPresent = 1; - if (valueDisplayUtf8) { - guiDisplay = strdup(valueDisplayUtf8); - if (guiDisplay == NULL) { - virReportOOMError(); - /* just don't go to cleanup yet as it is ok to have - * guiDisplay as NULL and we check it below if it - * exist and then only use it there - */ - } + if (valueDisplayUtf8 && + VIR_STRDUP(guiDisplay, valueDisplayUtf8) < 0) { + /* just don't go to cleanup yet as it is ok to have + * guiDisplay as NULL and we check it below if it + * exist and then only use it there + */ } } } @@ -3982,7 +3969,8 @@ vboxAttachDrives(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine) PRInt32 device = 0; PRUnichar *hddcnameUtf16 = NULL; - char *hddcname = strdup("IDE"); + char *hddcname; + ignore_value(VIR_STRDUP(hddcname, "IDE")); VBOX_UTF8_TO_UTF16(hddcname, &hddcnameUtf16); VIR_FREE(hddcname); @@ -4801,30 +4789,24 @@ vboxAttachDisplay(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine) if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP) && (guiPresent == 0)) { guiPresent = 1; - if (def->graphics[i]->data.desktop.display) { - guiDisplay = strdup(def->graphics[i]->data.desktop.display); - if (guiDisplay == NULL) { - virReportOOMError(); - /* just don't go to cleanup yet as it is ok to have - * guiDisplay as NULL and we check it below if it - * exist and then only use it there - */ - } + if (def->graphics[i]->data.desktop.display && + VIR_STRDUP(guiDisplay, def->graphics[i]->data.desktop.display) < 0) { + /* just don't go to cleanup yet as it is ok to have + * guiDisplay as NULL and we check it below if it + * exist and then only use it there + */ } } if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL) && (sdlPresent == 0)) { sdlPresent = 1; - if (def->graphics[i]->data.sdl.display) { - sdlDisplay = strdup(def->graphics[i]->data.sdl.display); - if (sdlDisplay == NULL) { - virReportOOMError(); - /* just don't go to cleanup yet as it is ok to have - * sdlDisplay as NULL and we check it below if it - * exist and then only use it there - */ - } + if (def->graphics[i]->data.sdl.display && + VIR_STRDUP(sdlDisplay, def->graphics[i]->data.sdl.display) < 0) { + /* just don't go to cleanup yet as it is ok to have + * sdlDisplay as NULL and we check it below if it + * exist and then only use it there + */ } } } @@ -5226,7 +5208,8 @@ vboxDomainUndefineFlags(virDomainPtr dom, unsigned int flags) { PRUnichar *hddcnameUtf16 = NULL; - char *hddcname = strdup("IDE"); + char *hddcname; + ignore_value(VIR_STRDUP(hddcname, "IDE")); VBOX_UTF8_TO_UTF16(hddcname, &hddcnameUtf16); VIR_FREE(hddcname); @@ -5385,12 +5368,8 @@ static int vboxDomainAttachDeviceImpl(virDomainPtr dom, return ret; } - def->os.type = strdup("hvm"); - - if (def->os.type == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->os.type, "hvm") < 0) goto cleanup; - } dev = virDomainDeviceDefParse(xml, def, data->caps, data->xmlopt, VIR_DOMAIN_XML_INACTIVE); @@ -5620,12 +5599,8 @@ static int vboxDomainDetachDevice(virDomainPtr dom, const char *xml) { return ret; } - def->os.type = strdup("hvm"); - - if (def->os.type == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->os.type, "hvm") < 0) goto cleanup; - } dev = virDomainDeviceDefParse(xml, def, data->caps, data->xmlopt, VIR_DOMAIN_XML_INACTIVE); @@ -6050,9 +6025,10 @@ vboxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot, if (!(snap = vboxDomainSnapshotGet(data, dom, machine, snapshot->name))) goto cleanup; - if (VIR_ALLOC(def) < 0 - || !(def->name = strdup(snapshot->name))) + if (VIR_ALLOC(def) < 0) goto no_memory; + if (VIR_STRDUP(def->name, snapshot->name) < 0) + goto cleanup; rc = snap->vtbl->GetDescription(snap, &str16); if (NS_FAILED(rc)) { @@ -6064,10 +6040,11 @@ vboxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot, if (str16) { VBOX_UTF16_TO_UTF8(str16, &str8); VBOX_UTF16_FREE(str16); - def->description = strdup(str8); + if (VIR_STRDUP(def->description, str8) < 0) { + VBOX_UTF8_FREE(str8); + goto cleanup; + } VBOX_UTF8_FREE(str8); - if (!def->description) - goto no_memory; } rc = snap->vtbl->GetTimeStamp(snap, ×tamp); @@ -6097,10 +6074,11 @@ vboxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot, } VBOX_UTF16_TO_UTF8(str16, &str8); VBOX_UTF16_FREE(str16); - def->parent = strdup(str8); - VBOX_UTF8_FREE(str8); - if (!def->parent) + if (VIR_STRDUP(def->parent, str8) < 0) { + VBOX_UTF8_FREE(str8); goto no_memory; + } + VBOX_UTF8_FREE(str8); } rc = snap->vtbl->GetOnline(snap, &online); @@ -6247,12 +6225,12 @@ vboxDomainSnapshotListNames(virDomainPtr dom, } VBOX_UTF16_TO_UTF8(nameUtf16, &name); VBOX_UTF16_FREE(nameUtf16); - names[i] = strdup(name); - VBOX_UTF8_FREE(name); - if (!names[i]) { + if (VIR_STRDUP(names[i], name) < 0) { virReportOOMError(); + VBOX_UTF8_FREE(name); goto cleanup; } + VBOX_UTF8_FREE(name); } if (count <= nameslen) @@ -7529,12 +7507,8 @@ static int vboxConnectListNetworks(virConnectPtr conn, char **const names, int n VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8); VIR_DEBUG("nnames[%d]: %s", ret, nameUtf8); - names[ret] = strdup(nameUtf8); - if (names[ret] == NULL) { - virReportOOMError(); - } else { + if (VIR_STRDUP(names[ret], nameUtf8) == 0) ret++; - } VBOX_UTF8_FREE(nameUtf8); VBOX_UTF16_FREE(nameUtf16); @@ -7611,12 +7585,8 @@ static int vboxConnectListDefinedNetworks(virConnectPtr conn, char **const names VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8); VIR_DEBUG("nnames[%d]: %s", ret, nameUtf8); - names[ret] = strdup(nameUtf8); - if (names[ret] == NULL) { - virReportOOMError(); - } else { + if (VIR_STRDUP(names[ret], nameUtf8) == 0) ret++; - } VBOX_UTF8_FREE(nameUtf8); VBOX_UTF16_FREE(nameUtf16); @@ -8117,8 +8087,7 @@ static char *vboxNetworkGetXMLDesc(virNetworkPtr network, networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType); if (interfaceType == HostNetworkInterfaceType_HostOnly) { - def->name = strdup(network->name); - if (def->name != NULL) { + if (VIR_STRDUP(def->name, network->name) == 0) { PRUnichar *networkNameUtf16 = NULL; IDHCPServer *dhcpServer = NULL; vboxIID vboxnet0IID = VBOX_IID_INITIALIZER; @@ -8175,11 +8144,9 @@ static char *vboxNetworkGetXMLDesc(virNetworkPtr network, ipdef->nhosts = 1; if (VIR_ALLOC_N(ipdef->hosts, ipdef->nhosts) >=0) { - ipdef->hosts[0].name = strdup(network->name); - if (ipdef->hosts[0].name == NULL) { + if (VIR_STRDUP(ipdef->hosts[0].name, network->name) < 0) { VIR_FREE(ipdef->hosts); ipdef->nhosts = 0; - virReportOOMError(); } else { PRUnichar *macAddressUtf16 = NULL; PRUnichar *ipAddressUtf16 = NULL; @@ -8296,14 +8263,9 @@ static int vboxConnectListStoragePools(virConnectPtr conn ATTRIBUTE_UNUSED, char **const names, int nnames) { int numActive = 0; - if (nnames == 1) { - names[numActive] = strdup("default-pool"); - if (names[numActive] == NULL) { - virReportOOMError(); - } else { - numActive++; - } - } + if (nnames == 1 && + VIR_STRDUP(names[numActive], "default-pool") == 0) + numActive++; return numActive; } @@ -8385,12 +8347,8 @@ static int vboxStoragePoolListVolumes(virStoragePoolPtr pool, char **const names if (nameUtf8) { VIR_DEBUG("nnames[%d]: %s", numActive, nameUtf8); - names[numActive] = strdup(nameUtf8); - if (names[numActive] == NULL) { - virReportOOMError(); - } else { + if (VIR_STRDUP(names[numActive], nameUtf8) == 0) numActive++; - } VBOX_UTF8_FREE(nameUtf8); } @@ -9007,12 +8965,10 @@ static char *vboxStorageVolGetXMLDesc(virStorageVolPtr vol, unsigned int flags) else defOk = 0; - def.name = strdup(vol->name); - if (!(def.name && defOk)) + if (VIR_STRDUP(def.name, vol->name) < 0) defOk = 0; - def.key = strdup(vol->key); - if (!(def.key && defOk)) + if (VIR_STRDUP(def.key, vol->key) < 0) defOk = 0; rc = hardDisk->vtbl->GetFormat(hardDisk, &hddFormatUtf16); @@ -9088,9 +9044,7 @@ static char *vboxStorageVolGetPath(virStorageVolPtr vol) { VBOX_UTF16_TO_UTF8(hddLocationUtf16, &hddLocationUtf8); if (hddLocationUtf8) { - ret = strdup(hddLocationUtf8); - if (!ret) - virReportOOMError(); + ignore_value(VIR_STRDUP(ret, hddLocationUtf8)); VIR_DEBUG("Storage Volume Name: %s", vol->name); VIR_DEBUG("Storage Volume Path: %s", hddLocationUtf8); @@ -9211,14 +9165,14 @@ vboxDomainScreenshot(virDomainPtr dom, goto endjob; } + if (VIR_STRDUP(ret, "image/png") < 0) + goto endjob; + if (virFDStreamOpenFile(st, tmp, 0, 0, O_RDONLY) < 0) { virReportError(VIR_ERR_OPERATION_FAILED, "%s", _("unable to open stream")); - goto endjob; + VIR_FREE(ret); } - - ret = strdup("image/png"); - endjob: VIR_FREE(screenData); VBOX_RELEASE(display); -- 1.8.1.5

On 05/03/2013 04:53 PM, Michal Privoznik wrote:
--- src/vbox/vbox_XPCOMCGlue.c | 6 +- src/vbox/vbox_tmpl.c | 278 +++++++++++++++++++-------------------------- 2 files changed, 117 insertions(+), 167 deletions(-)
diff --git a/src/vbox/vbox_tmpl.c b/src/vbox/vbox_tmpl.c index 43ddac8..4ac7b91 100644 --- a/src/vbox/vbox_tmpl.c +++ b/src/vbox/vbox_tmpl.c @@ -2290,7 +2288,8 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) { def->virtType = VIR_DOMAIN_VIRT_VBOX; def->id = dom->id; memcpy(def->uuid, dom->uuid, VIR_UUID_BUFLEN); - def->name = strdup(dom->name); + if (VIR_STRDUP(def->name, dom->name) < 0) + goto cleanup;
Bailing out after one unsuccessful strdup? Other parts of this function don't share this defeatist attitude.
machine->vtbl->GetMemorySize(machine, &memorySize); def->mem.cur_balloon = memorySize * 1024;
@@ -2460,10 +2460,8 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) {
if (STREQ(valueTypeUtf8, "sdl")) { sdlPresent = 1; - if (valueDisplayUtf8) - sdlDisplay = strdup(valueDisplayUtf8); - if (sdlDisplay == NULL) { - virReportOOMError(); + if (valueDisplayUtf8 && + VIR_STRDUP(sdlDisplay, valueDisplayUtf8) < 0) { /* just don't go to cleanup yet as it is ok to have * sdlDisplay as NULL and we check it below if it * exist and then only use it there @@ -2474,10 +2472,8 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) {
if (STREQ(valueTypeUtf8, "gui")) { guiPresent = 1; - if (valueDisplayUtf8) - guiDisplay = strdup(valueDisplayUtf8); - if (guiDisplay == NULL) { - virReportOOMError(); + if (valueDisplayUtf8 && + VIR_STRDUP(guiDisplay, valueDisplayUtf8) < 0) { /* just don't go to cleanup yet as it is ok to have * guiDisplay as NULL and we check it below if it * exist and then only use it there @@ -2512,14 +2508,11 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) { if (VIR_ALLOC(def->graphics[def->ngraphics]) >= 0) { def->graphics[def->ngraphics]->type = VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP; tmp = getenv("DISPLAY"); - if (tmp != NULL) { - def->graphics[def->ngraphics]->data.desktop.display = strdup(tmp); - if (def->graphics[def->ngraphics]->data.desktop.display == NULL) { - virReportOOMError(); - /* just don't go to cleanup yet as it is ok to have - * display as NULL - */ - } + if (tmp && + VIR_STRDUP(def->graphics[def->ngraphics]->data.desktop.display, tmp) < 0) { + /* just don't go to cleanup yet as it is ok to have + * display as NULL + */ } totalPresent++; def->ngraphics++;
You have preserved the existing behavior in these three hunks...
@@ -2649,9 +2642,9 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) {
if (hddType == HardDiskType_Immutable) def->disks[hddNum]->readonly = true; - def->disks[hddNum]->src = strdup(hddlocation); - def->disks[hddNum]->dst = strdup("hda"); - hddNum++; + if (VIR_STRDUP(def->disks[hddNum]->src, hddlocation) == 0 && + VIR_STRDUP(def->disks[hddNum]->dst, "hda") == 0) + hddNum++;
VBOX_UTF8_FREE(hddlocation); VBOX_UTF16_FREE(hddlocationUtf16); @@ -2670,9 +2663,9 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) {
if (hddType == HardDiskType_Immutable) def->disks[hddNum]->readonly = true; - def->disks[hddNum]->src = strdup(hddlocation); - def->disks[hddNum]->dst = strdup("hdb"); - hddNum++; + if (VIR_STRDUP(def->disks[hddNum]->src, hddlocation) == 0 && + VIR_STRDUP(def->disks[hddNum]->dst, "hdb") == 0) + hddNum++;
VBOX_UTF8_FREE(hddlocation); VBOX_UTF16_FREE(hddlocationUtf16); @@ -2691,9 +2684,9 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) {
if (hddType == HardDiskType_Immutable) def->disks[hddNum]->readonly = true; - def->disks[hddNum]->src = strdup(hddlocation); - def->disks[hddNum]->dst = strdup("hdd"); - hddNum++; + if (VIR_STRDUP_QUIET(def->disks[hddNum]->src, hddlocation) == 0 && + VIR_STRDUP_QUIET(def->disks[hddNum]->dst, "hdd") == 0) + hddNum++;
VBOX_UTF8_FREE(hddlocation); VBOX_UTF16_FREE(hddlocationUtf16);
.. but not in these three. I think you should call ignore_value(VIR_STRDUP()) in all three. Or fix it properly.
@@ -2780,7 +2773,7 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) { medium->vtbl->GetLocation(medium, &mediumLocUtf16); VBOX_UTF16_TO_UTF8(mediumLocUtf16, &mediumLocUtf8); VBOX_UTF16_FREE(mediumLocUtf16); - def->disks[diskCount]->src = strdup(mediumLocUtf8); + ignore_value(VIR_STRDUP(def->disks[diskCount]->src, mediumLocUtf8));
VIR_STRDUP_QUIET, or remove the virReportOOMError a few lines below.
VBOX_UTF8_FREE(mediumLocUtf8);
if (!(def->disks[diskCount]->src)) {
@@ -3120,8 +3111,9 @@ sharedFoldersCleanup: def->disks[def->ndisks - 1]->bus = VIR_DOMAIN_DISK_BUS_IDE; def->disks[def->ndisks - 1]->type = VIR_DOMAIN_DISK_TYPE_FILE; def->disks[def->ndisks - 1]->readonly = true; - def->disks[def->ndisks - 1]->src = strdup(location); - def->disks[def->ndisks - 1]->dst = strdup("hdc"); + if (VIR_STRDUP(def->disks[def->ndisks - 1]->src, location) < 0 || + VIR_STRDUP(def->disks[def->ndisks - 1]->dst, "hdc") < 0) + def->ndisks--; } else { def->ndisks--; virReportOOMError(); @@ -3167,8 +3159,9 @@ sharedFoldersCleanup: def->disks[def->ndisks - 1]->bus = VIR_DOMAIN_DISK_BUS_FDC; def->disks[def->ndisks - 1]->type = VIR_DOMAIN_DISK_TYPE_FILE; def->disks[def->ndisks - 1]->readonly = false; - def->disks[def->ndisks - 1]->src = strdup(location); - def->disks[def->ndisks - 1]->dst = strdup("fda"); + if (VIR_STRDUP(def->disks[def->ndisks - 1]->src, location) < 0 || + VIR_STRDUP(def->disks[def->ndisks - 1]->dst, "fda") < 0) + def->ndisks--; } else { def->ndisks--; virReportOOMError();
ignore_value(VIR_STRDUP) in both hunks.
@@ -6247,12 +6225,12 @@ vboxDomainSnapshotListNames(virDomainPtr dom, } VBOX_UTF16_TO_UTF8(nameUtf16, &name); VBOX_UTF16_FREE(nameUtf16); - names[i] = strdup(name); - VBOX_UTF8_FREE(name); - if (!names[i]) { + if (VIR_STRDUP(names[i], name) < 0) { virReportOOMError();
redundant virReportOOMError()
+ VBOX_UTF8_FREE(name); goto cleanup; } + VBOX_UTF8_FREE(name); }
if (count <= nameslen)
@@ -8117,8 +8087,7 @@ static char *vboxNetworkGetXMLDesc(virNetworkPtr network, networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
if (interfaceType == HostNetworkInterfaceType_HostOnly) { - def->name = strdup(network->name); - if (def->name != NULL) { + if (VIR_STRDUP(def->name, network->name) == 0) { PRUnichar *networkNameUtf16 = NULL; IDHCPServer *dhcpServer = NULL; vboxIID vboxnet0IID = VBOX_IID_INITIALIZER;
You can delete the else branch with virReportOOMError() The error handling is horrible in a few places, but that's pre-existing. ACK Jan

On Fri, May 10, 2013 at 02:28:02PM +0200, Ján Tomko wrote:
On 05/03/2013 04:53 PM, Michal Privoznik wrote:
--- src/vbox/vbox_XPCOMCGlue.c | 6 +- src/vbox/vbox_tmpl.c | 278 +++++++++++++++++++-------------------------- 2 files changed, 117 insertions(+), 167 deletions(-)
diff --git a/src/vbox/vbox_tmpl.c b/src/vbox/vbox_tmpl.c index 43ddac8..4ac7b91 100644 --- a/src/vbox/vbox_tmpl.c +++ b/src/vbox/vbox_tmpl.c @@ -2290,7 +2288,8 @@ static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) { def->virtType = VIR_DOMAIN_VIRT_VBOX; def->id = dom->id; memcpy(def->uuid, dom->uuid, VIR_UUID_BUFLEN); - def->name = strdup(dom->name); + if (VIR_STRDUP(def->name, dom->name) < 0) + goto cleanup;
Bailing out after one unsuccessful strdup? Other parts of this function don't share this defeatist attitude.
The VirtualBox code is truely awful in this respect. Any improvements to reporting errors like this change does are more than welcome. Daniel -- |: http://berrange.com -o- http://www.flickr.com/photos/dberrange/ :| |: http://libvirt.org -o- http://virt-manager.org :| |: http://autobuild.org -o- http://search.cpan.org/~danberr/ :| |: http://entangle-photo.org -o- http://live.gnome.org/gtk-vnc :|

--- src/vmware/vmware_conf.c | 28 ++++++++++------------------ src/vmware/vmware_driver.c | 11 +++++------ 2 files changed, 15 insertions(+), 24 deletions(-) diff --git a/src/vmware/vmware_conf.c b/src/vmware/vmware_conf.c index 4fb61a8..4b61a9c 100644 --- a/src/vmware/vmware_conf.c +++ b/src/vmware/vmware_conf.c @@ -174,11 +174,8 @@ vmwareLoadDomains(struct vmware_driver *driver) pDomain = vm->privateData; - pDomain->vmxPath = strdup(vmxPath); - if (pDomain->vmxPath == NULL) { - virReportOOMError(); + if (VIR_STRDUP(pDomain->vmxPath, vmxPath) < 0) goto cleanup; - } vmwareDomainConfigDisplay(pDomain, vmdef); @@ -297,22 +294,21 @@ vmwareParsePath(char *path, char **directory, char **filename) return -1; } - if ((*directory = strdup(path)) == NULL) - goto no_memory; - if ((*filename = strdup(separator)) == NULL) { + if (VIR_STRDUP(*directory, path) < 0) + goto error; + if (VIR_STRDUP(*filename, separator) < 0) { VIR_FREE(*directory); - goto no_memory; + goto error; } } else { - if ((*filename = strdup(path)) == NULL) - goto no_memory; + if (VIR_STRDUP(*filename, path) < 0) + goto error; } return 0; -no_memory: - virReportOOMError(); +error: return -1; } @@ -492,12 +488,8 @@ cleanup: char * vmwareCopyVMXFileName(const char *datastorePath, void *opaque ATTRIBUTE_UNUSED) { - char *path = strdup(datastorePath); - - if (path == NULL) { - virReportOOMError(); - return NULL; - } + char *path; + ignore_value(VIR_STRDUP_QUIET(path, datastorePath)); return path; } diff --git a/src/vmware/vmware_driver.c b/src/vmware/vmware_driver.c index 1e2634e..91a271f 100644 --- a/src/vmware/vmware_driver.c +++ b/src/vmware/vmware_driver.c @@ -33,6 +33,7 @@ #include "vmx.h" #include "vmware_conf.h" #include "vmware_driver.h" +#include "virstring.h" static const char *vmw_types[] = { "player", "ws" }; @@ -352,10 +353,8 @@ vmwareDomainDefineXML(virConnectPtr conn, const char *xml) goto cleanup; pDomain = vm->privateData; - if ((pDomain->vmxPath = strdup(vmxPath)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(pDomain->vmxPath, vmxPath) < 0) goto cleanup; - } vmwareDomainConfigDisplay(pDomain, vmdef); @@ -636,7 +635,8 @@ vmwareDomainCreateXML(virConnectPtr conn, const char *xml, goto cleanup; pDomain = vm->privateData; - pDomain->vmxPath = strdup(vmxPath); + if (VIR_STRDUP(pDomain->vmxPath, vmxPath) < 0) + goto cleanup; vmwareDomainConfigDisplay(pDomain, vmdef); vmdef = NULL; @@ -800,8 +800,7 @@ vmwareDomainGetOSType(virDomainPtr dom) goto cleanup; } - if (!(ret = strdup(vm->def->os.type))) - virReportOOMError(); + ignore_value(VIR_STRDUP(ret, vm->def->os.type)); cleanup: if (vm) -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/vmware/vmware_conf.c | 28 ++++++++++------------------ src/vmware/vmware_driver.c | 11 +++++------ 2 files changed, 15 insertions(+), 24 deletions(-)
ACK. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

2013/5/3 Michal Privoznik <mprivozn@redhat.com>:
--- src/vmware/vmware_conf.c | 28 ++++++++++------------------ src/vmware/vmware_driver.c | 11 +++++------ 2 files changed, 15 insertions(+), 24 deletions(-)
diff --git a/src/vmware/vmware_conf.c b/src/vmware/vmware_conf.c index 4fb61a8..4b61a9c 100644 --- a/src/vmware/vmware_conf.c +++ b/src/vmware/vmware_conf.c @@ -492,12 +488,8 @@ cleanup: char * vmwareCopyVMXFileName(const char *datastorePath, void *opaque ATTRIBUTE_UNUSED) { - char *path = strdup(datastorePath); - - if (path == NULL) { - virReportOOMError(); - return NULL; - } + char *path;
+ ignore_value(VIR_STRDUP_QUIET(path, datastorePath)); return path; }
Why did you remove the OOM reporting here? -- Matthias Bolte http://photron.blogspot.com

On 15.05.2013 23:23, Matthias Bolte wrote:
2013/5/3 Michal Privoznik <mprivozn@redhat.com>:
--- src/vmware/vmware_conf.c | 28 ++++++++++------------------ src/vmware/vmware_driver.c | 11 +++++------ 2 files changed, 15 insertions(+), 24 deletions(-)
diff --git a/src/vmware/vmware_conf.c b/src/vmware/vmware_conf.c index 4fb61a8..4b61a9c 100644 --- a/src/vmware/vmware_conf.c +++ b/src/vmware/vmware_conf.c @@ -492,12 +488,8 @@ cleanup: char * vmwareCopyVMXFileName(const char *datastorePath, void *opaque ATTRIBUTE_UNUSED) { - char *path = strdup(datastorePath); - - if (path == NULL) { - virReportOOMError(); - return NULL; - } + char *path;
+ ignore_value(VIR_STRDUP_QUIET(path, datastorePath)); return path; }
Why did you remove the OOM reporting here?
-- Matthias Bolte http://photron.blogspot.com
Wooops, can you send a patch please? Michal

--- src/vmx/vmx.c | 36 ++++++------------------------------ 1 file changed, 6 insertions(+), 30 deletions(-) diff --git a/src/vmx/vmx.c b/src/vmx/vmx.c index 9ec0269..a75cced 100644 --- a/src/vmx/vmx.c +++ b/src/vmx/vmx.c @@ -682,14 +682,7 @@ virVMXGetConfigString(virConfPtr conf, const char *name, char **string, return -1; } - *string = strdup(value->str); - - if (*string == NULL) { - virReportOOMError(); - return -1; - } - - return 0; + return VIR_STRDUP(*string, value->str); } @@ -1526,12 +1519,8 @@ virVMXParseConfig(virVMXContext *ctx, def->onCrash = VIR_DOMAIN_LIFECYCLE_DESTROY; /* def:os */ - def->os.type = strdup("hvm"); - - if (def->os.type == NULL) { - virReportOOMError(); + if (VIR_STRDUP(def->os.type, "hvm") < 0) goto cleanup; - } /* vmx:guestOS -> def:os.arch */ if (virVMXGetConfigString(conf, "guestOS", &guestOS, true) < 0) { @@ -2579,12 +2568,8 @@ virVMXParseEthernet(virConfPtr conf, int controller, virDomainNetDefPtr *def) if (STRCASEEQ(virtualDev, "vmxnet") && features == 15) { VIR_FREE(virtualDev); - virtualDev = strdup("vmxnet2"); - - if (virtualDev == NULL) { - virReportOOMError(); + if (VIR_STRDUP(virtualDev, "vmxnet2") < 0) goto cleanup; - } } } @@ -2596,13 +2581,8 @@ virVMXParseEthernet(virConfPtr conf, int controller, virDomainNetDefPtr *def) true) < 0) goto cleanup; - if (networkName == NULL) { - networkName = strdup(""); - if (networkName == NULL) { - virReportOOMError(); - goto cleanup; - } - } + if (!networkName && VIR_STRDUP(networkName, "") < 0) + goto cleanup; } /* vmx:vnet -> def:data.ifname */ @@ -2797,12 +2777,8 @@ virVMXParseSerial(virVMXContext *ctx, virConfPtr conf, int port, goto cleanup; } - (*def)->source.data.tcp.host = strdup(parsedUri->server); - - if ((*def)->source.data.tcp.host == NULL) { - virReportOOMError(); + if (VIR_STRDUP((*def)->source.data.tcp.host, parsedUri->server) < 0) goto cleanup; - } if (virAsprintf(&(*def)->source.data.tcp.service, "%d", parsedUri->port) < 0) { -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- src/vmx/vmx.c | 36 ++++++------------------------------ 1 file changed, 6 insertions(+), 30 deletions(-)
ACK. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/xen/block_stats.c | 16 +++++----- src/xen/xen_driver.c | 9 +++--- src/xen/xen_hypervisor.c | 19 ++++-------- src/xen/xen_inotify.c | 15 +++------- src/xen/xend_internal.c | 78 ++++++++++++------------------------------------ src/xen/xm_internal.c | 9 ++---- src/xen/xs_internal.c | 44 ++++++++++----------------- 7 files changed, 59 insertions(+), 131 deletions(-) diff --git a/src/xen/block_stats.c b/src/xen/block_stats.c index ded8d7f..5952971 100644 --- a/src/xen/block_stats.c +++ b/src/xen/block_stats.c @@ -292,14 +292,14 @@ xenLinuxDomainDeviceID(int domid, const char *path) * /sys/devices/xen-backend/(vbd|tap)-{domid}-{devid}/statistics/{...} */ - if (strlen(path) >= 5 && STRPREFIX(path, "/dev/")) - mod_path = strdup(path); - else - ignore_value(virAsprintf(&mod_path, "/dev/%s", path)); - - if (!mod_path) { - virReportOOMError(); - return -1; + if (strlen(path) >= 5 && STRPREFIX(path, "/dev/")) { + if (VIR_STRDUP(mod_path, path) < 0) + return -1; + } else { + if (virAsprintf(&mod_path, "/dev/%s", path) < 0) { + virReportOOMError(); + return -1; + } } retval = -1; diff --git a/src/xen/xen_driver.c b/src/xen/xen_driver.c index 6ad050c..f992ccd 100644 --- a/src/xen/xen_driver.c +++ b/src/xen/xen_driver.c @@ -443,10 +443,8 @@ xenUnifiedConnectOpen(virConnectPtr conn, virConnectAuthPtr auth, unsigned int f } #endif - if (!(priv->saveDir = strdup(XEN_SAVE_DIR))) { - virReportOOMError(); + if (VIR_STRDUP(priv->saveDir, XEN_SAVE_DIR) < 0) goto fail; - } if (virFileMakePath(priv->saveDir) < 0) { VIR_ERROR(_("Failed to create save dir '%s': %s"), priv->saveDir, @@ -2504,8 +2502,8 @@ xenUnifiedAddDomainInfo(xenUnifiedDomainInfoListPtr list, if (VIR_ALLOC(info) < 0) goto memory_error; - if (!(info->name = strdup(name))) - goto memory_error; + if (VIR_STRDUP(info->name, name) < 0) + goto error; memcpy(info->uuid, uuid, VIR_UUID_BUFLEN); info->id = id; @@ -2521,6 +2519,7 @@ xenUnifiedAddDomainInfo(xenUnifiedDomainInfoListPtr list, return 0; memory_error: virReportOOMError(); +error: if (info) VIR_FREE(info->name); VIR_FREE(info); diff --git a/src/xen/xen_hypervisor.c b/src/xen/xen_hypervisor.c index e15f7f2..03ebc0e 100644 --- a/src/xen/xen_hypervisor.c +++ b/src/xen/xen_hypervisor.c @@ -1199,16 +1199,12 @@ xenHypervisorGetSchedulerType(virDomainPtr domain, int *nparams) switch (op.u.getschedulerid.sched_id){ case XEN_SCHEDULER_SEDF: - schedulertype = strdup("sedf"); - if (schedulertype == NULL) - virReportOOMError(); + ignore_value(VIR_STRDUP(schedulertype, "sedf")); if (nparams) *nparams = XEN_SCHED_SEDF_NPARAM; break; case XEN_SCHEDULER_CREDIT: - schedulertype = strdup("credit"); - if (schedulertype == NULL) - virReportOOMError(); + ignore_value(VIR_STRDUP(schedulertype, "credit")); if (nparams) *nparams = XEN_SCHED_CRED_NPARAM; break; @@ -2894,14 +2890,9 @@ xenHypervisorDomainGetOSType(virDomainPtr dom) return NULL; } - if (XEN_GETDOMAININFO_FLAGS(dominfo) & DOMFLAGS_HVM) - ostype = strdup("hvm"); - else - ostype = strdup("linux"); - - if (ostype == NULL) - virReportOOMError(); - + ignore_value(VIR_STRDUP(ostype, + XEN_GETDOMAININFO_FLAGS(dominfo) & DOMFLAGS_HVM ? + "hvm" : "linux")); return ostype; } diff --git a/src/xen/xen_inotify.c b/src/xen/xen_inotify.c index d83708c..fe9ce65 100644 --- a/src/xen/xen_inotify.c +++ b/src/xen/xen_inotify.c @@ -39,7 +39,7 @@ #include "virlog.h" #include "viruuid.h" #include "virfile.h" - +#include "virstring.h" #include "xm_internal.h" /* for xenXMDomainConfigParse */ #define VIR_FROM_THIS VIR_FROM_XEN_INOTIFY @@ -62,12 +62,9 @@ xenInotifyXenCacheLookup(virConnectPtr conn, return -1; } - *name = strdup(entry->def->name); memcpy(uuid, entry->def->uuid, VIR_UUID_BUFLEN); - - if (!*name) { + if (VIR_STRDUP(*name, entry->def->name) < 0) { VIR_DEBUG("Error getting dom from def"); - virReportOOMError(); return -1; } return 0; @@ -107,11 +104,8 @@ xenInotifyXendDomainsDirLookup(virConnectPtr conn, list info */ for (i = 0 ; i < priv->configInfoList->count ; i++) { if (!memcmp(rawuuid, priv->configInfoList->doms[i]->uuid, VIR_UUID_BUFLEN)) { - *name = strdup(priv->configInfoList->doms[i]->name); - if (!*name) { - virReportOOMError(); + if (VIR_STRDUP(*name, priv->configInfoList->doms[i]->name) < 0) return -1; - } memcpy(uuid, priv->configInfoList->doms[i]->uuid, VIR_UUID_BUFLEN); VIR_DEBUG("Found dom on list"); return 0; @@ -122,8 +116,7 @@ xenInotifyXendDomainsDirLookup(virConnectPtr conn, return -1; } - if (!(*name = strdup(dom->name))) { - virReportOOMError(); + if (VIR_STRDUP(*name, dom->name) < 0) { virDomainFree(dom); return -1; } diff --git a/src/xen/xend_internal.c b/src/xen/xend_internal.c index 97f44ab..78edba4 100644 --- a/src/xen/xend_internal.c +++ b/src/xen/xend_internal.c @@ -761,8 +761,7 @@ xenDaemonListDomainsOld(virConnectPtr xend) _for_i = _for_i->u.s.cdr, node = _for_i->u.s.car) { if (node->kind != SEXPR_VALUE) continue; - ret[i] = strdup(node->u.value); - if (!ret[i]) + if (VIR_STRDUP(ret[i], node->u.value) < 0) goto no_memory; i++; } @@ -887,13 +886,8 @@ xenDaemonDomainLookupByID(virConnectPtr xend, "%s", _("domain information incomplete, missing name")); goto error; } - if (domname) { - *domname = strdup(name); - if (*domname == NULL) { - virReportOOMError(); - goto error; - } - } + if (domname && VIR_STRDUP(*domname, name) < 0) + goto error; if (sexpr_uuid(uuid, root, "domain/uuid") < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, @@ -1454,14 +1448,8 @@ xenDaemonDomainGetOSType(virDomainPtr domain) if (root == NULL) return NULL; - if (sexpr_lookup(root, "domain/image/hvm")) { - type = strdup("hvm"); - } else { - type = strdup("linux"); - } - - if (type == NULL) - virReportOOMError(); + ignore_value(VIR_STRDUP(type, + sexpr_lookup(root, "domain/image/hvm") ? "hvm" : "linux")); sexpr_free(root); @@ -2363,12 +2351,8 @@ xenDaemonLookupByUUID(virConnectPtr conn, const unsigned char *uuid) else id = -1; - if (domname) { - name = strdup(domname); - - if (name == NULL) - virReportOOMError(); - } + if (domname) + ignore_value(VIR_STRDUP(name, domname)); sexpr_free(root); } @@ -2532,12 +2516,9 @@ xenDaemonAttachDeviceFlags(virDomainPtr domain, priv->xendConfigVersion, 1) < 0) goto cleanup; - if (dev->data.disk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) { - if (!(target = strdup(dev->data.disk->dst))) { - virReportOOMError(); - goto cleanup; - } - } + if (dev->data.disk->device != VIR_DOMAIN_DISK_DEVICE_CDROM && + VIR_STRDUP(target, dev->data.disk->dst) < 0) + goto cleanup; break; case VIR_DOMAIN_DEVICE_NET: @@ -2551,10 +2532,8 @@ xenDaemonAttachDeviceFlags(virDomainPtr domain, char macStr[VIR_MAC_STRING_BUFLEN]; virMacAddrFormat(&dev->data.net->mac, macStr); - if (!(target = strdup(macStr))) { - virReportOOMError(); + if (VIR_STRDUP(target, macStr) < 0) goto cleanup; - } break; case VIR_DOMAIN_DEVICE_HOSTDEV: @@ -2886,12 +2865,9 @@ xenDaemonDomainSetAutostart(virDomainPtr domain, int autostart) /* Change the autostart value in place, then define the new sexpr */ VIR_FREE(autonode->u.s.car->u.value); - autonode->u.s.car->u.value = (autostart ? strdup("start") - : strdup("ignore")); - if (!(autonode->u.s.car->u.value)) { - virReportOOMError(); + if (VIR_STRDUP(autonode->u.s.car->u.value, + autostart ? "start" : "ignore") < 0) goto error; - } if (sexpr2string(root, &buffer) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, @@ -3050,9 +3026,7 @@ xenDaemonDomainMigratePerform(virDomainPtr domain, virURIFree(uriptr); return -1; } - hostname = strdup(uriptr->server); - if (!hostname) { - virReportOOMError(); + if (VIR_STRDUP(hostname, uriptr->server) < 0) { virURIFree(uriptr); return -1; } @@ -3072,19 +3046,13 @@ xenDaemonDomainMigratePerform(virDomainPtr domain, /* Get the hostname. */ n = p - uri; /* n = Length of hostname in bytes. */ - hostname = strdup(uri); - if (!hostname) { - virReportOOMError(); + if (VIR_STRDUP(hostname, uri) < 0) return -1; - } hostname[n] = '\0'; } else { /* "hostname" (or IP address) */ - hostname = strdup(uri); - if (!hostname) { - virReportOOMError(); + if (VIR_STRDUP(hostname, uri) < 0) return -1; - } } VIR_DEBUG("hostname = %s, port = %s", hostname, port); @@ -3263,10 +3231,8 @@ xenDaemonListDefinedDomains(virConnectPtr conn, if (node->kind != SEXPR_VALUE) continue; - if ((names[ret++] = strdup(node->u.value)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(names[ret++], node->u.value) < 0) goto error; - } if (ret >= maxnames) break; @@ -3322,19 +3288,13 @@ xenDaemonGetSchedulerType(virDomainPtr domain, int *nparams) goto error; } if (STREQ(ret, "credit")) { - schedulertype = strdup("credit"); - if (schedulertype == NULL){ - virReportOOMError(); + if (VIR_STRDUP(schedulertype, "credit") < 0) goto error; - } if (nparams) *nparams = XEN_SCHED_CRED_NPARAM; } else if (STREQ(ret, "sedf")) { - schedulertype = strdup("sedf"); - if (schedulertype == NULL){ - virReportOOMError(); + if (VIR_STRDUP(schedulertype, "sedf") < 0) goto error; - } if (nparams) *nparams = XEN_SCHED_SEDF_NPARAM; } else { diff --git a/src/xen/xm_internal.c b/src/xen/xm_internal.c index 921c66a..b261e34 100644 --- a/src/xen/xm_internal.c +++ b/src/xen/xm_internal.c @@ -260,8 +260,7 @@ xenXMConfigCacheAddFile(virConnectPtr conn, const char *filename) virReportOOMError(); return -1; } - if ((entry->filename = strdup(filename)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(entry->filename, filename) < 0) { VIR_FREE(entry); return -1; } @@ -1092,10 +1091,8 @@ xenXMDomainDefineXML(virConnectPtr conn, const char *xml) goto error; } - if ((entry->filename = strdup(filename)) == NULL) { - virReportOOMError(); + if (VIR_STRDUP(entry->filename, filename) < 0) goto error; - } entry->def = def; if (virHashAddEntry(priv->configCache, filename, entry) < 0) { @@ -1190,7 +1187,7 @@ xenXMListIterator(void *payload ATTRIBUTE_UNUSED, const void *name, void *data) dom = xenDaemonLookupByName(ctx->conn, name); if (!dom) { - if (!(ctx->names[ctx->count] = strdup(name))) + if (VIR_STRDUP(ctx->names[ctx->count], name) < 0) ctx->oom = 1; else ctx->count++; diff --git a/src/xen/xs_internal.c b/src/xen/xs_internal.c index 5f0df63..776ddc6 100644 --- a/src/xen/xs_internal.c +++ b/src/xen/xs_internal.c @@ -50,6 +50,7 @@ #include "xen_driver.h" #include "xs_internal.h" #include "xen_hypervisor.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_XEN @@ -851,11 +852,7 @@ xenStoreDomainGetNetworkID(virConnectPtr conn, int id, const char *mac) VIR_FREE(val); if (match) { - ret = strdup(list[i]); - - if (ret == NULL) - virReportOOMError(); - + ignore_value(VIR_STRDUP(ret, list[i])); break; } } @@ -904,10 +901,7 @@ xenStoreDomainGetDiskID(virConnectPtr conn, int id, const char *dev) if ((devlen != len) || memcmp(val, dev, len)) { VIR_FREE(val); } else { - ret = strdup(list[i]); - - if (ret == NULL) - virReportOOMError(); + ignore_value(VIR_STRDUP(ret, list[i])); VIR_FREE(val); VIR_FREE(list); @@ -927,10 +921,7 @@ xenStoreDomainGetDiskID(virConnectPtr conn, int id, const char *dev) if ((devlen != len) || memcmp(val, dev, len)) { VIR_FREE(val); } else { - ret = strdup(list[i]); - - if (ret == NULL) - virReportOOMError(); + ignore_value(VIR_STRDUP(ret, list[i])); VIR_FREE(val); VIR_FREE(list); @@ -982,7 +973,7 @@ xenStoreDomainGetPCIID(virConnectPtr conn, int id, const char *bdf) VIR_FREE(val); if (match) { - ret = strdup(list[i]); + ignore_value(VIR_STRDUP(ret, list[i])); break; } } @@ -1088,22 +1079,22 @@ xenStoreAddWatch(virConnectPtr conn, } } - if (VIR_ALLOC(watch) < 0) - goto no_memory; + if (VIR_ALLOC(watch) < 0) { + virReportOOMError(); + goto error; + } - watch->path = strdup(path); - watch->token = strdup(token); - watch->cb = cb; + watch->cb = cb; watch->opaque = opaque; - - if (watch->path == NULL || watch->token == NULL) { - goto no_memory; - } + if (VIR_STRDUP(watch->path, path) < 0 || + VIR_STRDUP(watch->token, token) < 0) + goto error; /* Make space on list */ n = list->count; if (VIR_REALLOC_N(list->watches, n + 1) < 0) { - goto no_memory; + virReportOOMError(); + goto error; } list->watches[n] = watch; @@ -1111,15 +1102,12 @@ xenStoreAddWatch(virConnectPtr conn, return xs_watch(priv->xshandle, watch->path, watch->token); - no_memory: + error: if (watch) { VIR_FREE(watch->path); VIR_FREE(watch->token); VIR_FREE(watch); } - - virReportOOMError(); - return -1; } -- 1.8.1.5

--- src/xenapi/xenapi_driver.c | 59 ++++++++++++++++++++-------------------------- src/xenapi/xenapi_utils.c | 39 +++++++++++++++--------------- 2 files changed, 46 insertions(+), 52 deletions(-) diff --git a/src/xenapi/xenapi_driver.c b/src/xenapi/xenapi_driver.c index 7e64df6..2dcd024 100644 --- a/src/xenapi/xenapi_driver.c +++ b/src/xenapi/xenapi_driver.c @@ -135,12 +135,8 @@ xenapiConnectOpen(virConnectPtr conn, virConnectAuthPtr auth, } if (conn->uri->user != NULL) { - username = strdup(conn->uri->user); - - if (username == NULL) { - virReportOOMError(); + if (VIR_STRDUP(username, conn->uri->user) < 0) goto error; - } } else { username = virAuthGetUsername(conn, auth, "xen", NULL, conn->uri->server); @@ -320,9 +316,8 @@ xenapiConnectGetVersion(virConnectPtr conn, unsigned long *hvVer) if (result && result->size > 0) { for (i = 0; i < result->size; i++) { if (STREQ(result->contents[i].key, "xen")) { - if (!(version = strdup(result->contents[i].val))) { + if (VIR_STRDUP(version, result->contents[i].val) < 0) { xen_string_string_map_free(result); - virReportOOMError(); return -1; } break; @@ -952,8 +947,8 @@ xenapiDomainGetOSType(virDomainPtr dom) xenapiSessionErrorHandler(dom->conn, VIR_ERR_INTERNAL_ERROR, NULL); goto cleanup; } - if (!(ostype = (STREQ(boot_policy,"BIOS order") ? strdup("hvm") : strdup("xen")))) - virReportOOMError(); + ignore_value(VIR_STRDUP(ostype, + STREQ(boot_policy, "BIOS order") ? "hvm" : "xen")); VIR_FREE(boot_policy); } else xenapiSessionErrorHandler(dom->conn, VIR_ERR_NO_DOMAIN, NULL); @@ -1268,10 +1263,9 @@ xenapiDomainGetVcpus(virDomainPtr dom, } for (i = 0; i < vcpu_params->size; i++) { if (STREQ(vcpu_params->contents[i].key, "mask")) { - if (!(mask = strdup(vcpu_params->contents[i].val))){ + if (VIR_STRDUP(mask, vcpu_params->contents[i].val) < 0){ xen_vm_set_free(vms); xen_string_string_map_free(vcpu_params); - virReportOOMError(); return -1; } break; @@ -1386,13 +1380,13 @@ xenapiDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) defPtr->virtType = VIR_DOMAIN_VIRT_XEN; defPtr->id = dom->id; memcpy(defPtr->uuid, dom->uuid, VIR_UUID_BUFLEN); - if (!(defPtr->name = strdup(dom->name))) - goto error_cleanup; + if (VIR_STRDUP(defPtr->name, dom->name) < 0) + goto error; xen_vm_get_hvm_boot_policy(session, &boot_policy, vm); if (STREQ(boot_policy,"BIOS order")) { - if (!(defPtr->os.type = strdup("hvm"))) { + if (VIR_STRDUP(defPtr->os.type, "hvm") < 0) { VIR_FREE(boot_policy); - goto error_cleanup; + goto error; } xen_vm_get_hvm_boot_params(session, &result, vm); if (result != NULL) { @@ -1413,50 +1407,50 @@ xenapiDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) VIR_FREE(boot_policy); } else { char *value = NULL; - if (!(defPtr->os.type = strdup("xen"))) { + if (VIR_STRDUP(defPtr->os.type, "xen") < 0) { VIR_FREE(boot_policy); - goto error_cleanup; + goto error; } - if (!(defPtr->os.loader = strdup("pygrub"))) { + if (VIR_STRDUP(defPtr->os.loader, "pygrub") < 0) { VIR_FREE(boot_policy); - goto error_cleanup; + goto error; } xen_vm_get_pv_kernel(session, &value, vm); if (STRNEQ(value, "")) { - if (!(defPtr->os.kernel = strdup(value))) { + if (VIR_STRDUP(defPtr->os.kernel, value) < 0) { VIR_FREE(boot_policy); VIR_FREE(value); - goto error_cleanup; + goto error; } VIR_FREE(value); } xen_vm_get_pv_ramdisk(session, &value, vm); if (STRNEQ(value, "")) { - if (!(defPtr->os.initrd = strdup(value))) { + if (VIR_STRDUP(defPtr->os.initrd, value) < 0) { VIR_FREE(boot_policy); VIR_FREE(value); - goto error_cleanup; + goto error; } VIR_FREE(value); } xen_vm_get_pv_args(session, &value, vm); if (STRNEQ(value, "")) { - if (!(defPtr->os.cmdline = strdup(value))) { + if (VIR_STRDUP(defPtr->os.cmdline, value) < 0) { VIR_FREE(boot_policy); VIR_FREE(value); - goto error_cleanup; + goto error; } VIR_FREE(value); } VIR_FREE(boot_policy); - if (!(defPtr->os.bootloader = strdup("pygrub"))) - goto error_cleanup; + if (VIR_STRDUP(defPtr->os.bootloader, "pygrub") < 0) + goto error; } xen_vm_get_pv_bootloader_args(session, &val, vm); if (STRNEQ(val, "")) { - if (!(defPtr->os.bootloaderArgs = strdup(val))) { + if (VIR_STRDUP(defPtr->os.bootloaderArgs, val) < 0) { VIR_FREE(val); - goto error_cleanup; + goto error; } VIR_FREE(val); } @@ -1542,6 +1536,7 @@ xenapiDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) error_cleanup: virReportOOMError(); + error: xen_vm_set_free(vms); virDomainDefFree(defPtr); return NULL; @@ -1569,8 +1564,7 @@ xenapiConnectListDefinedDomains(virConnectPtr conn, char **const names, if (record != NULL) { if (record->is_a_template == 0) { char *usenames = NULL; - if (!(usenames = strdup(record->name_label))) { - virReportOOMError(); + if (VIR_STRDUP(usenames, record->name_label) < 0) { xen_vm_record_free(record); xen_vm_set_free(result); while (--j >= 0) VIR_FREE(names[j]); @@ -1862,8 +1856,7 @@ xenapiDomainGetSchedulerType(virDomainPtr dom ATTRIBUTE_UNUSED, int *nparams) if (nparams) *nparams = 0; - if (!(result = strdup("credit"))) - virReportOOMError(); + ignore_value(VIR_STRDUP(result, "credit")); return result; } diff --git a/src/xenapi/xenapi_utils.c b/src/xenapi/xenapi_utils.c index 55fbb24..46e1aea 100644 --- a/src/xenapi/xenapi_utils.c +++ b/src/xenapi/xenapi_utils.c @@ -352,12 +352,12 @@ allocStringMap(xen_string_string_map **strings, char *key, char *val) return -1; } (*strings)->size = sz; - if (!((*strings)->contents[sz-1].key = strdup(key))) goto error; - if (!((*strings)->contents[sz-1].val = strdup(val))) goto error; + if (VIR_STRDUP((*strings)->contents[sz-1].key, key) < 0 || + VIR_STRDUP((*strings)->contents[sz-1].val, val) < 0) + goto error; return 0; error: xen_string_string_map_free(*strings); - virReportOOMError(); return -1; } @@ -455,17 +455,17 @@ createVMRecordFromXml(virConnectPtr conn, virDomainDefPtr def, int i; *record = xen_vm_record_alloc(); - if (!((*record)->name_label = strdup(def->name))) - goto error_cleanup; + if (VIR_STRDUP((*record)->name_label, def->name) < 0) + goto error; if (def->uuid) { virUUIDFormat(def->uuid, uuidStr); - if (!((*record)->uuid = strdup(uuidStr))) - goto error_cleanup; + if (VIR_STRDUP((*record)->uuid, uuidStr) < 0) + goto error; } if (STREQ(def->os.type, "hvm")) { char *boot_order = NULL; - if (!((*record)->hvm_boot_policy = strdup("BIOS order"))) - goto error_cleanup; + if (VIR_STRDUP((*record)->hvm_boot_policy, "BIOS order") < 0) + goto error; if (def->os.nBootDevs != 0) boot_order = createXenAPIBootOrderString(def->os.nBootDevs, &def->os.bootDevs[0]); if (boot_order != NULL) { @@ -475,25 +475,25 @@ createVMRecordFromXml(virConnectPtr conn, virDomainDefPtr def, VIR_FREE(boot_order); } } else if (STREQ(def->os.type, "xen")) { - if (!((*record)->pv_bootloader = strdup("pygrub"))) - goto error_cleanup; + if (VIR_STRDUP((*record)->pv_bootloader, "pygrub") < 0) + goto error; if (def->os.kernel) { - if (!((*record)->pv_kernel = strdup(def->os.kernel))) - goto error_cleanup; + if (VIR_STRDUP((*record)->pv_kernel, def->os.kernel) < 0) + goto error; } if (def->os.initrd) { - if (!((*record)->pv_ramdisk = strdup(def->os.initrd))) - goto error_cleanup; + if (VIR_STRDUP((*record)->pv_ramdisk, def->os.initrd) < 0) + goto error; } if (def->os.cmdline) { - if (!((*record)->pv_args = strdup(def->os.cmdline))) - goto error_cleanup; + if (VIR_STRDUP((*record)->pv_args, def->os.cmdline) < 0) + goto error; } (*record)->hvm_boot_params = xen_string_string_map_alloc(0); } if (def->os.bootloaderArgs) - if (!((*record)->pv_bootloader_args = strdup(def->os.bootloaderArgs))) - goto error_cleanup; + if (VIR_STRDUP((*record)->pv_bootloader_args, def->os.bootloaderArgs) < 0) + goto error; if (def->mem.cur_balloon) (*record)->memory_static_max = (int64_t) (def->mem.cur_balloon * 1024); @@ -561,6 +561,7 @@ createVMRecordFromXml(virConnectPtr conn, virDomainDefPtr def, error_cleanup: virReportOOMError(); + error: xen_vm_record_free(*record); return -1; } -- 1.8.1.5

--- src/xenxs/xen_sxpr.c | 192 +++++++++++++++++++++++---------------------------- src/xenxs/xen_xm.c | 94 +++++++++++-------------- 2 files changed, 125 insertions(+), 161 deletions(-) diff --git a/src/xenxs/xen_sxpr.c b/src/xenxs/xen_sxpr.c index 9a76d04..4b486b2 100644 --- a/src/xenxs/xen_sxpr.c +++ b/src/xenxs/xen_sxpr.c @@ -192,9 +192,8 @@ xenParseSxprChar(const char *value, if (value[0] == '/') { def->source.type = VIR_DOMAIN_CHR_TYPE_DEV; - def->source.data.file.path = strdup(value); - if (!def->source.data.file.path) - goto no_memory; + if (VIR_STRDUP(def->source.data.file.path, value) < 0) + goto error; } else { if ((tmp = strchr(value, ':')) != NULL) { *tmp = '\0'; @@ -215,15 +214,14 @@ xenParseSxprChar(const char *value, switch (def->source.type) { case VIR_DOMAIN_CHR_TYPE_PTY: - if (tty != NULL && - !(def->source.data.file.path = strdup(tty))) - goto no_memory; + if (tty && VIR_STRDUP(def->source.data.file.path, tty) < 0) + goto error; break; case VIR_DOMAIN_CHR_TYPE_FILE: case VIR_DOMAIN_CHR_TYPE_PIPE: - if (!(def->source.data.file.path = strdup(value))) - goto no_memory; + if (VIR_STRDUP(def->source.data.file.path, value) < 0) + goto error; break; case VIR_DOMAIN_CHR_TYPE_TCP: @@ -238,18 +236,14 @@ xenParseSxprChar(const char *value, } if (offset != value && - (def->source.data.tcp.host = strndup(value, - offset - value)) == NULL) - goto no_memory; + VIR_STRNDUP(def->source.data.tcp.host, value, offset - value) < 0) + goto error; offset2 = strchr(offset, ','); - if (offset2 == NULL) - def->source.data.tcp.service = strdup(offset+1); - else - def->source.data.tcp.service = strndup(offset+1, - offset2-(offset+1)); - if (def->source.data.tcp.service == NULL) - goto no_memory; + if ((offset && VIR_STRNDUP(def->source.data.tcp.service, + offset + 1, offset2 - offset - 1) < 0) || + (!offset && VIR_STRDUP(def->source.data.tcp.service, offset + 1) < 0)) + goto error; if (offset2 && strstr(offset2, ",server")) def->source.data.tcp.listen = true; @@ -268,15 +262,14 @@ xenParseSxprChar(const char *value, } if (offset != value && - (def->source.data.udp.connectHost - = strndup(value, offset - value)) == NULL) - goto no_memory; + VIR_STRNDUP(def->source.data.udp.connectHost, value, offset - value) < 0) + goto error; offset2 = strchr(offset, '@'); if (offset2 != NULL) { - if ((def->source.data.udp.connectService - = strndup(offset + 1, offset2-(offset+1))) == NULL) - goto no_memory; + if (VIR_STRNDUP(def->source.data.udp.connectService, + offset + 1, offset2 - offset - 1) < 0) + goto error; offset3 = strchr(offset2, ':'); if (offset3 == NULL) { @@ -286,17 +279,15 @@ xenParseSxprChar(const char *value, } if (offset3 > (offset2 + 1) && - (def->source.data.udp.bindHost - = strndup(offset2 + 1, offset3 - (offset2+1))) == NULL) - goto no_memory; + VIR_STRNDUP(def->source.data.udp.bindHost, + offset2 + 1, offset3 - offset2 - 1) < 0) + goto error; - if ((def->source.data.udp.bindService - = strdup(offset3 + 1)) == NULL) - goto no_memory; + if (VIR_STRDUP(def->source.data.udp.bindService, offset3 + 1) < 0) + goto error; } else { - if ((def->source.data.udp.connectService - = strdup(offset + 1)) == NULL) - goto no_memory; + if (VIR_STRDUP(def->source.data.udp.connectService, offset + 1) < 0) + goto error; } } break; @@ -304,12 +295,9 @@ xenParseSxprChar(const char *value, case VIR_DOMAIN_CHR_TYPE_UNIX: { const char *offset = strchr(value, ','); - if (offset) - def->source.data.nix.path = strndup(value, (offset - value)); - else - def->source.data.nix.path = strdup(value); - if (def->source.data.nix.path == NULL) - goto no_memory; + if ((offset && VIR_STRNDUP(def->source.data.nix.path, value, offset - value) < 0) || + (!offset && VIR_STRDUP(def->source.data.nix.path, value) < 0)) + goto error; if (offset != NULL && strstr(offset, ",server") != NULL) @@ -320,8 +308,6 @@ xenParseSxprChar(const char *value, return def; -no_memory: - virReportOOMError(); error: virDomainChrDefFree(def); return NULL; @@ -411,8 +397,8 @@ xenParseSxprDisks(virDomainDefPtr def, if (sexpr_lookup(node, "device/tap2") && STRPREFIX(src, "tap:")) { - if (!(disk->driverName = strdup("tap2"))) - goto no_memory; + if (VIR_STRDUP(disk->driverName, "tap2") < 0) + goto error; } else { if (VIR_ALLOC_N(disk->driverName, (offset-src)+1) < 0) goto no_memory; @@ -438,8 +424,8 @@ xenParseSxprDisks(virDomainDefPtr def, goto error; } - if (!(driverType = strndup(src, offset - src))) - goto no_memory; + if (VIR_STRNDUP(driverType, src, offset - src) < 0) + goto error; if (STREQ(driverType, "aio")) disk->format = VIR_STORAGE_FILE_RAW; else @@ -490,11 +476,10 @@ xenParseSxprDisks(virDomainDefPtr def, } } - if (!(disk->dst = strdup(dst))) - goto no_memory; - if (src && - !(disk->src = strdup(src))) - goto no_memory; + if (VIR_STRDUP(disk->dst, dst) < 0) + goto error; + if (src && VIR_STRDUP(disk->src, src) < 0) + goto error; if (STRPREFIX(disk->dst, "xvd")) disk->bus = VIR_DOMAIN_DISK_BUS_XEN; @@ -572,26 +557,21 @@ xenParseSxprNets(virDomainDefPtr def, net->type = VIR_DOMAIN_NET_TYPE_BRIDGE; /* XXX virtual network reverse resolve */ - if (tmp && - !(net->data.bridge.brname = strdup(tmp))) - goto no_memory; - if (tmp2 && - net->type == VIR_DOMAIN_NET_TYPE_BRIDGE && - !(net->script = strdup(tmp2))) - goto no_memory; + if (tmp && VIR_STRDUP(net->data.bridge.brname, tmp) < 0) + goto cleanup; + if (tmp2 && net->type == VIR_DOMAIN_NET_TYPE_BRIDGE && + VIR_STRDUP(net->script, tmp2) < 0) + goto cleanup; tmp = sexpr_node(node, "device/vif/ip"); - if (tmp && - !(net->data.bridge.ipaddr = strdup(tmp))) - goto no_memory; + if (tmp && VIR_STRDUP(net->data.bridge.ipaddr, tmp) < 0) + goto cleanup; } else { net->type = VIR_DOMAIN_NET_TYPE_ETHERNET; - if (tmp2 && - !(net->script = strdup(tmp2))) - goto no_memory; + if (tmp2 && VIR_STRDUP(net->script, tmp2) < 0) + goto cleanup; tmp = sexpr_node(node, "device/vif/ip"); - if (tmp && - !(net->data.ethernet.ipaddr = strdup(tmp))) - goto no_memory; + if (tmp && VIR_STRDUP(net->data.ethernet.ipaddr, tmp) < 0) + goto cleanup; } tmp = sexpr_node(node, "device/vif/vifname"); @@ -599,8 +579,8 @@ xenParseSxprNets(virDomainDefPtr def, * definition regardless of domain state. If vifname is not * specified, only generate one if domain is active (id != -1). */ if (tmp) { - if (!(net->ifname = strdup(tmp))) - goto no_memory; + if (VIR_STRDUP(net->ifname, tmp) < 0) + goto cleanup; } else if (def->id != -1) { if (virAsprintf(&net->ifname, "vif%d.%d", def->id, vif_index) < 0) goto no_memory; @@ -615,14 +595,12 @@ xenParseSxprNets(virDomainDefPtr def, } } - if (model && - !(net->model = strdup(model))) - goto no_memory; + if (model && VIR_STRDUP(net->model, model) < 0) + goto cleanup; - if (!model && type && - STREQ(type, "netfront") && - !(net->model = strdup("netfront"))) - goto no_memory; + if (!model && type && STREQ(type, "netfront") && + VIR_STRDUP(net->model, "netfront") < 0) + goto cleanup; if (VIR_REALLOC_N(def->nets, def->nnets + 1) < 0) goto no_memory; @@ -834,12 +812,12 @@ xenParseSxprGraphicsOld(virDomainDefPtr def, goto error; if (vncPasswd && - !(graphics->data.vnc.auth.passwd = strdup(vncPasswd))) - goto no_memory; + VIR_STRDUP(graphics->data.vnc.auth.passwd, vncPasswd) < 0) + goto error; if (keymap && - !(graphics->data.vnc.keymap = strdup(keymap))) - goto no_memory; + VIR_STRDUP(graphics->data.vnc.keymap, keymap) < 0) + goto error; if (VIR_ALLOC_N(def->graphics, 1) < 0) goto no_memory; @@ -857,11 +835,11 @@ xenParseSxprGraphicsOld(virDomainDefPtr def, graphics->type = VIR_DOMAIN_GRAPHICS_TYPE_SDL; if (display && - !(graphics->data.sdl.display = strdup(display))) - goto no_memory; + VIR_STRDUP(graphics->data.sdl.display, display) < 0) + goto error; if (xauth && - !(graphics->data.sdl.xauth = strdup(xauth))) - goto no_memory; + VIR_STRDUP(graphics->data.sdl.xauth, xauth) < 0) + goto error; if (VIR_ALLOC_N(def->graphics, 1) < 0) goto no_memory; @@ -927,11 +905,11 @@ xenParseSxprGraphicsNew(virDomainDefPtr def, const char *display = sexpr_node(node, "device/vfb/display"); const char *xauth = sexpr_node(node, "device/vfb/xauthority"); if (display && - !(graphics->data.sdl.display = strdup(display))) - goto no_memory; + VIR_STRDUP(graphics->data.sdl.display, display) < 0) + goto error; if (xauth && - !(graphics->data.sdl.xauth = strdup(xauth))) - goto no_memory; + VIR_STRDUP(graphics->data.sdl.xauth, xauth) < 0) + goto error; } else { int port; const char *listenAddr = sexpr_node(node, "device/vfb/vnclisten"); @@ -961,12 +939,12 @@ xenParseSxprGraphicsNew(virDomainDefPtr def, goto error; if (vncPasswd && - !(graphics->data.vnc.auth.passwd = strdup(vncPasswd))) - goto no_memory; + VIR_STRDUP(graphics->data.vnc.auth.passwd, vncPasswd) < 0) + goto error; if (keymap && - !(graphics->data.vnc.keymap = strdup(keymap))) - goto no_memory; + VIR_STRDUP(graphics->data.vnc.keymap, keymap) < 0) + goto error; } if (VIR_ALLOC_N(def->graphics, 1) < 0) @@ -1180,8 +1158,8 @@ xenParseSxpr(const struct sexpr *root, if (!def->os.bootloader && sexpr_has(root, "domain/bootloader") && - (def->os.bootloader = strdup("")) == NULL) - goto no_memory; + VIR_STRDUP(def->os.bootloader, "") < 0) + goto error; if (def->os.bootloader && sexpr_node_copy(root, "domain/bootloader_args", @@ -1189,8 +1167,8 @@ xenParseSxpr(const struct sexpr *root, goto no_memory; } - if (!(def->os.type = strdup(hvm ? "hvm" : "linux"))) - goto no_memory; + if (VIR_STRDUP(def->os.type, hvm ? "hvm" : "linux") < 0) + goto error; if (def->id != 0) { if (sexpr_lookup(root, "domain/image")) { @@ -1357,19 +1335,19 @@ xenParseSxpr(const struct sexpr *root, virDomainDiskDefPtr disk; if (VIR_ALLOC(disk) < 0) goto no_memory; - if (!(disk->src = strdup(tmp))) { + if (VIR_STRDUP(disk->src, tmp) < 0) { virDomainDiskDefFree(disk); - goto no_memory; + goto error; } disk->type = VIR_DOMAIN_DISK_TYPE_FILE; disk->device = VIR_DOMAIN_DISK_DEVICE_CDROM; - if (!(disk->dst = strdup("hdc"))) { + if (VIR_STRDUP(disk->dst, "hdc") < 0) { virDomainDiskDefFree(disk); - goto no_memory; + goto error; } - if (!(disk->driverName = strdup("file"))) { + if (VIR_STRDUP(disk->driverName, "file") < 0) { virDomainDiskDefFree(disk); - goto no_memory; + goto error; } disk->bus = VIR_DOMAIN_DISK_BUS_IDE; disk->readonly = true; @@ -1393,19 +1371,19 @@ xenParseSxpr(const struct sexpr *root, virDomainDiskDefPtr disk; if (VIR_ALLOC(disk) < 0) goto no_memory; - if (!(disk->src = strdup(tmp))) { + if (VIR_STRDUP(disk->src, tmp) < 0) { VIR_FREE(disk); - goto no_memory; + goto error; } disk->type = VIR_DOMAIN_DISK_TYPE_FILE; disk->device = VIR_DOMAIN_DISK_DEVICE_FLOPPY; - if (!(disk->dst = strdup(fds[i]))) { + if (VIR_STRDUP(disk->dst, fds[i]) < 0) { virDomainDiskDefFree(disk); - goto no_memory; + goto error; } - if (!(disk->driverName = strdup("file"))) { + if (VIR_STRDUP(disk->driverName, "file") < 0) { virDomainDiskDefFree(disk); - goto no_memory; + goto error; } disk->bus = VIR_DOMAIN_DISK_BUS_FDC; diff --git a/src/xenxs/xen_xm.c b/src/xenxs/xen_xm.c index 57ce2e7..d3c44c8 100644 --- a/src/xenxs/xen_xm.c +++ b/src/xenxs/xen_xm.c @@ -183,12 +183,7 @@ static int xenXMConfigCopyStringInternal(virConfPtr conf, return -1; } - if (!(*value = strdup(val->str))) { - virReportOOMError(); - return -1; - } - - return 0; + return VIR_STRDUP(*value, val->str); } @@ -288,8 +283,8 @@ xenParseXM(virConfPtr conf, int xendConfigVersion, STREQ(str, "hvm")) hvm = 1; - if (!(def->os.type = strdup(hvm ? "hvm" : "xen"))) - goto no_memory; + if (VIR_STRDUP(def->os.type, hvm ? "hvm" : "xen") < 0) + goto cleanup; def->os.arch = virCapabilitiesDefaultGuestArch(caps, @@ -307,8 +302,8 @@ xenParseXM(virConfPtr conf, int xendConfigVersion, def->os.arch, virDomainVirtTypeToString(def->virtType)); if (defaultMachine != NULL) { - if (!(def->os.machine = strdup(defaultMachine))) - goto no_memory; + if (VIR_STRDUP(def->os.machine, defaultMachine) < 0) + goto cleanup; } if (hvm) { @@ -562,8 +557,8 @@ xenParseXM(virConfPtr conf, int xendConfigVersion, if (!(tmp = strchr(disk->src, ':'))) goto skipdisk; - if (!(driverType = strndup(disk->src, tmp - disk->src))) - goto no_memory; + if (VIR_STRNDUP(driverType, disk->src, tmp - disk->src) < 0) + goto cleanup; if (STREQ(driverType, "aio")) disk->format = VIR_STORAGE_FILE_RAW; else @@ -585,8 +580,8 @@ xenParseXM(virConfPtr conf, int xendConfigVersion, /* No source, or driver name, so fix to phy: */ if (!disk->driverName && - !(disk->driverName = strdup("phy"))) - goto no_memory; + VIR_STRDUP(disk->driverName, "phy") < 0) + goto cleanup; /* phy: type indicates a block device */ @@ -637,12 +632,12 @@ xenParseXM(virConfPtr conf, int xendConfigVersion, disk->type = VIR_DOMAIN_DISK_TYPE_FILE; disk->device = VIR_DOMAIN_DISK_DEVICE_CDROM; - if (!(disk->driverName = strdup("file"))) - goto no_memory; - if (!(disk->src = strdup(str))) - goto no_memory; - if (!(disk->dst = strdup("hdc"))) - goto no_memory; + if (VIR_STRDUP(disk->driverName, "file") < 0) + goto cleanup; + if (VIR_STRDUP(disk->src, str) < 0) + goto cleanup; + if (VIR_STRDUP(disk->dst, "hdc") < 0) + goto cleanup; disk->bus = VIR_DOMAIN_DISK_BUS_IDE; disk->readonly = true; @@ -703,9 +698,8 @@ xenParseXM(virConfPtr conf, int xendConfigVersion, } else if (STRPREFIX(key, "script=")) { int len = nextkey ? (nextkey - data) : strlen(data); VIR_FREE(script); - if (!(script = strndup(data, len))) { - goto no_memory; - } + if (VIR_STRNDUP(script, data, len) < 0) + goto cleanup; } else if (STRPREFIX(key, "model=")) { int len = nextkey ? (nextkey - data) : sizeof(model) - 1; if (virStrncpy(model, data, len, sizeof(model)) == NULL) { @@ -763,34 +757,27 @@ xenParseXM(virConfPtr conf, int xendConfigVersion, } if (net->type == VIR_DOMAIN_NET_TYPE_BRIDGE) { - if (bridge[0] && - !(net->data.bridge.brname = strdup(bridge))) - goto no_memory; - if (ip[0] && - !(net->data.bridge.ipaddr = strdup(ip))) - goto no_memory; + if (bridge[0] && VIR_STRDUP(net->data.bridge.brname, bridge) < 0) + goto cleanup; + if (ip[0] && VIR_STRDUP(net->data.bridge.ipaddr, ip) < 0) + goto cleanup; } else { - if (ip[0] && - !(net->data.ethernet.ipaddr = strdup(ip))) - goto no_memory; + if (ip[0] && VIR_STRDUP(net->data.ethernet.ipaddr, ip) < 0) + goto cleanup; } - if (script && script[0] && - !(net->script = strdup(script))) - goto no_memory; + if (script && script[0] && VIR_STRDUP(net->script, script) < 0) + goto cleanup; - if (model[0] && - !(net->model = strdup(model))) + if (model[0] && VIR_STRDUP(net->model, model) < 0) goto no_memory; - if (!model[0] && type[0] && - STREQ(type, "netfront") && - !(net->model = strdup("netfront"))) - goto no_memory; + if (!model[0] && type[0] && STREQ(type, "netfront") && + VIR_STRDUP(net->model, "netfront") < 0) + goto cleanup; - if (vifname[0] && - !(net->ifname = strdup(vifname))) - goto no_memory; + if (vifname[0] && VIR_STRDUP(net->ifname, vifname) < 0) + goto cleanup; if (VIR_REALLOC_N(def->nets, def->nnets+1) < 0) goto no_memory; @@ -1019,21 +1006,21 @@ xenParseXM(virConfPtr conf, int xendConfigVersion, -1, true) < 0) goto cleanup; } else if (STRPREFIX(key, "vncpasswd=")) { - if (!(graphics->data.vnc.auth.passwd = strdup(key + 10))) - goto no_memory; + if (VIR_STRDUP(graphics->data.vnc.auth.passwd, key + 10) < 0) + goto cleanup; } else if (STRPREFIX(key, "keymap=")) { - if (!(graphics->data.vnc.keymap = strdup(key + 7))) - goto no_memory; + if (VIR_STRDUP(graphics->data.vnc.keymap, key + 7) < 0) + goto cleanup; } else if (STRPREFIX(key, "vncdisplay=")) { graphics->data.vnc.port = strtol(key+11, NULL, 10) + 5900; } } else { if (STRPREFIX(key, "display=")) { - if (!(graphics->data.sdl.display = strdup(key + 8))) - goto no_memory; + if (VIR_STRDUP(graphics->data.sdl.display, key + 8) < 0) + goto cleanup; } else if (STRPREFIX(key, "xauthority=")) { - if (!(graphics->data.sdl.xauth = strdup(key + 11))) - goto no_memory; + if (VIR_STRDUP(graphics->data.sdl.xauth, key + 11) < 0) + goto cleanup; } } @@ -1193,9 +1180,8 @@ int xenXMConfigSetString(virConfPtr conf, const char *setting, const char *str) value->type = VIR_CONF_STRING; value->next = NULL; - if (!(value->str = strdup(str))) { + if (VIR_STRDUP(value->str, str) < 0) { VIR_FREE(value); - virReportOOMError(); return -1; } -- 1.8.1.5

--- tests/commandhelper.c | 10 ++++++++-- tests/commandtest.c | 2 +- tests/openvzutilstest.c | 6 ++++-- tests/qemumonitortestutils.c | 15 +++++++-------- tests/qemuxml2argvtest.c | 23 ++++++++++++----------- tests/qemuxmlnstest.c | 4 +++- tests/securityselinuxhelper.c | 9 +++------ tests/securityselinuxlabeltest.c | 3 +-- tests/securityselinuxtest.c | 9 +++++---- tests/storagebackendsheepdogtest.c | 6 ++---- tests/testutils.c | 4 +++- tests/testutilsqemu.c | 5 ++++- tests/vircgrouptest.c | 2 +- tests/virnetmessagetest.c | 21 +++++++++------------ tests/vmx2xmltest.c | 9 ++++----- tests/xml2vmxtest.c | 9 ++++----- 16 files changed, 71 insertions(+), 66 deletions(-) diff --git a/tests/commandhelper.c b/tests/commandhelper.c index 92f031f..1be5d66 100644 --- a/tests/commandhelper.c +++ b/tests/commandhelper.c @@ -31,6 +31,9 @@ #include "viralloc.h" #include "virfile.h" #include "testutils.h" +#include "virstring.h" + +#define VIR_FROM_THIS VIR_FROM_NONE #ifndef WIN32 @@ -42,8 +45,11 @@ static int envsort(const void *a, const void *b) { const char *bstr = *bstrptr; char *aeq = strchr(astr, '='); char *beq = strchr(bstr, '='); - char *akey = strndup(astr, aeq - astr); - char *bkey = strndup(bstr, beq - bstr); + char *akey; + char *bkey; + if (VIR_STRNDUP(akey, astr, aeq - astr) < 0 || + VIR_STRNDUP(bkey, bstr, beq - bstr) < 0) + return -1; int ret = strcmp(akey, bkey); VIR_FREE(akey); VIR_FREE(bkey); diff --git a/tests/commandtest.c b/tests/commandtest.c index 6cb88c5..097e605 100644 --- a/tests/commandtest.c +++ b/tests/commandtest.c @@ -685,7 +685,7 @@ static int test17(const void *unused ATTRIBUTE_UNUSED) goto cleanup; } VIR_FREE(outbuf); - if ((outbuf = strdup("should not be leaked")) == NULL) { + if (VIR_STRDUP(outbuf, "should not be leaked") < 0) { puts("test framework failure"); goto cleanup; } diff --git a/tests/openvzutilstest.c b/tests/openvzutilstest.c index be0c74c..4850017 100644 --- a/tests/openvzutilstest.c +++ b/tests/openvzutilstest.c @@ -13,6 +13,8 @@ # include "openvz/openvz_conf.h" # include "virstring.h" +# define VIR_FROM_THIS VIR_FROM_OPENVZ + static int testLocateConfFile(int vpsid ATTRIBUTE_UNUSED, char **conffile, const char *ext ATTRIBUTE_UNUSED) @@ -103,8 +105,8 @@ testReadNetworkConf(const void *data ATTRIBUTE_UNUSED) "</domain>\n"; if (VIR_ALLOC(def) < 0 || - !(def->os.type = strdup("exe")) || - !(def->os.init = strdup("/sbin/init"))) + VIR_STRDUP(def->os.type, "exe") < 0 || + VIR_STRDUP(def->os.init, "/sbin/init") < 0) goto cleanup; def->virtType = VIR_DOMAIN_VIRT_OPENVZ; diff --git a/tests/qemumonitortestutils.c b/tests/qemumonitortestutils.c index c24a37f..df09802 100644 --- a/tests/qemumonitortestutils.c +++ b/tests/qemumonitortestutils.c @@ -159,10 +159,8 @@ static int qemuMonitorTestProcessCommandText(qemuMonitorTestPtr test, char *cmdname; int ret = -1; - if (!(cmdname = strdup(cmdstr))) { - virReportOOMError(); + if (VIR_STRDUP(cmdname, cmdstr) < 0) return -1; - } if (!(tmp = strchr(cmdname, ' '))) { virReportError(VIR_ERR_INTERNAL_ERROR, "Cannot find command name in '%s'", cmdstr); @@ -407,9 +405,9 @@ qemuMonitorTestAddItem(qemuMonitorTestPtr test, if (VIR_ALLOC(item) < 0) goto no_memory; - if (!(item->command_name = strdup(command_name)) || - !(item->response = strdup(response))) - goto no_memory; + if (VIR_STRDUP(item->command_name, command_name) < 0 || + VIR_STRDUP(item->response, response) < 0) + goto error; virMutexLock(&test->lock); if (VIR_EXPAND_N(test->items, test->nitems, 1) < 0) { @@ -424,6 +422,7 @@ qemuMonitorTestAddItem(qemuMonitorTestPtr test, no_memory: virReportOOMError(); +error: qemuMonitorTestItemFree(item); return -1; } @@ -467,8 +466,8 @@ qemuMonitorTestPtr qemuMonitorTestNew(bool json, virDomainXMLOptionPtr xmlopt) return NULL; } - if (!(tmpdir_template = strdup("/tmp/libvirt_XXXXXX"))) - goto no_memory; + if (VIR_STRDUP(tmpdir_template, "/tmp/libvirt_XXXXXX") < 0) + goto error; if (!(test->tmpdir = mkdtemp(tmpdir_template))) { virReportSystemError(errno, "%s", diff --git a/tests/qemuxml2argvtest.c b/tests/qemuxml2argvtest.c index 1286273..7c86af3 100644 --- a/tests/qemuxml2argvtest.c +++ b/tests/qemuxml2argvtest.c @@ -23,6 +23,8 @@ # include "testutilsqemu.h" +# define VIR_FROM_THIS VIR_FROM_QEMU + static const char *abs_top_srcdir; static virQEMUDriver driver; @@ -32,10 +34,9 @@ fakeSecretGetValue(virSecretPtr obj ATTRIBUTE_UNUSED, unsigned int fakeflags ATTRIBUTE_UNUSED, unsigned int internalFlags ATTRIBUTE_UNUSED) { - char *secret = strdup("AQCVn5hO6HzFAhAAq0NCv8jtJcIcE+HOBlMQ1A"); - if (!secret) { + char *secret; + if (VIR_STRDUP(secret, "AQCVn5hO6HzFAhAAq0NCv8jtJcIcE+HOBlMQ1A") < 0) return NULL; - } *value_size = strlen(secret); return (unsigned char *) secret; } @@ -129,7 +130,7 @@ static int testCompareXMLToArgvFiles(const char *xml, if (STREQ(vmdef->os.machine, "pc") && STREQ(vmdef->emulator, "/usr/bin/qemu-system-x86_64")) { VIR_FREE(vmdef->os.machine); - if (!(vmdef->os.machine = strdup("pc-0.11"))) + if (VIR_STRDUP(vmdef->os.machine, "pc-0.11") < 0) goto out; } @@ -288,10 +289,10 @@ mymain(void) VIR_FREE(driver.config->vncListen); VIR_FREE(driver.config->vncTLSx509certdir); - if ((driver.config->vncTLSx509certdir = strdup("/etc/pki/libvirt-vnc")) == NULL) + if (VIR_STRDUP_QUIET(driver.config->vncTLSx509certdir, "/etc/pki/libvirt-vnc") < 0) return EXIT_FAILURE; VIR_FREE(driver.config->spiceTLSx509certdir); - if ((driver.config->spiceTLSx509certdir = strdup("/etc/pki/libvirt-spice")) == NULL) + if (VIR_STRDUP_QUIET(driver.config->spiceTLSx509certdir, "/etc/pki/libvirt-spice") < 0) return EXIT_FAILURE; if ((driver.caps = testQemuCapsInit()) == NULL) @@ -299,16 +300,16 @@ mymain(void) if (!(driver.xmlopt = virQEMUDriverCreateXMLConf(&driver))) return EXIT_FAILURE; VIR_FREE(driver.config->stateDir); - if ((driver.config->stateDir = strdup("/nowhere")) == NULL) + if (VIR_STRDUP_QUIET(driver.config->stateDir, "/nowhere") < 0) return EXIT_FAILURE; VIR_FREE(driver.config->hugetlbfsMount); - if ((driver.config->hugetlbfsMount = strdup("/dev/hugepages")) == NULL) + if (VIR_STRDUP_QUIET(driver.config->hugetlbfsMount, "/dev/hugepages") < 0) return EXIT_FAILURE; VIR_FREE(driver.config->hugepagePath); - if ((driver.config->hugepagePath = strdup("/dev/hugepages/libvirt/qemu")) == NULL) + if (VIR_STRDUP_QUIET(driver.config->hugepagePath, "/dev/hugepages/libvirt/qemu") < 0) return EXIT_FAILURE; driver.config->spiceTLS = 1; - if (!(driver.config->spicePassword = strdup("123456"))) + if (VIR_STRDUP(driver.config->spicePassword, "123456") < 0) return EXIT_FAILURE; if (virAsprintf(&map, "%s/src/cpu/cpu_map.xml", abs_top_srcdir) < 0 || cpuMapOverride(map) < 0) { @@ -601,7 +602,7 @@ mymain(void) driver.config->vncSASL = 1; VIR_FREE(driver.config->vncSASLdir); - driver.config->vncSASLdir = strdup("/root/.sasl2"); + ignore_value(VIR_STRDUP(driver.config->vncSASLdir, "/root/.sasl2")); DO_TEST("graphics-vnc-sasl", QEMU_CAPS_VNC, QEMU_CAPS_VGA); driver.config->vncTLS = 1; driver.config->vncTLSx509verify = 1; diff --git a/tests/qemuxmlnstest.c b/tests/qemuxmlnstest.c index cd493e3..952b8e2 100644 --- a/tests/qemuxmlnstest.c +++ b/tests/qemuxmlnstest.c @@ -21,6 +21,8 @@ # include "testutilsqemu.h" # include "virstring.h" +# define VIR_FROM_THIS VIR_FROM_QEMU + static const char *abs_top_srcdir; static virQEMUDriver driver; @@ -68,7 +70,7 @@ static int testCompareXMLToArgvFiles(const char *xml, * detects such paths, strips the extra '/' and makes the path absolute. */ if (vmdef->emulator && STRPREFIX(vmdef->emulator, "/.")) { - if (!(emulator = strdup(vmdef->emulator + 1))) + if (VIR_STRDUP(emulator, vmdef->emulator + 1) < 0) goto fail; VIR_FREE(vmdef->emulator); vmdef->emulator = NULL; diff --git a/tests/securityselinuxhelper.c b/tests/securityselinuxhelper.c index 647b841..a82ca6d 100644 --- a/tests/securityselinuxhelper.c +++ b/tests/securityselinuxhelper.c @@ -28,6 +28,7 @@ # include <attr/xattr.h> #endif +#include "virstring.h" /* * The kernel policy will not allow us to arbitrarily change @@ -43,9 +44,7 @@ int getcon_raw(security_context_t *context) errno = EINVAL; return -1; } - if (!(*context = strdup(getenv("FAKE_CONTEXT")))) - return -1; - return 0; + return VIR_STRDUP_QUIET(*context, getenv("FAKE_CONTEXT")); } int getcon(security_context_t *context) @@ -65,9 +64,7 @@ int getpidcon_raw(pid_t pid, security_context_t *context) errno = EINVAL; return -1; } - if (!(*context = strdup(getenv("FAKE_CONTEXT")))) - return -1; - return 0; + return VIR_STRDUP_QUIET(*context, getenv("FAKE_CONTEXT")); } int getpidcon(pid_t pid, security_context_t *context) diff --git a/tests/securityselinuxlabeltest.c b/tests/securityselinuxlabeltest.c index e270a76..275ca93 100644 --- a/tests/securityselinuxlabeltest.c +++ b/tests/securityselinuxlabeltest.c @@ -116,10 +116,9 @@ testSELinuxLoadFileList(const char *testname, goto cleanup; } if (*tmp != '\0' && *tmp != '\n') { - if (!(context = strdup(tmp))) { + if (VIR_STRDUP(context, tmp) < 0) { VIR_FREE(line); VIR_FREE(file); - virReportOOMError(); goto cleanup; } diff --git a/tests/securityselinuxtest.c b/tests/securityselinuxtest.c index dd4cd11..0d56769 100644 --- a/tests/securityselinuxtest.c +++ b/tests/securityselinuxtest.c @@ -81,17 +81,18 @@ testBuildDomainDef(bool dynamic, def->seclabels[0]->type = dynamic ? VIR_DOMAIN_SECLABEL_DYNAMIC : VIR_DOMAIN_SECLABEL_STATIC; if (label && - !(def->seclabels[0]->label = strdup(label))) - goto no_memory; + VIR_STRDUP(def->seclabels[0]->label, label) < 0) + goto error; if (baselabel && - !(def->seclabels[0]->baselabel = strdup(baselabel))) - goto no_memory; + VIR_STRDUP(def->seclabels[0]->baselabel, baselabel) < 0) + goto error; return def; no_memory: virReportOOMError(); +error: virDomainDefFree(def); return NULL; } diff --git a/tests/storagebackendsheepdogtest.c b/tests/storagebackendsheepdogtest.c index 9b43a6d..39b2299 100644 --- a/tests/storagebackendsheepdogtest.c +++ b/tests/storagebackendsheepdogtest.c @@ -57,8 +57,7 @@ test_node_info_parser(collie_test test, char *poolxml) if (!(pool = virStoragePoolDefParseString(poolXmlData))) goto cleanup; - output = strdup(test.output); - if (!output) + if (VIR_STRDUP(output, test.output) < 0) goto cleanup; if (virStorageBackendSheepdogParseNodeInfo(pool, output) != @@ -102,8 +101,7 @@ test_vdi_list_parser(collie_test test, char *poolxml, char *volxml) if (!(vol = virStorageVolDefParseString(pool, volXmlData))) goto cleanup; - output = strdup(test.output); - if (!output) + if (VIR_STRDUP(output, test.output) < 0) goto cleanup; if (virStorageBackendSheepdogParseVdiList(vol, output) != diff --git a/tests/testutils.c b/tests/testutils.c index b0806de..222c016 100644 --- a/tests/testutils.c +++ b/tests/testutils.c @@ -512,7 +512,9 @@ virtTestLogContentAndReset(void) if (virBufferError(&testLog.buf)) return NULL; ret = virBufferContentAndReset(&testLog.buf); - return ret ? ret : strdup(""); + if (!ret) + ignore_value(VIR_STRDUP(ret, "")); + return ret; } #if TEST_OOM_TRACE diff --git a/tests/testutilsqemu.c b/tests/testutilsqemu.c index fba17a3..45ca6fe 100644 --- a/tests/testutilsqemu.c +++ b/tests/testutilsqemu.c @@ -8,6 +8,9 @@ # include "cpu_conf.h" # include "qemu/qemu_driver.h" # include "qemu/qemu_domain.h" +# include "virstring.h" + +# define VIR_FROM_THIS VIR_FROM_QEMU static virCapsGuestMachinePtr *testQemuAllocMachines(int *nmachines) { @@ -38,7 +41,7 @@ static virCapsGuestMachinePtr *testQemuAllocNewerMachines(int *nmachines) "pc-0.11", "pc", "pc-0.10", "isapc" }; - if ((canonical = strdup(x86_machines[0])) == NULL) + if (VIR_STRDUP(canonical, x86_machines[0]) < 0) return NULL; machines = virCapabilitiesAllocMachines(x86_machines, diff --git a/tests/vircgrouptest.c b/tests/vircgrouptest.c index 4777fae..75acfcb 100644 --- a/tests/vircgrouptest.c +++ b/tests/vircgrouptest.c @@ -501,7 +501,7 @@ mymain(void) int ret = 0; char *fakesysfsdir; - if (!(fakesysfsdir = strdup(FAKESYSFSDIRTEMPLATE))) { + if (VIR_STRDUP_QUIET(fakesysfsdir, FAKESYSFSDIRTEMPLATE) < 0) { fprintf(stderr, "Out of memory\n"); abort(); } diff --git a/tests/virnetmessagetest.c b/tests/virnetmessagetest.c index 96defe4..7e81ef0 100644 --- a/tests/virnetmessagetest.c +++ b/tests/virnetmessagetest.c @@ -27,7 +27,7 @@ #include "virerror.h" #include "viralloc.h" #include "virlog.h" - +#include "virstring.h" #include "rpc/virnetmessage.h" #define VIR_FROM_THIS VIR_FROM_RPC @@ -236,18 +236,15 @@ static int testMessagePayloadEncode(const void *args ATTRIBUTE_UNUSED) err.domain = VIR_FROM_RPC; err.level = VIR_ERR_ERROR; - if (VIR_ALLOC(err.message) < 0) - goto cleanup; - *err.message = strdup("Hello World"); - if (VIR_ALLOC(err.str1) < 0) - goto cleanup; - *err.str1 = strdup("One"); - if (VIR_ALLOC(err.str2) < 0) - goto cleanup; - *err.str2 = strdup("Two"); - if (VIR_ALLOC(err.str3) < 0) + if (VIR_ALLOC(err.message) < 0 || + VIR_STRDUP(*err.message, "Hello World") < 0 || + VIR_ALLOC(err.str1) < 0 || + VIR_STRDUP(*err.str1, "One") < 0 || + VIR_ALLOC(err.str2) < 0 || + VIR_STRDUP(*err.str2, "Two") < 0 || + VIR_ALLOC(err.str3) < 0 || + VIR_STRDUP(*err.str3, "Three") < 0) goto cleanup; - *err.str3 = strdup("Three"); err.int1 = 1; err.int2 = 2; diff --git a/tests/vmx2xmltest.c b/tests/vmx2xmltest.c index bd7cbc6..c9616de 100644 --- a/tests/vmx2xmltest.c +++ b/tests/vmx2xmltest.c @@ -13,6 +13,8 @@ # include "vmx/vmx.h" # include "virstring.h" +# define VIR_FROM_THIS VIR_FROM_VMWARE + static virCapsPtr caps; static virDomainXMLOptionPtr xmlopt; static virVMXContext ctx; @@ -159,11 +161,8 @@ testParseVMXFileName(const char *fileName, void *opaque ATTRIBUTE_UNUSED) if (STRPREFIX(fileName, "/vmfs/volumes/")) { /* Found absolute path referencing a file inside a datastore */ - copyOfFileName = strdup(fileName); - - if (copyOfFileName == NULL) { + if (VIR_STRDUP(copyOfFileName, fileName) < 0) goto cleanup; - } /* Expected format: '/vmfs/volumes/<datastore>/<path>' */ if ((tmp = STRSKIP(copyOfFileName, "/vmfs/volumes/")) == NULL || @@ -177,7 +176,7 @@ testParseVMXFileName(const char *fileName, void *opaque ATTRIBUTE_UNUSED) goto cleanup; } else if (STRPREFIX(fileName, "/")) { /* Found absolute path referencing a file outside a datastore */ - src = strdup(fileName); + ignore_value(VIR_STRDUP(src, fileName)); } else if (strchr(fileName, '/') != NULL) { /* Found relative path, this is not supported */ src = NULL; diff --git a/tests/xml2vmxtest.c b/tests/xml2vmxtest.c index 38b5a4d..0dffebd 100644 --- a/tests/xml2vmxtest.c +++ b/tests/xml2vmxtest.c @@ -13,6 +13,8 @@ # include "vmx/vmx.h" # include "virstring.h" +# define VIR_FROM_THIS VIR_FROM_VMWARE + static virCapsPtr caps; static virVMXContext ctx; static virDomainXMLOptionPtr xmlopt; @@ -169,11 +171,8 @@ testFormatVMXFileName(const char *src, void *opaque ATTRIBUTE_UNUSED) if (STRPREFIX(src, "[")) { /* Found potential datastore path */ - copyOfDatastorePath = strdup(src); - - if (copyOfDatastorePath == NULL) { + if (VIR_STRDUP(copyOfDatastorePath, src) < 0) goto cleanup; - } /* Expected format: '[<datastore>] <path>' where <path> is optional */ if ((tmp = STRSKIP(copyOfDatastorePath, "[")) == NULL || *tmp == ']' || @@ -194,7 +193,7 @@ testFormatVMXFileName(const char *src, void *opaque ATTRIBUTE_UNUSED) goto cleanup; } else if (STRPREFIX(src, "/")) { /* Found absolute path */ - absolutePath = strdup(src); + ignore_value(VIR_STRDUP(absolutePath, src)); } else { /* Found relative path, this is not supported */ goto cleanup; -- 1.8.1.5

On 05/03/2013 04:53 PM, Michal Privoznik wrote:
--- tests/commandhelper.c | 10 ++++++++-- tests/commandtest.c | 2 +- tests/openvzutilstest.c | 6 ++++-- tests/qemumonitortestutils.c | 15 +++++++-------- tests/qemuxml2argvtest.c | 23 ++++++++++++----------- tests/qemuxmlnstest.c | 4 +++- tests/securityselinuxhelper.c | 9 +++------ tests/securityselinuxlabeltest.c | 3 +-- tests/securityselinuxtest.c | 9 +++++---- tests/storagebackendsheepdogtest.c | 6 ++---- tests/testutils.c | 4 +++- tests/testutilsqemu.c | 5 ++++- tests/vircgrouptest.c | 2 +- tests/virnetmessagetest.c | 21 +++++++++------------ tests/vmx2xmltest.c | 9 ++++----- tests/xml2vmxtest.c | 9 ++++----- 16 files changed, 71 insertions(+), 66 deletions(-)
diff --git a/tests/commandhelper.c b/tests/commandhelper.c index 92f031f..1be5d66 100644 --- a/tests/commandhelper.c +++ b/tests/commandhelper.c @@ -31,6 +31,9 @@ #include "viralloc.h" #include "virfile.h" #include "testutils.h" +#include "virstring.h" + +#define VIR_FROM_THIS VIR_FROM_NONE
#ifndef WIN32
@@ -42,8 +45,11 @@ static int envsort(const void *a, const void *b) { const char *bstr = *bstrptr; char *aeq = strchr(astr, '='); char *beq = strchr(bstr, '='); - char *akey = strndup(astr, aeq - astr); - char *bkey = strndup(bstr, beq - bstr); + char *akey; + char *bkey; + if (VIR_STRNDUP(akey, astr, aeq - astr) < 0 || + VIR_STRNDUP(bkey, bstr, beq - bstr) < 0) + return -1; int ret = strcmp(akey, bkey); VIR_FREE(akey); VIR_FREE(bkey);
This is used as a comparison function for qsort, returning -1 doesn't mean an error. I'd suggest ignore_value(VIR_STRNDUP_QUIET()) instead, and dropping the #define.
diff --git a/tests/qemuxml2argvtest.c b/tests/qemuxml2argvtest.c index 1286273..7c86af3 100644 --- a/tests/qemuxml2argvtest.c +++ b/tests/qemuxml2argvtest.c @@ -288,10 +289,10 @@ mymain(void) VIR_FREE(driver.config->vncListen);
VIR_FREE(driver.config->vncTLSx509certdir); - if ((driver.config->vncTLSx509certdir = strdup("/etc/pki/libvirt-vnc")) == NULL) + if (VIR_STRDUP_QUIET(driver.config->vncTLSx509certdir, "/etc/pki/libvirt-vnc") < 0) return EXIT_FAILURE; VIR_FREE(driver.config->spiceTLSx509certdir); - if ((driver.config->spiceTLSx509certdir = strdup("/etc/pki/libvirt-spice")) == NULL) + if (VIR_STRDUP_QUIET(driver.config->spiceTLSx509certdir, "/etc/pki/libvirt-spice") < 0) return EXIT_FAILURE;
if ((driver.caps = testQemuCapsInit()) == NULL) @@ -299,16 +300,16 @@ mymain(void) if (!(driver.xmlopt = virQEMUDriverCreateXMLConf(&driver))) return EXIT_FAILURE; VIR_FREE(driver.config->stateDir); - if ((driver.config->stateDir = strdup("/nowhere")) == NULL) + if (VIR_STRDUP_QUIET(driver.config->stateDir, "/nowhere") < 0) return EXIT_FAILURE; VIR_FREE(driver.config->hugetlbfsMount); - if ((driver.config->hugetlbfsMount = strdup("/dev/hugepages")) == NULL) + if (VIR_STRDUP_QUIET(driver.config->hugetlbfsMount, "/dev/hugepages") < 0) return EXIT_FAILURE; VIR_FREE(driver.config->hugepagePath); - if ((driver.config->hugepagePath = strdup("/dev/hugepages/libvirt/qemu")) == NULL) + if (VIR_STRDUP_QUIET(driver.config->hugepagePath, "/dev/hugepages/libvirt/qemu") < 0) return EXIT_FAILURE; driver.config->spiceTLS = 1; - if (!(driver.config->spicePassword = strdup("123456"))) + if (VIR_STRDUP(driver.config->spicePassword, "123456") < 0)
VIR_STRDUP_QUIET
return EXIT_FAILURE; if (virAsprintf(&map, "%s/src/cpu/cpu_map.xml", abs_top_srcdir) < 0 || cpuMapOverride(map) < 0) {
ACK Jan

--- src/datatypes.c | 76 +++++++++++++++++++++++++++------------------------------ src/libvirt.c | 14 +++-------- src/nodeinfo.c | 5 +--- 3 files changed, 41 insertions(+), 54 deletions(-) diff --git a/src/datatypes.c b/src/datatypes.c index d3cf5f2..41e9c57 100644 --- a/src/datatypes.c +++ b/src/datatypes.c @@ -27,6 +27,7 @@ #include "virlog.h" #include "viralloc.h" #include "viruuid.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_NONE @@ -225,8 +226,8 @@ virGetDomain(virConnectPtr conn, const char *name, const unsigned char *uuid) if (!(ret = virObjectNew(virDomainClass))) return NULL; - if (!(ret->name = strdup(name))) - goto no_memory; + if (VIR_STRDUP(ret->name, name) < 0) + goto error; ret->conn = virObjectRef(conn); ret->id = -1; @@ -234,8 +235,7 @@ virGetDomain(virConnectPtr conn, const char *name, const unsigned char *uuid) return ret; -no_memory: - virReportOOMError(); +error: virObjectUnref(ret); return NULL; } @@ -297,15 +297,15 @@ virGetNetwork(virConnectPtr conn, const char *name, const unsigned char *uuid) if (!(ret = virObjectNew(virNetworkClass))) return NULL; - if (!(ret->name = strdup(name))) - goto no_memory; + if (VIR_STRDUP(ret->name, name) < 0) + goto error; ret->conn = virObjectRef(conn); memcpy(&(ret->uuid[0]), uuid, VIR_UUID_BUFLEN); return ret; -no_memory: +error: virReportOOMError(); virObjectUnref(ret); return NULL; @@ -372,16 +372,15 @@ virGetInterface(virConnectPtr conn, const char *name, const char *mac) if (!(ret = virObjectNew(virInterfaceClass))) return NULL; - if (!(ret->name = strdup(name))) - goto no_memory; - if (!(ret->mac = strdup(mac))) - goto no_memory; + if (VIR_STRDUP(ret->name, name) < 0 || + VIR_STRDUP(ret->mac, mac) < 0) + goto error; ret->conn = virObjectRef(conn); return ret; -no_memory: +error: virReportOOMError(); virObjectUnref(ret); return NULL; @@ -446,8 +445,8 @@ virGetStoragePool(virConnectPtr conn, const char *name, if (!(ret = virObjectNew(virStoragePoolClass))) return NULL; - if (!(ret->name = strdup(name))) - goto no_memory; + if (VIR_STRDUP(ret->name, name) < 0) + goto error; ret->conn = virObjectRef(conn); memcpy(&(ret->uuid[0]), uuid, VIR_UUID_BUFLEN); @@ -458,8 +457,7 @@ virGetStoragePool(virConnectPtr conn, const char *name, return ret; -no_memory: - virReportOOMError(); +error: virObjectUnref(ret); return NULL; } @@ -530,12 +528,10 @@ virGetStorageVol(virConnectPtr conn, const char *pool, const char *name, if (!(ret = virObjectNew(virStorageVolClass))) return NULL; - if (!(ret->pool = strdup(pool))) - goto no_memory; - if (!(ret->name = strdup(name))) - goto no_memory; - if (!(ret->key = strdup(key))) - goto no_memory; + if (VIR_STRDUP(ret->pool, pool) < 0 || + VIR_STRDUP(ret->name, name) < 0 || + VIR_STRDUP(ret->key, key) < 0) + goto error; ret->conn = virObjectRef(conn); @@ -545,8 +541,7 @@ virGetStorageVol(virConnectPtr conn, const char *pool, const char *name, return ret; -no_memory: - virReportOOMError(); +error: virObjectUnref(ret); return NULL; } @@ -610,13 +605,13 @@ virGetNodeDevice(virConnectPtr conn, const char *name) if (!(ret = virObjectNew(virNodeDeviceClass))) return NULL; - if (!(ret->name = strdup(name))) - goto no_memory; + if (VIR_STRDUP(ret->name, name) < 0) + goto error; ret->conn = virObjectRef(conn); return ret; -no_memory: - virReportOOMError(); + +error: virObjectUnref(ret); return NULL; } @@ -680,14 +675,14 @@ virGetSecret(virConnectPtr conn, const unsigned char *uuid, memcpy(&(ret->uuid[0]), uuid, VIR_UUID_BUFLEN); ret->usageType = usageType; - if (!(ret->usageID = strdup(usageID))) - goto no_memory; + if (VIR_STRDUP(ret->usageID, usageID) < 0) + goto error; ret->conn = virObjectRef(conn); return ret; -no_memory: - virReportOOMError(); + +error: virObjectUnref(ret); return NULL; } @@ -775,16 +770,16 @@ virGetNWFilter(virConnectPtr conn, const char *name, if (!(ret = virObjectNew(virNWFilterClass))) return NULL; - if (!(ret->name = strdup(name))) - goto no_memory; + if (VIR_STRDUP(ret->name, name) < 0) + goto error; memcpy(&(ret->uuid[0]), uuid, VIR_UUID_BUFLEN); ret->conn = virObjectRef(conn); return ret; -no_memory: - virReportOOMError(); + +error: virObjectUnref(ret); return NULL; } @@ -832,13 +827,14 @@ virGetDomainSnapshot(virDomainPtr domain, const char *name) if (!(ret = virObjectNew(virDomainSnapshotClass))) return NULL; - if (!(ret->name = strdup(name))) - goto no_memory; + if (VIR_STRDUP(ret->name, name) < 0) + goto cleanup; + ret->domain = virObjectRef(domain); return ret; -no_memory: - virReportOOMError(); + +cleanup: virObjectUnref(ret); return NULL; } diff --git a/src/libvirt.c b/src/libvirt.c index 467f6dd..5007971 100644 --- a/src/libvirt.c +++ b/src/libvirt.c @@ -213,11 +213,9 @@ static int virConnectAuthCallbackDefault(virConnectCredentialPtr cred, } if (cred[i].type != VIR_CRED_EXTERNAL) { - if (STREQ(bufptr, "") && cred[i].defresult) - cred[i].result = strdup(cred[i].defresult); - else - cred[i].result = strdup(bufptr); - if (!cred[i].result) + if (VIR_STRDUP(cred[i].result, + STREQ(bufptr, "") && cred[i].defresult ? + cred[i].defresult : bufptr) < 0) return -1; cred[i].resultlen = strlen(cred[i].result); } @@ -1046,11 +1044,7 @@ virConnectOpenFindURIAliasMatch(virConfValuePtr value, const char *alias, char * STREQLEN(entry->str, alias, alias_len)) { VIR_DEBUG("Resolved alias '%s' to '%s'", alias, offset+1); - if (!(*uri = strdup(offset+1))) { - virReportOOMError(); - return -1; - } - return 0; + return VIR_STRDUP(*uri, offset+1); } entry = entry->next; diff --git a/src/nodeinfo.c b/src/nodeinfo.c index 95c2f33..ca28452 100644 --- a/src/nodeinfo.c +++ b/src/nodeinfo.c @@ -984,11 +984,8 @@ int nodeGetMemoryStats(virConnectPtr conn ATTRIBUTE_UNUSED, FILE *meminfo; if (cellNum == VIR_NODE_MEMORY_STATS_ALL_CELLS) { - meminfo_path = strdup(MEMINFO_PATH); - if (!meminfo_path) { - virReportOOMError(); + if (VIR_STRDUP(meminfo_path, MEMINFO_PATH) < 0) return -1; - } } else { # if WITH_NUMACTL if (numa_available() < 0) { -- 1.8.1.5

On 05/03/2013 04:53 PM, Michal Privoznik wrote:
--- src/datatypes.c | 76 +++++++++++++++++++++++++++------------------------------ src/libvirt.c | 14 +++-------- src/nodeinfo.c | 5 +--- 3 files changed, 41 insertions(+), 54 deletions(-)
@@ -297,15 +297,15 @@ virGetNetwork(virConnectPtr conn, const char *name, const unsigned char *uuid) if (!(ret = virObjectNew(virNetworkClass))) return NULL;
- if (!(ret->name = strdup(name))) - goto no_memory; + if (VIR_STRDUP(ret->name, name) < 0) + goto error;
ret->conn = virObjectRef(conn); memcpy(&(ret->uuid[0]), uuid, VIR_UUID_BUFLEN);
return ret;
-no_memory: +error: virReportOOMError(); virObjectUnref(ret); return NULL; @@ -372,16 +372,15 @@ virGetInterface(virConnectPtr conn, const char *name, const char *mac) if (!(ret = virObjectNew(virInterfaceClass))) return NULL;
- if (!(ret->name = strdup(name))) - goto no_memory; - if (!(ret->mac = strdup(mac))) - goto no_memory; + if (VIR_STRDUP(ret->name, name) < 0 || + VIR_STRDUP(ret->mac, mac) < 0) + goto error;
ret->conn = virObjectRef(conn);
return ret;
-no_memory: +error: virReportOOMError(); virObjectUnref(ret); return NULL;
Duplicate virReportOOMError in these two hunks.
@@ -530,12 +528,10 @@ virGetStorageVol(virConnectPtr conn, const char *pool, const char *name, if (!(ret = virObjectNew(virStorageVolClass))) return NULL;
- if (!(ret->pool = strdup(pool))) - goto no_memory; - if (!(ret->name = strdup(name))) - goto no_memory; - if (!(ret->key = strdup(key))) - goto no_memory; + if (VIR_STRDUP(ret->pool, pool) < 0 || + VIR_STRDUP(ret->name, name) < 0 || + VIR_STRDUP(ret->key, key) < 0) + goto error;
ret->conn = virObjectRef(conn);
VIR_STRDUP accepts NULL now, you should check if pool is non-null as well.
diff --git a/src/libvirt.c b/src/libvirt.c index 467f6dd..5007971 100644 --- a/src/libvirt.c +++ b/src/libvirt.c @@ -213,11 +213,9 @@ static int virConnectAuthCallbackDefault(virConnectCredentialPtr cred, }
if (cred[i].type != VIR_CRED_EXTERNAL) { - if (STREQ(bufptr, "") && cred[i].defresult) - cred[i].result = strdup(cred[i].defresult); - else - cred[i].result = strdup(bufptr); - if (!cred[i].result) + if (VIR_STRDUP(cred[i].result, + STREQ(bufptr, "") && cred[i].defresult ? + cred[i].defresult : bufptr) < 0) return -1; cred[i].resultlen = strlen(cred[i].result); }
This function doesn't report any errors. But it's an improvement to report an extra message than crash on OOM. ACK Jan

On 10.05.2013 09:57, Ján Tomko wrote:
On 05/03/2013 04:53 PM, Michal Privoznik wrote:
--- src/datatypes.c | 76 +++++++++++++++++++++++++++------------------------------ src/libvirt.c | 14 +++-------- src/nodeinfo.c | 5 +--- 3 files changed, 41 insertions(+), 54 deletions(-)
@@ -530,12 +528,10 @@ virGetStorageVol(virConnectPtr conn, const char *pool, const char *name, if (!(ret = virObjectNew(virStorageVolClass))) return NULL;
- if (!(ret->pool = strdup(pool))) - goto no_memory; - if (!(ret->name = strdup(name))) - goto no_memory; - if (!(ret->key = strdup(key))) - goto no_memory; + if (VIR_STRDUP(ret->pool, pool) < 0 || + VIR_STRDUP(ret->name, name) < 0 || + VIR_STRDUP(ret->key, key) < 0) + goto error;
ret->conn = virObjectRef(conn);
VIR_STRDUP accepts NULL now, you should check if pool is non-null as well.
Yeah, we should add: --- a/src/datatypes.c +++ b/src/datatypes.c @@ -520,6 +520,7 @@ virGetStorageVol(virConnectPtr conn, const char *pool, const char *name, virLibConnError(VIR_ERR_INVALID_CONN, "%s", _("no connection")); return NULL; } + virCheckNonNullArgReturn(pool, NULL); virCheckNonNullArgReturn(name, NULL); virCheckNonNullArgReturn(key, NULL); But I think that deserves a separate patch.
ACK
Jan

--- cfg.mk | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/cfg.mk b/cfg.mk index 1d63bbd..4ed2c3a 100644 --- a/cfg.mk +++ b/cfg.mk @@ -387,6 +387,11 @@ sc_prohibit_asprintf: halt='use strdup instead of virAsprintf with "%s"' \ $(_sc_search_regexp) +sc_prohibit_strdup: + @prohibit='\<strn?dup\> *\(' \ + halt='use VIR_STRUP, not strdup' \ + $(_sc_search_regexp) + # Prefer virSetUIDGID. sc_prohibit_setuid: @prohibit='\<set(re)?[ug]id\> *\(' \ @@ -864,6 +869,9 @@ exclude_file_name_regexp--sc_prohibit_always_true_header_tests = \ exclude_file_name_regexp--sc_prohibit_asprintf = \ ^(bootstrap.conf$$|src/util/virstring\.c$$|examples/domain-events/events-c/event-test\.c$$|tests/vircgroupmock\.c$$) +exclude_file_name_regexp--sc_prohibit_strdup = \ + ^(docs/|examples/|python/|src/util/virstring\.c$$|tools/virsh\.c$$) + exclude_file_name_regexp--sc_prohibit_close = \ (\.p[yl]$$|^docs/|^(src/util/virfile\.c|src/libvirt\.c|tests/vircgroupmock\.c)$$) -- 1.8.1.5

On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- cfg.mk | 8 ++++++++ 1 file changed, 8 insertions(+)
diff --git a/cfg.mk b/cfg.mk index 1d63bbd..4ed2c3a 100644 --- a/cfg.mk +++ b/cfg.mk @@ -387,6 +387,11 @@ sc_prohibit_asprintf: halt='use strdup instead of virAsprintf with "%s"' \ $(_sc_search_regexp)
+sc_prohibit_strdup: + @prohibit='\<strn?dup\> *\(' \ + halt='use VIR_STRUP, not strdup' \
s/VIR_STRUP/VIR_STRDUP/
+ $(_sc_search_regexp) + # Prefer virSetUIDGID. sc_prohibit_setuid: @prohibit='\<set(re)?[ug]id\> *\(' \ @@ -864,6 +869,9 @@ exclude_file_name_regexp--sc_prohibit_always_true_header_tests = \ exclude_file_name_regexp--sc_prohibit_asprintf = \ ^(bootstrap.conf$$|src/util/virstring\.c$$|examples/domain-events/events-c/event-test\.c$$|tests/vircgroupmock\.c$$)
+exclude_file_name_regexp--sc_prohibit_strdup = \ + ^(docs/|examples/|python/|src/util/virstring\.c$$|tools/virsh\.c$$)
Do we really need to allow strdup() in the python c code? Likewise for tools/virsh.c? There will probably be more places to touch up before you finally commit this, given other activity in the tree in the meantime :) -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On 07.05.2013 05:54, Eric Blake wrote:
On 05/03/2013 08:53 AM, Michal Privoznik wrote:
--- cfg.mk | 8 ++++++++ 1 file changed, 8 insertions(+)
diff --git a/cfg.mk b/cfg.mk index 1d63bbd..4ed2c3a 100644 --- a/cfg.mk +++ b/cfg.mk @@ -387,6 +387,11 @@ sc_prohibit_asprintf: halt='use strdup instead of virAsprintf with "%s"' \ $(_sc_search_regexp)
+sc_prohibit_strdup: + @prohibit='\<strn?dup\> *\(' \ + halt='use VIR_STRUP, not strdup' \
s/VIR_STRUP/VIR_STRDUP/
+ $(_sc_search_regexp) + # Prefer virSetUIDGID. sc_prohibit_setuid: @prohibit='\<set(re)?[ug]id\> *\(' \ @@ -864,6 +869,9 @@ exclude_file_name_regexp--sc_prohibit_always_true_header_tests = \ exclude_file_name_regexp--sc_prohibit_asprintf = \ ^(bootstrap.conf$$|src/util/virstring\.c$$|examples/domain-events/events-c/event-test\.c$$|tests/vircgroupmock\.c$$)
+exclude_file_name_regexp--sc_prohibit_strdup = \ + ^(docs/|examples/|python/|src/util/virstring\.c$$|tools/virsh\.c$$)
Do we really need to allow strdup() in the python c code? Likewise for tools/virsh.c?
Do you mean we should s/strdup/VIR_STRDUP/ within vshStrdup? And I'll fix python surely. Michal

On 05/09/2013 04:39 AM, Michal Privoznik wrote:
+exclude_file_name_regexp--sc_prohibit_strdup = \ + ^(docs/|examples/|python/|src/util/virstring\.c$$|tools/virsh\.c$$)
Do we really need to allow strdup() in the python c code? Likewise for tools/virsh.c?
Do you mean we should s/strdup/VIR_STRDUP/ within vshStrdup?
Might as well - it never hurts to be consistent in as many places as possible.
And I'll fix python surely.
Michal
-- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On 03.05.2013 16:53, Michal Privoznik wrote:
Previously this aimed on dropping OOM report from almost everywhere (v1), then just prepare the ground (v2). Now, it just aims on introducing VIR_STRDUP and VIR_STRNDUP which do report OOM error. This will cause rebase conflicts, for sure. Sorry.
Patches available at: git://gitorious.org/~zippy2/libvirt/michal-staging.git branch oom4
Michal Privoznik (34): virstring: Introduce VIR_STRDUP and VIR_STRNDUP Adapt to VIR_STRDUP and VIR_STRNDUP in daemon/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/conf/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/cpu/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/esx/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/hyperv/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/libxl/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/locking/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/lxc/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/network/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/node_device/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/interface/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/nwfilter/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/openvz/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/parallels/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/phyp/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/qemu/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/remote/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/rpc/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/secret/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/security/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/storage/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/test/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/uml/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/util/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/vbox/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/vmware/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/vmx/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/xen/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/xenapi/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/xenxs/* Adapt to VIR_STRDUP and VIR_STRNDUP in tests/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/* Introduce syntax-check rule to prefer VIR_STRDUP over strdup
HACKING | 11 + cfg.mk | 8 + daemon/libvirtd-config.c | 50 ++-- daemon/libvirtd.c | 29 +-- daemon/remote.c | 161 +++++------- docs/hacking.html.in | 14 + include/libvirt/libvirt.h.in | 10 +- src/conf/capabilities.c | 30 +-- src/conf/cpu_conf.c | 19 +- src/conf/domain_conf.c | 105 +++----- src/conf/domain_event.c | 39 ++- src/conf/node_device_conf.c | 29 +-- src/conf/nwfilter_conf.c | 17 +- src/conf/nwfilter_params.c | 30 +-- src/conf/snapshot_conf.c | 11 +- src/conf/storage_conf.c | 13 +- src/conf/virchrdev.c | 12 +- src/cpu/cpu_generic.c | 8 +- src/cpu/cpu_map.c | 3 +- src/cpu/cpu_powerpc.c | 13 +- src/cpu/cpu_x86.c | 10 +- src/datatypes.c | 76 +++--- src/esx/esx_driver.c | 43 +-- src/esx/esx_interface_driver.c | 7 +- src/esx/esx_network_driver.c | 28 +- src/esx/esx_storage_backend_iscsi.c | 21 +- src/esx/esx_storage_backend_vmfs.c | 16 +- src/esx/esx_util.c | 45 +--- src/esx/esx_vi.c | 79 ++---- src/esx/esx_vi_types.c | 36 +-- src/hyperv/hyperv_driver.c | 50 +--- src/hyperv/hyperv_util.c | 18 +- src/interface/interface_backend_udev.c | 36 +-- src/libvirt.c | 14 +- src/libvirt_private.syms | 2 + src/libxl/libxl_conf.c | 86 ++---- src/libxl/libxl_driver.c | 14 +- src/locking/lock_daemon.c | 30 +-- src/locking/lock_daemon_config.c | 12 +- src/locking/lock_daemon_dispatch.c | 6 +- src/locking/lock_driver_lockd.c | 41 ++- src/locking/lock_driver_sanlock.c | 12 +- src/locking/lock_manager.c | 4 +- src/lxc/lxc_cgroup.c | 3 +- src/lxc/lxc_conf.c | 36 ++- src/lxc/lxc_container.c | 18 +- src/lxc/lxc_controller.c | 20 +- src/lxc/lxc_driver.c | 9 +- src/lxc/lxc_process.c | 7 +- src/network/bridge_driver.c | 34 +-- src/node_device/node_device_driver.c | 33 +-- src/node_device/node_device_hal.c | 13 +- src/node_device/node_device_udev.c | 99 ++----- src/nodeinfo.c | 5 +- src/nwfilter/nwfilter_dhcpsnoop.c | 22 +- src/nwfilter/nwfilter_driver.c | 7 +- src/nwfilter/nwfilter_ebiptables_driver.c | 2 +- src/nwfilter/nwfilter_gentech_driver.c | 5 +- src/nwfilter/nwfilter_learnipaddr.c | 5 +- src/openvz/openvz_conf.c | 45 ++-- src/openvz/openvz_driver.c | 39 ++- src/parallels/parallels_driver.c | 71 +++-- src/parallels/parallels_network.c | 23 +- src/parallels/parallels_storage.c | 62 ++--- src/phyp/phyp_driver.c | 50 +--- src/qemu/qemu_capabilities.c | 79 +++--- src/qemu/qemu_cgroup.c | 4 +- src/qemu/qemu_command.c | 419 ++++++++++++------------------ src/qemu/qemu_conf.c | 58 ++--- src/qemu/qemu_domain.c | 26 +- src/qemu/qemu_driver.c | 113 +++----- src/qemu/qemu_hotplug.c | 15 +- src/qemu/qemu_migration.c | 20 +- src/qemu/qemu_monitor_json.c | 63 ++--- src/qemu/qemu_monitor_text.c | 15 +- src/qemu/qemu_process.c | 64 ++--- src/remote/remote_driver.c | 116 ++++----- src/rpc/gendispatch.pl | 21 +- src/rpc/virnetclient.c | 16 +- src/rpc/virnetmessage.c | 12 +- src/rpc/virnetsaslcontext.c | 6 +- src/rpc/virnetserver.c | 6 +- src/rpc/virnetserverclient.c | 10 +- src/rpc/virnetservermdns.c | 6 +- src/rpc/virnetsocket.c | 10 +- src/rpc/virnetsshsession.c | 76 +++--- src/rpc/virnettlscontext.c | 26 +- src/secret/secret_driver.c | 5 +- src/security/security_apparmor.c | 20 +- src/security/security_dac.c | 23 +- src/security/security_nop.c | 7 +- src/security/security_selinux.c | 79 ++---- src/security/virt-aa-helper.c | 4 +- src/storage/parthelper.c | 5 +- src/storage/storage_backend.c | 22 +- src/storage/storage_backend_disk.c | 26 +- src/storage/storage_backend_fs.c | 34 +-- src/storage/storage_backend_iscsi.c | 17 +- src/storage/storage_backend_logical.c | 32 +-- src/storage/storage_backend_mpath.c | 5 +- src/storage/storage_backend_rbd.c | 5 +- src/storage/storage_backend_scsi.c | 19 +- src/storage/storage_backend_sheepdog.c | 6 +- src/storage/storage_driver.c | 18 +- src/test/test_driver.c | 144 ++++------ src/uml/uml_conf.c | 10 +- src/uml/uml_driver.c | 8 +- src/util/virauth.c | 17 +- src/util/virauthconfig.c | 8 +- src/util/virbitmap.c | 9 +- src/util/vircgroup.c | 36 ++- src/util/vircommand.c | 33 ++- src/util/virconf.c | 34 +-- src/util/virdnsmasq.c | 22 +- src/util/virebtables.c | 34 +-- src/util/virebtables.h | 2 +- src/util/virerror.c | 19 +- src/util/virhash.c | 5 +- src/util/viridentity.c | 15 +- src/util/virinitctl.c | 4 +- src/util/viriptables.c | 4 +- src/util/virjson.c | 18 +- src/util/virkeyfile.c | 13 +- src/util/virlockspace.c | 25 +- src/util/virlog.c | 25 +- src/util/virnetdevmacvlan.c | 16 +- src/util/virnetdevtap.c | 11 +- src/util/virnetdevvportprofile.c | 4 +- src/util/virobject.c | 16 +- src/util/virpci.c | 14 +- src/util/virsexpr.c | 37 +-- src/util/virsocketaddr.c | 9 +- src/util/virstoragefile.c | 18 +- src/util/virstring.c | 91 ++++++- src/util/virstring.h | 62 +++++ src/util/virsysinfo.c | 290 ++++++++------------- src/util/virtypedparam.c | 14 +- src/util/viruri.c | 58 ++--- src/util/virutil.c | 91 +++---- src/util/virxml.c | 5 +- src/vbox/vbox_XPCOMCGlue.c | 6 +- src/vbox/vbox_tmpl.c | 278 +++++++++----------- src/vmware/vmware_conf.c | 28 +- src/vmware/vmware_driver.c | 11 +- src/vmx/vmx.c | 36 +-- src/xen/block_stats.c | 16 +- src/xen/xen_driver.c | 9 +- src/xen/xen_hypervisor.c | 19 +- src/xen/xen_inotify.c | 15 +- src/xen/xend_internal.c | 78 ++---- src/xen/xm_internal.c | 9 +- src/xen/xs_internal.c | 44 ++-- src/xenapi/xenapi_driver.c | 59 ++--- src/xenapi/xenapi_utils.c | 39 +-- src/xenxs/xen_sxpr.c | 192 ++++++-------- src/xenxs/xen_xm.c | 94 +++---- tests/commandhelper.c | 10 +- tests/commandtest.c | 2 +- tests/openvzutilstest.c | 6 +- tests/qemumonitortestutils.c | 15 +- tests/qemuxml2argvtest.c | 23 +- tests/qemuxmlnstest.c | 4 +- tests/securityselinuxhelper.c | 9 +- tests/securityselinuxlabeltest.c | 3 +- tests/securityselinuxtest.c | 9 +- tests/storagebackendsheepdogtest.c | 6 +- tests/testutils.c | 4 +- tests/testutilsqemu.c | 5 +- tests/vircgrouptest.c | 2 +- tests/virnetmessagetest.c | 21 +- tests/vmx2xmltest.c | 9 +- tests/xml2vmxtest.c | 9 +- 172 files changed, 2204 insertions(+), 3501 deletions(-)
I've pushed some independent ACKed patches. Others, like 18/34 and 19/34 are ACKed, but require include/libvirt/libvirt.h.in changed made in yet unreviewed 17/34 so I hold the push until then. Michal
participants (6)
-
Daniel P. Berrange
-
Eric Blake
-
Ján Tomko
-
Martin Kletzander
-
Matthias Bolte
-
Michal Privoznik