[libvirt] [PATCH v4 00/13] 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 oom5 Michal Privoznik (13): Adapt to VIR_STRDUP and VIR_STRNDUP in src/conf/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/openvz/* Change virConnectDomainEventGraphicsCallback signature _virConnectCredential: turn @prompt into char * 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/security/* Adapt to VIR_STRDUP and VIR_STRNDUP in src/util/* 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/* Introduce syntax-check rule to prefer VIR_STRDUP over strdup cfg.mk | 8 + include/libvirt/libvirt.h.in | 16 +- src/conf/capabilities.c | 30 +-- src/conf/cpu_conf.c | 20 +- src/conf/domain_conf.c | 119 +++-------- src/conf/domain_event.c | 41 ++-- src/conf/node_device_conf.c | 28 ++- src/conf/nwfilter_conf.c | 17 +- src/conf/nwfilter_params.c | 34 +--- src/conf/snapshot_conf.c | 11 +- src/conf/storage_conf.c | 13 +- src/conf/virchrdev.c | 12 +- src/openvz/openvz_conf.c | 45 ++-- src/openvz/openvz_driver.c | 29 +-- src/qemu/qemu_capabilities.c | 79 +++----- src/qemu/qemu_cgroup.c | 4 +- src/qemu/qemu_command.c | 428 +++++++++++++++------------------------ src/qemu/qemu_conf.c | 64 +++--- src/qemu/qemu_domain.c | 26 +-- src/qemu/qemu_driver.c | 129 ++++-------- src/qemu/qemu_hotplug.c | 15 +- src/qemu/qemu_migration.c | 17 +- 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 | 27 ++- 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 | 78 ++++--- src/rpc/virnettlscontext.c | 26 +-- src/security/security_apparmor.c | 20 +- src/security/security_dac.c | 21 +- src/security/security_nop.c | 7 +- src/security/security_selinux.c | 79 ++------ src/security/virt-aa-helper.c | 4 +- src/util/virauth.c | 17 +- src/util/virauthconfig.c | 8 +- src/util/virbitmap.c | 9 +- src/util/vircgroup.c | 37 ++-- 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/virfile.c | 28 ++- src/util/virhash.c | 5 +- src/util/viridentity.c | 14 +- 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 | 27 +-- src/util/virnetdevmacvlan.c | 16 +- src/util/virnetdevtap.c | 11 +- src/util/virnetdevvportprofile.c | 4 +- src/util/virobject.c | 16 +- src/util/virpci.c | 13 +- src/util/virscsi.c | 6 +- src/util/virsexpr.c | 37 +--- src/util/virsocketaddr.c | 9 +- src/util/virstoragefile.c | 18 +- src/util/virstring.c | 17 +- src/util/virsysinfo.c | 293 +++++++++++---------------- src/util/virtypedparam.c | 14 +- src/util/viruri.c | 58 +++--- src/util/virutil.c | 57 ++---- src/util/virxml.c | 5 +- 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 | 68 ++----- 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 | 200 ++++++++---------- src/xenxs/xen_xm.c | 91 ++++----- 86 files changed, 1244 insertions(+), 2032 deletions(-) -- 1.8.2.1

--- src/conf/capabilities.c | 30 ++++------- src/conf/cpu_conf.c | 20 ++++---- src/conf/domain_conf.c | 119 ++++++++++++-------------------------------- src/conf/domain_event.c | 41 +++++++-------- src/conf/node_device_conf.c | 28 +++++------ src/conf/nwfilter_conf.c | 17 ++----- src/conf/nwfilter_params.c | 34 ++++--------- src/conf/snapshot_conf.c | 11 ++-- src/conf/storage_conf.c | 13 ++--- src/conf/virchrdev.c | 12 ++--- 10 files changed, 107 insertions(+), 218 deletions(-) diff --git a/src/conf/capabilities.c b/src/conf/capabilities.c index 5340b63..b306a78 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 (VIR_STRDUP(guest->arch.defaultInfo.emulator, emulator) < 0 || + 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 || + VIR_STRDUP(dom->info.emulator, emulator) < 0 || + 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..1144cba 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 (VIR_STRDUP(dst->model, src->model) < 0 || + VIR_STRDUP(dst->vendor, src->vendor) < 0 || + 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,8 +118,8 @@ virCPUDefCopyModel(virCPUDefPtr dst, dst->features[i].policy = src->features[i].policy; } - if (!(dst->features[i].name = strdup(src->features[i].name))) - goto no_memory; + if (VIR_STRDUP(dst->features[i].name, src->features[i].name) < 0) + return -1; } return 0; @@ -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) + return -1; def->features[def->nfeatures].policy = policy; def->nfeatures++; diff --git a/src/conf/domain_conf.c b/src/conf/domain_conf.c index e7a0381..441f83f 100644 --- a/src/conf/domain_conf.c +++ b/src/conf/domain_conf.c @@ -1358,60 +1358,35 @@ virDomainChrSourceDefCopy(virDomainChrSourceDefPtr dest, case VIR_DOMAIN_CHR_TYPE_DEV: 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(); + if (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(); + if (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(); + if (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(); + if (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(); + if (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(); + if (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(); + if (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(); + if (VIR_STRDUP(dest->data.nix.path, src->data.nix.path) < 0) return -1; - } break; } @@ -2391,14 +2366,9 @@ virDomainDeviceInfoCopy(virDomainDeviceInfoPtr dst, dst->alias = NULL; dst->romfile = NULL; - if (src->alias && !(dst->alias = strdup(src->alias))) { - virReportOOMError(); + if (VIR_STRDUP(dst->alias, src->alias) < 0 || + VIR_STRDUP(dst->romfile, src->romfile) < 0) return -1; - } - if (src->romfile && !(dst->romfile = strdup(src->romfile))) { - virReportOOMError(); - return -1; - } return 0; } @@ -4251,11 +4221,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")); @@ -5893,10 +5860,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) { @@ -6285,10 +6250,8 @@ 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)) { - virReportOOMError(); + VIR_STRDUP(addrtype, "usb") < 0) goto error; - } hostdev->mode = VIR_DOMAIN_HOSTDEV_MODE_SUBSYS; if (virDomainHostdevDefParseXMLSubsys(node, ctxt, addrtype, hostdev, flags) < 0) { @@ -7162,10 +7125,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; @@ -8965,10 +8926,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); /* @@ -9927,9 +9886,7 @@ virDomainDefGetDefaultEmulator(virDomainDefPtr def, return NULL; } - if (!(retemu = strdup(emulator))) - virReportOOMError(); - + ignore_value(VIR_STRDUP(retemu, emulator)); return retemu; } @@ -11035,10 +10992,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")); @@ -11053,9 +11008,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)) { @@ -11109,11 +11063,8 @@ virDomainDefParseXML(xmlDocPtr xml, def->os.type, 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; } /* @@ -11142,8 +11093,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); @@ -16799,7 +16751,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++; @@ -16821,7 +16773,6 @@ virDomainObjListGetInactiveNames(virDomainObjListPtr doms, if (data.oom) { for (i = 0 ; i < data.numnames ; i++) VIR_FREE(data.names[i]); - virReportOOMError(); return -1; } @@ -17352,12 +17303,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; } @@ -17394,12 +17342,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; } @@ -17734,7 +17679,7 @@ virDomainDefGenSecurityLabelDef(const char *model) virSecurityLabelDefPtr seclabel = NULL; if (VIR_ALLOC(seclabel) < 0 || - (model && !(seclabel->model = strdup(model)))) { + VIR_STRDUP(seclabel->model, model) < 0) { virReportOOMError(); virSecurityLabelDefFree(seclabel); seclabel = NULL; @@ -17749,7 +17694,7 @@ virDomainDiskDefGenSecurityLabelDef(const char *model) virSecurityDeviceLabelDefPtr seclabel = NULL; if (VIR_ALLOC(seclabel) < 0 || - (model && !(seclabel->model = strdup(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..1102170 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 || + 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 || + 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,13 @@ 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))) + if (VIR_STRDUP(ev->data.diskChange.oldSrcPath, oldSrcPath) < 0) goto error; - if (newSrcPath && - !(ev->data.diskChange.newSrcPath = strdup(newSrcPath))) + if (VIR_STRDUP(ev->data.diskChange.newSrcPath, newSrcPath) < 0) goto error; ev->data.diskChange.reason = reason; @@ -1004,7 +1001,6 @@ virDomainEventDiskChangeNew(int id, const char *name, return ev; error: - virReportOOMError(); virDomainEventFree(ev); return NULL; } @@ -1042,7 +1038,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 +1047,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..488d880 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,18 @@ 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); + goto cleanup; + } break; } @@ -1301,15 +1301,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..ac5f7ed 100644 --- a/src/conf/nwfilter_params.c +++ b/src/conf/nwfilter_params.c @@ -79,19 +79,15 @@ 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) - goto err_exit; - } + if (VIR_STRDUP(res->u.simple.value, val->u.simple.value) < 0) + goto err_exit; break; case NWFILTER_VALUE_TYPE_ARRAY: if (VIR_ALLOC_N(res->u.array.values, val->u.array.nValues) < 0) 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 +129,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 +648,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 +998,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 +1012,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 8fa805b..af46dcc 100644 --- a/src/conf/storage_conf.c +++ b/src/conf/storage_conf.c @@ -888,11 +888,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; - } } } @@ -1705,16 +1702,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.2.1

On 05/20/2013 11:55 AM, Michal Privoznik wrote:
--- src/conf/capabilities.c | 30 ++++------- src/conf/cpu_conf.c | 20 ++++---- src/conf/domain_conf.c | 119 ++++++++++++-------------------------------- src/conf/domain_event.c | 41 +++++++-------- src/conf/node_device_conf.c | 28 +++++------ src/conf/nwfilter_conf.c | 17 ++----- src/conf/nwfilter_params.c | 34 ++++--------- src/conf/snapshot_conf.c | 11 ++-- src/conf/storage_conf.c | 13 ++--- src/conf/virchrdev.c | 12 ++--- 10 files changed, 107 insertions(+), 218 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;
silent->noisy, but all callers reported OOM via a no_memory label, and I'm okay with double-oom if you are still planning on making another pass to reduce the number of no_memory labels in the code base.
@@ -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;
silent->noisy. esx_driver.c and qemu_capabilities aren't checking for error (they should), xen_hypervisor has double-oom via no_memory label, and tests/vmx2xmltest.c and tests/xml2vmxtest.c can get by as-is.
@@ -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;
silent->noisy, but all callers (outside tests) used no_memory label and now have 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;
Local double-oom. You might want to clean this one up now.
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 (VIR_STRDUP(guest->arch.defaultInfo.emulator, emulator) < 0 || + VIR_STRDUP(guest->arch.defaultInfo.loader, loader) < 0) goto no_memory;
another local double-oom. Cleaning now would be nice, but I guess I can live with the promise of later cleanup of 'no_memory' labels.
@@ -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 || + VIR_STRDUP(dom->info.emulator, emulator) < 0 || + VIR_STRDUP(dom->info.loader, loader) < 0) goto no_memory;
More double-oom
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;
and again
feature->defaultOn = defaultOn; feature->toggle = toggle; diff --git a/src/conf/cpu_conf.c b/src/conf/cpu_conf.c index 6aaee75..1144cba 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 (VIR_STRDUP(dst->model, src->model) < 0 || + VIR_STRDUP(dst->vendor, src->vendor) < 0 || + VIR_STRDUP(dst->vendor_id, src->vendor_id) < 0 || + VIR_ALLOC_N(dst->features, src->nfeatures) < 0) goto no_memory;
Here, you have double-oom, but you also have a VIR_ALLOC_N. I can definitely agree to leaving this one as-is, since we are going to audit VIR_ALLOC_N later and can clean up the double-oom then (the earlier uses have no VIR_ALLOC_N nearby, but if your goal is to get rid of no_memory labels in general, you'd still get them on a later pass).
+++ b/src/conf/domain_conf.c @@ -17352,12 +17303,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))
Might look nicer as: if (VIR_STRNDUP(listenInfo->address, address, len == -1 ? strlen(address) : len) < 0)
@@ -17394,12 +17342,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))
Another site where calling just VIR_STRNDUP looks nicer.
@@ -17734,7 +17679,7 @@ virDomainDefGenSecurityLabelDef(const char *model) virSecurityLabelDefPtr seclabel = NULL;
if (VIR_ALLOC(seclabel) < 0 || - (model && !(seclabel->model = strdup(model)))) { + VIR_STRDUP(seclabel->model, model) < 0) { virReportOOMError();
double-oom, but mixed with VIR_ALLOC so okay for now
+++ 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 || + VIR_STRDUP(ev->data.ioError.reason, reason) < 0) { virDomainEventFree(ev); ev = NULL;
silent->noisy, but this is a case where we are trying to send an asynchronous event, and merely discard it on OOM. This change now leaves an error in the thread-local storage, to be used in the next unrelated synchronous command that uses the same worker thread. Are we SURE this is right? That is, if ALL libvirt API clear out the local error on entry, then checking if the local error is set on exit, then littering the thread-local error at other times won't change the behavior of synchronous API. But I think you got lucky: looking at src/libvirt.c, we are pretty consistent on virResetLastError() at the head of all API.
} @@ -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 || + VIR_STRDUP(ev->data.ioError.reason, reason) < 0) { virDomainEventFree(ev); ev = NULL;
Same comment on silent-noisy now polluting thread-local storage.
} @@ -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;
and again
} @@ -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;
and again
} @@ -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;
but THIS virDomainEvent*New was already reporting. Okay, you win - we SHOULD be reporting everywhere, even if we end up discarding the error object instead of sending it across rpc because we hit oom. A couple of suggestions, but no major errors, and I know you are planning on doing some of the double-oom cleanup in a later patch. ACK. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On 21.05.2013 00:38, Eric Blake wrote:
On 05/20/2013 11:55 AM, Michal Privoznik wrote:
--- src/conf/capabilities.c | 30 ++++------- src/conf/cpu_conf.c | 20 ++++---- src/conf/domain_conf.c | 119 ++++++++++++-------------------------------- src/conf/domain_event.c | 41 +++++++-------- src/conf/node_device_conf.c | 28 +++++------ src/conf/nwfilter_conf.c | 17 ++----- src/conf/nwfilter_params.c | 34 ++++--------- src/conf/snapshot_conf.c | 11 ++-- src/conf/storage_conf.c | 13 ++--- src/conf/virchrdev.c | 12 ++--- 10 files changed, 107 insertions(+), 218 deletions(-)
} @@ -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;
Local double-oom. You might want to clean this one up now.
You mean s/no_memory/error/ ? Because even if the label is called no_memory not every label does call virReportOOMError(), like in this case.
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 (VIR_STRDUP(guest->arch.defaultInfo.emulator, emulator) < 0 || + VIR_STRDUP(guest->arch.defaultInfo.loader, loader) < 0) goto no_memory;
another local double-oom. Cleaning now would be nice, but I guess I can live with the promise of later cleanup of 'no_memory' labels.

On 05/21/2013 03:14 AM, Michal Privoznik wrote:
@@ -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;
Local double-oom. You might want to clean this one up now.
You mean s/no_memory/error/ ? Because even if the label is called no_memory not every label does call virReportOOMError(), like in this case.
Ah, now that I look at the label, you're right! Yes, s/no_memory/error/ would avoid my confusion (generally, I've been assuming that a no_memory label implied an OOM report). -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On 05/20/2013 01:55 PM, Michal Privoznik wrote:
--- [...snip...]
diff --git a/src/conf/nwfilter_params.c b/src/conf/nwfilter_params.c index 2509c0d..ac5f7ed 100644 --- a/src/conf/nwfilter_params.c +++ b/src/conf/nwfilter_params.c @@ -79,19 +79,15 @@ 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) - goto err_exit; - } + if (VIR_STRDUP(res->u.simple.value, val->u.simple.value) < 0) + goto err_exit; break; case NWFILTER_VALUE_TYPE_ARRAY: if (VIR_ALLOC_N(res->u.array.values, val->u.array.nValues) < 0) 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 +129,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 +648,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; }
Coverity complains (see below too) 648 { (1) Event cond_true: Condition "!virHashLookup(table->hashTable, name)", taking true branch 649 if (!virHashLookup(table->hashTable, name)) { (2) Event cond_true: Condition "copyName", taking true branch 650 if (copyName) { 651 char *newName; (3) Event cond_false: Condition "virStrdup(&newName, name, true /* 1 */, VIR_FROM_NWFILTER, "conf/nwfilter_params.c", <anonymous>, 652) < 0", taking false branch 652 if (VIR_STRDUP(newName, name) < 0) 653 return -1; 654 (5) Event cond_false: Condition "virReallocN(&table->names, 8UL /* sizeof (*table->names) */, table->nNames + 1) < 0", taking false branch 655 if (VIR_REALLOC_N(table->names, table->nNames + 1) < 0) { 656 VIR_FREE(name); 657 return -1; (6) Event if_end: End of if statement 658 } 659 table->names[table->nNames++] = newName; 660 } 661 (7) Event cond_true: Condition "virHashAddEntry(table->hashTable, name, val) < 0", taking true branch 662 if (virHashAddEntry(table->hashTable, name, val) < 0) { (8) Event cond_true: Condition "copyName", taking true branch 663 if (copyName) { (9) Event freed_arg: "virFree(void *)" frees parameter "name". [details] 664 VIR_FREE(name); 665 table->nNames--; 666 } 667 return -1; 668 } In particular, the "VIR_FREE(name)" causes a problem in one of the callers, see below. So I think the fix is to dump "newNames" up one level, then change: 664 VIR_FREE(name); 665 table->nNames--; to 664 VIR_FREE(newName); 665 table->nNames--; John
if (virHashAddEntry(table->hashTable, name, val) < 0) { @@ -1006,11 +998,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 +1012,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);
Coverity complains: 746 static void 747 addToTable(void *payload, const void *name, void *data) 748 { 749 struct addToTableStruct *atts = (struct addToTableStruct *)data; 750 virNWFilterVarValuePtr val; 751 (1) Event cond_false: Condition "atts->errOccurred", taking false branch 752 if (atts->errOccurred) 753 return; 754 755 val = virNWFilterVarValueCopy((virNWFilterVarValuePtr)payload); (2) Event cond_false: Condition "!val", taking false branch 756 if (!val) { 757 virReportOOMError(); 758 atts->errOccurred = 1; 759 return; (3) Event if_end: End of if statement 760 } 761 (4) Event freed_arg: "virNWFilterHashTablePut(virNWFilterHashTablePtr, char const *, virNWFilterVarValuePtr, int)" frees "name". [details] (5) Event cond_true: Condition "virNWFilterHashTablePut(atts->target, (char const *)name, val, 1) < 0", taking true branch Also see events: [pass_freed_arg] 762 if (virNWFilterHashTablePut(atts->target, (const char *)name, val, 1) < 0){ (6) Event pass_freed_arg: Passing freed pointer "name" as an argument to function "virReportErrorHelper(int, int, char const *, char const *, size_t, char const *, ...)". Also see events: [freed_arg] 763 virReportError(VIR_ERR_INTERNAL_ERROR, 764 _("Could not put variable '%s' into hashmap"), 765 (const char *)name); 766 atts->errOccurred = 1; 767 virNWFilterVarValueFree(val); 768 } 769 } The complaint being 'name' could be VIR_FREE()'d and we would be using it in a virReportError()

On 23.05.2013 15:04, John Ferlan wrote:
On 05/20/2013 01:55 PM, Michal Privoznik wrote:
--- [...snip...]
diff --git a/src/conf/nwfilter_params.c b/src/conf/nwfilter_params.c index 2509c0d..ac5f7ed 100644 --- a/src/conf/nwfilter_params.c +++ b/src/conf/nwfilter_params.c @@ -79,19 +79,15 @@ 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) - goto err_exit; - } + if (VIR_STRDUP(res->u.simple.value, val->u.simple.value) < 0) + goto err_exit; break; case NWFILTER_VALUE_TYPE_ARRAY: if (VIR_ALLOC_N(res->u.array.values, val->u.array.nValues) < 0) 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 +129,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 +648,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; }
Coverity complains (see below too)
648 {
(1) Event cond_true: Condition "!virHashLookup(table->hashTable, name)", taking true branch
649 if (!virHashLookup(table->hashTable, name)) {
(2) Event cond_true: Condition "copyName", taking true branch
650 if (copyName) { 651 char *newName;
(3) Event cond_false: Condition "virStrdup(&newName, name, true /* 1 */, VIR_FROM_NWFILTER, "conf/nwfilter_params.c", <anonymous>, 652) < 0", taking false branch
652 if (VIR_STRDUP(newName, name) < 0) 653 return -1; 654
(5) Event cond_false: Condition "virReallocN(&table->names, 8UL /* sizeof (*table->names) */, table->nNames + 1) < 0", taking false branch
655 if (VIR_REALLOC_N(table->names, table->nNames + 1) < 0) { 656 VIR_FREE(name); 657 return -1;
(6) Event if_end: End of if statement
658 } 659 table->names[table->nNames++] = newName; 660 } 661
(7) Event cond_true: Condition "virHashAddEntry(table->hashTable, name, val) < 0", taking true branch
662 if (virHashAddEntry(table->hashTable, name, val) < 0) {
(8) Event cond_true: Condition "copyName", taking true branch
663 if (copyName) {
(9) Event freed_arg: "virFree(void *)" frees parameter "name". [details]
664 VIR_FREE(name); 665 table->nNames--; 666 } 667 return -1; 668 }
In particular, the "VIR_FREE(name)" causes a problem in one of the callers, see below. So I think the fix is to dump "newNames" up one level, then change:
664 VIR_FREE(name); 665 table->nNames--;
to
664 VIR_FREE(newName); 665 table->nNames--;
John
Right, it took me a while to parse the coverity output, and here's the part of the original code that confused me: if (!virHashLookup(table->hashTable, name)) { if (copyName) { name = strdup(name);
if (virHashAddEntry(table->hashTable, name, val) < 0) { @@ -1006,11 +998,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 +1012,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);
Coverity complains:
746 static void 747 addToTable(void *payload, const void *name, void *data) 748 { 749 struct addToTableStruct *atts = (struct addToTableStruct *)data; 750 virNWFilterVarValuePtr val; 751
(1) Event cond_false: Condition "atts->errOccurred", taking false branch
752 if (atts->errOccurred) 753 return; 754 755 val = virNWFilterVarValueCopy((virNWFilterVarValuePtr)payload);
(2) Event cond_false: Condition "!val", taking false branch
756 if (!val) { 757 virReportOOMError(); 758 atts->errOccurred = 1; 759 return;
(3) Event if_end: End of if statement
760 } 761
(4) Event freed_arg: "virNWFilterHashTablePut(virNWFilterHashTablePtr, char const *, virNWFilterVarValuePtr, int)" frees "name". [details] (5) Event cond_true: Condition "virNWFilterHashTablePut(atts->target, (char const *)name, val, 1) < 0", taking true branch Also see events: [pass_freed_arg]
762 if (virNWFilterHashTablePut(atts->target, (const char *)name, val, 1) < 0){
(6) Event pass_freed_arg: Passing freed pointer "name" as an argument to function "virReportErrorHelper(int, int, char const *, char const *, size_t, char const *, ...)". Also see events: [freed_arg]
763 virReportError(VIR_ERR_INTERNAL_ERROR, 764 _("Could not put variable '%s' into hashmap"), 765 (const char *)name); 766 atts->errOccurred = 1; 767 virNWFilterVarValueFree(val); 768 } 769 }
The complaint being 'name' could be VIR_FREE()'d and we would be using it in a virReportError()
Yup, that due to the bug in virNWFilterHashTablePut(). Michal

On 05/23/2013 09:44 AM, Michal Privoznik wrote:
On 23.05.2013 15:04, John Ferlan wrote:
On 05/20/2013 01:55 PM, Michal Privoznik wrote:
--- [...snip...]
diff --git a/src/conf/nwfilter_params.c b/src/conf/nwfilter_params.c index 2509c0d..ac5f7ed 100644 --- a/src/conf/nwfilter_params.c +++ b/src/conf/nwfilter_params.c @@ -79,19 +79,15 @@ 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) - goto err_exit; - } + if (VIR_STRDUP(res->u.simple.value, val->u.simple.value) < 0) + goto err_exit; break; case NWFILTER_VALUE_TYPE_ARRAY: if (VIR_ALLOC_N(res->u.array.values, val->u.array.nValues) < 0) 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 +129,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 +648,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; }
Coverity complains (see below too)
648 {
(1) Event cond_true: Condition "!virHashLookup(table->hashTable, name)", taking true branch
649 if (!virHashLookup(table->hashTable, name)) {
(2) Event cond_true: Condition "copyName", taking true branch
650 if (copyName) { 651 char *newName;
(3) Event cond_false: Condition "virStrdup(&newName, name, true /* 1 */, VIR_FROM_NWFILTER, "conf/nwfilter_params.c", <anonymous>, 652) < 0", taking false branch
652 if (VIR_STRDUP(newName, name) < 0) 653 return -1; 654
(5) Event cond_false: Condition "virReallocN(&table->names, 8UL /* sizeof (*table->names) */, table->nNames + 1) < 0", taking false branch
655 if (VIR_REALLOC_N(table->names, table->nNames + 1) < 0) { 656 VIR_FREE(name); 657 return -1;
(6) Event if_end: End of if statement
658 } 659 table->names[table->nNames++] = newName; 660 } 661
(7) Event cond_true: Condition "virHashAddEntry(table->hashTable, name, val) < 0", taking true branch
662 if (virHashAddEntry(table->hashTable, name, val) < 0) {
(8) Event cond_true: Condition "copyName", taking true branch
663 if (copyName) {
(9) Event freed_arg: "virFree(void *)" frees parameter "name". [details]
664 VIR_FREE(name); 665 table->nNames--; 666 } 667 return -1; 668 }
In particular, the "VIR_FREE(name)" causes a problem in one of the callers, see below. So I think the fix is to dump "newNames" up one level, then change:
664 VIR_FREE(name); 665 table->nNames--;
to
664 VIR_FREE(newName); 665 table->nNames--;
John
Right, it took me a while to parse the coverity output, and here's the part of the original code that confused me:
if (!virHashLookup(table->hashTable, name)) { if (copyName) { name = strdup(name);
Taking advantage that when returned to the caller name is what it was... The following seems right (that is use newName instead of name locally): diff --git a/src/conf/nwfilter_params.c b/src/conf/nwfilter_params.c index ac5f7ed..44b9f05 100644 --- a/src/conf/nwfilter_params.c +++ b/src/conf/nwfilter_params.c @@ -647,13 +647,13 @@ virNWFilterHashTablePut(virNWFilterHashTablePtr table, int copyName) { if (!virHashLookup(table->hashTable, name)) { + char *newName = NULL; if (copyName) { - char *newName; if (VIR_STRDUP(newName, name) < 0) return -1; if (VIR_REALLOC_N(table->names, table->nNames + 1) < 0) { - VIR_FREE(name); + VIR_FREE(newName); return -1; } table->names[table->nNames++] = newName; @@ -661,7 +661,7 @@ virNWFilterHashTablePut(virNWFilterHashTablePtr table, if (virHashAddEntry(table->hashTable, name, val) < 0) { if (copyName) { - VIR_FREE(name); + VIR_FREE(newName); table->nNames--; } return -1;

On 23.05.2013 15:56, John Ferlan wrote:
On 05/23/2013 09:44 AM, Michal Privoznik wrote:
On 23.05.2013 15:04, John Ferlan wrote:
On 05/20/2013 01:55 PM, Michal Privoznik wrote:
--- [...snip...]
diff --git a/src/conf/nwfilter_params.c b/src/conf/nwfilter_params.c index 2509c0d..ac5f7ed 100644 --- a/src/conf/nwfilter_params.c +++ b/src/conf/nwfilter_params.c @@ -79,19 +79,15 @@ 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) - goto err_exit; - } + if (VIR_STRDUP(res->u.simple.value, val->u.simple.value) < 0) + goto err_exit; break; case NWFILTER_VALUE_TYPE_ARRAY: if (VIR_ALLOC_N(res->u.array.values, val->u.array.nValues) < 0) 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 +129,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 +648,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; }
Coverity complains (see below too)
648 {
(1) Event cond_true: Condition "!virHashLookup(table->hashTable, name)", taking true branch
649 if (!virHashLookup(table->hashTable, name)) {
(2) Event cond_true: Condition "copyName", taking true branch
650 if (copyName) { 651 char *newName;
(3) Event cond_false: Condition "virStrdup(&newName, name, true /* 1 */, VIR_FROM_NWFILTER, "conf/nwfilter_params.c", <anonymous>, 652) < 0", taking false branch
652 if (VIR_STRDUP(newName, name) < 0) 653 return -1; 654
(5) Event cond_false: Condition "virReallocN(&table->names, 8UL /* sizeof (*table->names) */, table->nNames + 1) < 0", taking false branch
655 if (VIR_REALLOC_N(table->names, table->nNames + 1) < 0) { 656 VIR_FREE(name); 657 return -1;
(6) Event if_end: End of if statement
658 } 659 table->names[table->nNames++] = newName; 660 } 661
(7) Event cond_true: Condition "virHashAddEntry(table->hashTable, name, val) < 0", taking true branch
662 if (virHashAddEntry(table->hashTable, name, val) < 0) {
(8) Event cond_true: Condition "copyName", taking true branch
663 if (copyName) {
(9) Event freed_arg: "virFree(void *)" frees parameter "name". [details]
664 VIR_FREE(name); 665 table->nNames--; 666 } 667 return -1; 668 }
In particular, the "VIR_FREE(name)" causes a problem in one of the callers, see below. So I think the fix is to dump "newNames" up one level, then change:
664 VIR_FREE(name); 665 table->nNames--;
to
664 VIR_FREE(newName); 665 table->nNames--;
John
Right, it took me a while to parse the coverity output, and here's the part of the original code that confused me:
if (!virHashLookup(table->hashTable, name)) { if (copyName) { name = strdup(name);
Taking advantage that when returned to the caller name is what it was...
The following seems right (that is use newName instead of name locally):
diff --git a/src/conf/nwfilter_params.c b/src/conf/nwfilter_params.c index ac5f7ed..44b9f05 100644 --- a/src/conf/nwfilter_params.c +++ b/src/conf/nwfilter_params.c @@ -647,13 +647,13 @@ virNWFilterHashTablePut(virNWFilterHashTablePtr table, int copyName) { if (!virHashLookup(table->hashTable, name)) { + char *newName = NULL; if (copyName) { - char *newName; if (VIR_STRDUP(newName, name) < 0) return -1;
if (VIR_REALLOC_N(table->names, table->nNames + 1) < 0) { - VIR_FREE(name); + VIR_FREE(newName); return -1; } table->names[table->nNames++] = newName; @@ -661,7 +661,7 @@ virNWFilterHashTablePut(virNWFilterHashTablePtr table,
if (virHashAddEntry(table->hashTable, name, val) < 0) { if (copyName) { - VIR_FREE(name); + VIR_FREE(newName); table->nNames--; } return -1;
Yup, that's exactly the patch that I wrote (haven't send it though yet). ACK if you want to push it. Michal

--- src/openvz/openvz_conf.c | 45 ++++++++++++++++++++++----------------------- src/openvz/openvz_driver.c | 29 ++++++++++------------------- 2 files changed, 32 insertions(+), 42 deletions(-) diff --git a/src/openvz/openvz_conf.c b/src/openvz/openvz_conf.c index bea08d8..90b4483 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 33ba624..426747c 100644 --- a/src/openvz/openvz_driver.c +++ b/src/openvz/openvz_driver.c @@ -94,13 +94,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; } @@ -356,8 +351,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) @@ -770,12 +764,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 * @@ -786,7 +782,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; @@ -801,15 +797,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; } @@ -1601,10 +1594,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.2.1

On 05/20/2013 11:55 AM, Michal Privoznik wrote:
--- src/openvz/openvz_conf.c | 45 ++++++++++++++++++++++----------------------- src/openvz/openvz_driver.c | 29 ++++++++++------------------- 2 files changed, 32 insertions(+), 42 deletions(-)
+++ b/src/openvz/openvz_driver.c @@ -94,13 +94,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");
Unintentional change in return value from 0 to 1; I'd prefer keeping it at 0.
@@ -770,12 +764,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;
Why snprintf only to strdup it? You can ditch dev_name, and just do: if (virAsprintf(&ret, "veth%d.%d", veid, ifNo) < 0) virReportOOMError(); return ret; ACK with those fixes. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

For future work we need _virDomainEventGraphicsAddress and _virDomainEventGraphicsSubjectIdentity members to be char * not const char *. We are strdup()ing them anyway, so they should have been char * anyway (from const correctness POV). However, we don't want users to change passed values, so we need to make the callback's argument const. --- include/libvirt/libvirt.h.in | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/include/libvirt/libvirt.h.in b/include/libvirt/libvirt.h.in index 693b834..1804c93 100644 --- a/include/libvirt/libvirt.h.in +++ b/include/libvirt/libvirt.h.in @@ -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; @@ -4560,10 +4560,10 @@ typedef virDomainEventGraphicsSubject *virDomainEventGraphicsSubjectPtr; typedef void (*virConnectDomainEventGraphicsCallback)(virConnectPtr conn, virDomainPtr dom, int phase, - virDomainEventGraphicsAddressPtr local, - virDomainEventGraphicsAddressPtr remote, + const virDomainEventGraphicsAddressPtr local, + const virDomainEventGraphicsAddressPtr remote, const char *authScheme, - virDomainEventGraphicsSubjectPtr subject, + const virDomainEventGraphicsSubjectPtr subject, void *opaque); /** -- 1.8.2.1

On 05/20/2013 11:55 AM, Michal Privoznik wrote:
For future work we need _virDomainEventGraphicsAddress and _virDomainEventGraphicsSubjectIdentity members to be char * not const char *. We are strdup()ing them anyway, so they should have been char * anyway (from const correctness POV). However, we don't want users to change passed values, so we need to make the callback's argument const. --- include/libvirt/libvirt.h.in | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-)
Please update your commit message to include a bit more justification - this part of my analysis on v3 (slightly reworded here) would be a good start: Although this is an API change, real callers won't be impacted. Why? 1. these callback members are read-only, 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. ACK with that improvement. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On 21.05.2013 01:20, Eric Blake wrote:
On 05/20/2013 11:55 AM, Michal Privoznik wrote:
For future work we need _virDomainEventGraphicsAddress and _virDomainEventGraphicsSubjectIdentity members to be char * not const char *. We are strdup()ing them anyway, so they should have been char * anyway (from const correctness POV). However, we don't want users to change passed values, so we need to make the callback's argument const. --- include/libvirt/libvirt.h.in | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-)
Please update your commit message to include a bit more justification - this part of my analysis on v3 (slightly reworded here) would be a good start:
Although this is an API change, real callers won't be impacted. Why? 1. these callback members are read-only, 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.
ACK with that improvement.
Okay, I've pushed the first three patches. Thanks so far. Michal

Currently, @prompt member within _virConnectCredential struct is const char. This violates const correctness as we are not just strdup()-ing the value, we are even changing it (e.g. in virNetSSHKbIntCb()). --- include/libvirt/libvirt.h.in | 2 +- src/remote/remote_driver.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/include/libvirt/libvirt.h.in b/include/libvirt/libvirt.h.in index 1804c93..1bd3d1a 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) */ 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.2.1

On 05/20/2013 11:55 AM, Michal Privoznik wrote:
Currently, @prompt member within _virConnectCredential struct is const char. This violates const correctness as we are not just strdup()-ing the value, we are even changing it (e.g. in virNetSSHKbIntCb()). --- include/libvirt/libvirt.h.in | 2 +- src/remote/remote_driver.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-)
I am not comfortable with this one. This is an API change that WILL cause compilation to fail on anyone that compiled against the old type.
diff --git a/include/libvirt/libvirt.h.in b/include/libvirt/libvirt.h.in index 1804c93..1bd3d1a 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 */
Is the USER allowed to change prompt? Or is the only place where it is changed our internal code?
const char *challenge; /* Additional challenge to show */ const char *defresult; /* Optional default result */ char *result; /* Result to be filled with user response (or defresult) */
Remember, the user WILL be changing result.
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;
I'm still not convinced this is right. Is casting away const sufficient, or should we be strdup'ing here?
if (interact[*ncred].defresult) (*cred)[*ncred].defresult = interact[ninteract].defresult; (*cred)[*ncred].result = NULL;
I'd really like someone else to weigh in on this one. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- src/qemu/qemu_capabilities.c | 79 +++----- src/qemu/qemu_cgroup.c | 4 +- src/qemu/qemu_command.c | 428 +++++++++++++++++-------------------------- src/qemu/qemu_conf.c | 64 +++---- src/qemu/qemu_domain.c | 26 +-- src/qemu/qemu_driver.c | 129 ++++--------- src/qemu/qemu_hotplug.c | 15 +- src/qemu/qemu_migration.c | 17 +- src/qemu/qemu_monitor_json.c | 63 ++----- src/qemu/qemu_monitor_text.c | 15 +- src/qemu/qemu_process.c | 64 +++---- 11 files changed, 333 insertions(+), 571 deletions(-) diff --git a/src/qemu/qemu_capabilities.c b/src/qemu/qemu_capabilities.c index 82129a2..f0471f4 100644 --- a/src/qemu/qemu_capabilities.c +++ b/src/qemu/qemu_capabilities.c @@ -369,8 +369,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) + return -1; p = t; if ((t = strstr(p, "(default)")) && (!next || t < next)) @@ -381,9 +381,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; + return -1; } } @@ -391,7 +391,8 @@ virQEMUCapsParseMachineTypesStr(const char *output, VIR_REALLOC_N(qemuCaps->machineAliases, qemuCaps->nmachineTypes + 1) < 0) { VIR_FREE(name); VIR_FREE(canonical); - goto no_memory; + virReportOOMError(); + return -1; } qemuCaps->nmachineTypes++; if (canonical) { @@ -408,10 +409,6 @@ virQEMUCapsParseMachineTypesStr(const char *output, virQEMUCapsSetDefaultMachine(qemuCaps, defIdx); return 0; - -no_memory: - virReportOOMError(); - return -1; } static int @@ -506,10 +503,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; @@ -559,10 +554,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; @@ -1512,10 +1505,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; @@ -1569,10 +1560,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; @@ -1741,8 +1730,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) @@ -1751,17 +1740,16 @@ 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 (qemuCaps->machineAliases[i] && - !(ret->machineAliases[i] = strdup(qemuCaps->machineAliases[i]))) - goto no_memory; + if (VIR_STRDUP(ret->machineTypes[i], qemuCaps->machineTypes[i]) < 0 || + VIR_STRDUP(ret->machineAliases[i], qemuCaps->machineAliases[i]) < 0) + goto error; } return ret; no_memory: virReportOOMError(); +error: virObjectUnref(ret); return NULL; } @@ -1863,11 +1851,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(); @@ -1912,12 +1899,11 @@ int virQEMUCapsGetMachineTypesCaps(virQEMUCapsPtr qemuCaps, if (VIR_ALLOC(mach) < 0) goto no_memory; if (qemuCaps->machineAliases[i]) { - if (!(mach->name = strdup(qemuCaps->machineAliases[i]))) - goto no_memory; - if (!(mach->canonical = strdup(qemuCaps->machineTypes[i]))) + if (VIR_STRDUP(mach->name, qemuCaps->machineAliases[i]) < 0 || + 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; @@ -2106,16 +2092,9 @@ 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 (VIR_STRDUP(qemuCaps->machineAliases[i], machines[i]->alias) < 0 || + VIR_STRDUP(qemuCaps->machineTypes[i], machines[i]->name) < 0) goto cleanup; - } if (machines[i]->isDefault) defIdx = i; } @@ -2666,8 +2645,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. */ @@ -2697,8 +2676,6 @@ virQEMUCapsPtr virQEMUCapsNewForBinary(const char *binary, return qemuCaps; -no_memory: - virReportOOMError(); error: virObjectUnref(qemuCaps); qemuCaps = NULL; @@ -2748,10 +2725,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 ff9a075..6feeecd 100644 --- a/src/qemu/qemu_cgroup.c +++ b/src/qemu/qemu_cgroup.c @@ -32,6 +32,7 @@ #include "virerror.h" #include "domain_audit.h" #include "virscsi.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_QEMU @@ -695,8 +696,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 33a1910..22c4e4c 100644 --- a/src/qemu/qemu_command.c +++ b/src/qemu/qemu_command.c @@ -325,10 +325,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"), @@ -340,10 +338,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; } @@ -541,17 +537,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; } @@ -568,10 +557,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; } @@ -2489,13 +2475,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); @@ -2513,6 +2497,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; @@ -2526,9 +2511,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'; } @@ -2553,11 +2537,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; @@ -2584,9 +2566,8 @@ static int qemuParseRBDString(virDomainDiskDefPtr disk) VIR_FREE(options); return 0; -no_memory: +error: VIR_FREE(options); - virReportOOMError(); return -1; } @@ -2626,9 +2607,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; @@ -2638,9 +2618,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); @@ -2651,9 +2630,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; @@ -2664,9 +2642,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; @@ -2746,7 +2723,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) { @@ -2756,23 +2734,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; } @@ -2822,9 +2797,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; @@ -5643,9 +5617,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 (VIR_STRDUP(guest->vendor_id, cpu->vendor_id) < 0) + goto cleanup; guest->arch = host->arch; if (cpu->match == VIR_CPU_MATCH_MINIMUM) @@ -7282,8 +7257,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; } } @@ -8078,8 +8053,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); @@ -8549,17 +8524,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); @@ -8609,13 +8583,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; } @@ -8689,14 +8664,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; @@ -8800,11 +8775,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; @@ -8829,11 +8801,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, ':'); @@ -8852,18 +8821,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); @@ -8888,11 +8851,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") || @@ -9032,21 +8992,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 @@ -9398,14 +9356,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:")) { @@ -9416,40 +9372,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:") || @@ -9472,37 +9420,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); @@ -9555,13 +9491,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))) @@ -9584,13 +9516,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); @@ -9648,13 +9576,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); @@ -9872,8 +9796,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; @@ -9883,12 +9807,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; @@ -9951,10 +9875,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 { /* @@ -9994,10 +9917,11 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, } if (*opts == ',') { - char *orig_opts = strdup(opts + 1); - if (!orig_opts) { + char *orig_opts; + + if (VIR_STRDUP(orig_opts, opts + 1) < 0) { virDomainGraphicsDefFree(vnc); - goto no_memory; + goto error; } opts = orig_opts; @@ -10093,9 +10017,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")) { @@ -10108,13 +10031,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; @@ -10147,12 +10068,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: @@ -10199,24 +10118,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(); @@ -10260,11 +10179,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); @@ -10274,11 +10193,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 */ @@ -10287,11 +10206,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; @@ -10362,17 +10278,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; @@ -10474,9 +10390,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")) { @@ -10509,8 +10424,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 */ @@ -10592,9 +10507,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++; } } @@ -10623,9 +10537,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) { @@ -10636,17 +10549,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; @@ -10670,8 +10582,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) { @@ -10682,15 +10594,13 @@ virDomainDefPtr qemuParseCommandLine(virCapsPtr qemuCaps, goto no_memory; sdl->type = VIR_DOMAIN_GRAPHICS_TYPE_SDL; sdl->data.sdl.fullscreen = fullscreen; - if (display && - !(sdl->data.sdl.display = strdup(display))) { + if (VIR_STRDUP(sdl->data.sdl.display, display) < 0) { VIR_FREE(sdl); - goto no_memory; + goto error; } - if (xauth && - !(sdl->data.sdl.xauth = strdup(xauth))) { + if (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) { @@ -10807,7 +10717,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) { @@ -10825,10 +10735,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 */ @@ -10843,7 +10751,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 41fe0b9..60c2370 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; @@ -243,8 +241,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; @@ -350,8 +348,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); @@ -382,16 +380,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; } @@ -518,8 +517,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; } @@ -618,10 +617,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); } @@ -1140,10 +1138,8 @@ qemuSharedDeviceEntryCopy(const qemuSharedDeviceEntryPtr 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++; } @@ -1237,8 +1233,8 @@ qemuAddSharedDevice(virQEMUDriverPtr driver, if (!(new_entry = qemuSharedDeviceEntryCopy(entry))) goto cleanup; - if ((VIR_EXPAND_N(new_entry->domains, new_entry->ref, 1) < 0) || - !(new_entry->domains[new_entry->ref - 1] = strdup(name))) { + if (VIR_EXPAND_N(new_entry->domains, new_entry->ref, 1) < 0 || + VIR_STRDUP(new_entry->domains[new_entry->ref - 1], name) < 0) { qemuSharedDeviceEntryFree(new_entry, NULL); virReportOOMError(); goto cleanup; @@ -1249,9 +1245,9 @@ qemuAddSharedDevice(virQEMUDriverPtr driver, goto cleanup; } } else { - if ((VIR_ALLOC(entry) < 0) || - (VIR_ALLOC_N(entry->domains, 1) < 0) || - !(entry->domains[0] = strdup(name))) { + if (VIR_ALLOC(entry) < 0 || + VIR_ALLOC_N(entry->domains, 1) < 0 || + VIR_STRDUP(entry->domains[0], name) < 0) { qemuSharedDeviceEntryFree(entry, NULL); virReportOOMError(); goto cleanup; diff --git a/src/qemu/qemu_domain.c b/src/qemu/qemu_domain.c index d7c2975..8a84cf0 100644 --- a/src/qemu/qemu_domain.c +++ b/src/qemu/qemu_domain.c @@ -727,14 +727,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 */ @@ -758,8 +754,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 && @@ -801,8 +797,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; } @@ -811,10 +809,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 0665131..4dfac60 100644 --- a/src/qemu/qemu_driver.c +++ b/src/qemu/qemu_driver.c @@ -1456,10 +1456,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; } @@ -2047,8 +2045,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) @@ -3426,7 +3423,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); @@ -5174,11 +5171,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); @@ -5244,11 +5238,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); @@ -6923,9 +6915,7 @@ static char *qemuDomainGetSchedulerType(virDomainPtr dom, *nparams = 5; } - ret = strdup("posix"); - if (!ret) - virReportOOMError(); + ignore_value(VIR_STRDUP(ret, "posix")); cleanup: if (vm) @@ -6983,11 +6973,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; @@ -7351,13 +7338,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) { @@ -7882,8 +7864,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) { @@ -9560,10 +9542,8 @@ qemuDomainMigratePrepareTunnel(virConnectPtr dconn, if (dname) { VIR_FREE(def->name); - if (!(def->name = strdup(dname))) { - virReportOOMError(); + if (VIR_STRDUP(def->name, dname) < 0) goto cleanup; - } } ret = qemuMigrationPrepareTunnel(driver, dconn, @@ -9633,10 +9613,8 @@ qemuDomainMigratePrepare2(virConnectPtr dconn, if (dname) { VIR_FREE(def->name); - if (!(def->name = strdup(dname))) { - virReportOOMError(); + if (VIR_STRDUP(def->name, dname) < 0) goto cleanup; - } } /* Do not use cookies in v2 protocol, since the cookie @@ -9874,10 +9852,8 @@ qemuDomainMigratePrepare3(virConnectPtr dconn, if (dname) { VIR_FREE(def->name); - if (!(def->name = strdup(dname))) { - virReportOOMError(); + if (VIR_STRDUP(def->name, dname) < 0) goto cleanup; - } } ret = qemuMigrationPrepareDirect(driver, dconn, @@ -9939,10 +9915,8 @@ qemuDomainMigratePrepareTunnel3(virConnectPtr dconn, if (dname) { VIR_FREE(def->name); - if (!(def->name = strdup(dname))) { - virReportOOMError(); + if (VIR_STRDUP(def->name, dname) < 0) goto cleanup; - } } ret = qemuMigrationPrepareTunnel(driver, dconn, @@ -10959,9 +10933,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; @@ -11250,9 +11223,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; } @@ -11329,12 +11301,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); @@ -11938,13 +11907,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, @@ -12723,14 +12688,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) @@ -13637,10 +13598,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) { @@ -14271,10 +14230,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++; } @@ -14331,15 +14288,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 (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 (VIR_STRDUP(vm->def->title, metadata) < 0) + goto cleanup; break; case VIR_DOMAIN_METADATA_ELEMENT: virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", @@ -14359,15 +14314,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 (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 (VIR_STRDUP(persistentDef->title, metadata) < 0) + goto cleanup; break; case VIR_DOMAIN_METADATA_ELEMENT: virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", @@ -14393,9 +14346,6 @@ cleanup: virObjectUnref(caps); virObjectUnref(cfg); return ret; -no_memory: - virReportOOMError(); - goto cleanup; } static char * @@ -14453,10 +14403,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 77d9f4f..c0aa824 100644 --- a/src/qemu/qemu_hotplug.c +++ b/src/qemu/qemu_hotplug.c @@ -1353,10 +1353,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; @@ -1609,11 +1607,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")); @@ -1638,11 +1633,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 e10127d..fcb2deb 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())) @@ -460,15 +460,14 @@ qemuMigrationCookieAddLockstate(qemuMigrationCookiePtr mig, } if (virDomainObjGetState(dom, NULL) == VIR_DOMAIN_PAUSED) { - if (priv->lockState && - !(mig->lockState = strdup(priv->lockState))) + if (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; } @@ -2081,10 +2080,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 d95198b..12657e5 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; @@ -4002,10 +3990,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) { @@ -4020,10 +4006,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; - } } } @@ -4108,10 +4092,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; @@ -4257,10 +4237,8 @@ int qemuMonitorJSONGetEvents(qemuMonitorPtr mon, goto cleanup; } - if (!(eventlist[i] = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(eventlist[i], tmp) < 0) goto cleanup; - } } ret = n; @@ -4500,10 +4478,8 @@ int qemuMonitorJSONGetObjectTypes(qemuMonitorPtr mon, goto cleanup; } - if (!(typelist[i] = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(typelist[i], tmp) < 0) goto cleanup; - } } ret = n; @@ -4580,10 +4556,8 @@ int qemuMonitorJSONGetObjectProps(qemuMonitorPtr mon, goto cleanup; } - if (!(proplist[i] = strdup(tmp))) { - virReportOOMError(); + if (VIR_STRDUP(proplist[i], tmp) < 0) goto cleanup; - } } ret = n; @@ -4631,10 +4605,7 @@ qemuMonitorJSONGetTargetArch(qemuMonitorPtr mon) goto cleanup; } - if (!(ret = strdup(arch))) { - virReportOOMError(); - goto cleanup; - } + ignore_value(VIR_STRDUP(ret, arch)); cleanup: virJSONValueFree(cmd); @@ -4928,10 +4899,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 a68601b..b6c1284 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) { @@ -3476,13 +3470,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; } } @@ -4257,9 +4248,8 @@ int qemuProcessAttach(virConnectPtr conn ATTRIBUTE_UNUSED, } VIR_FREE(priv->pidfile); - if (pidfile && - !(priv->pidfile = strdup(pidfile))) - goto no_memory; + if (VIR_STRDUP(priv->pidfile, pidfile) < 0) + goto cleanup; VIR_DEBUG("Detect security driver config"); sec_managers = virSecurityManagerGetNested(driver->securityManager); @@ -4280,11 +4270,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); } -- 1.8.2.1

On 05/20/2013 11:55 AM, Michal Privoznik wrote:
--- src/qemu/qemu_capabilities.c | 79 +++----- src/qemu/qemu_cgroup.c | 4 +- src/qemu/qemu_command.c | 428 +++++++++++++++++-------------------------- src/qemu/qemu_conf.c | 64 +++---- src/qemu/qemu_domain.c | 26 +-- src/qemu/qemu_driver.c | 129 ++++--------- src/qemu/qemu_hotplug.c | 15 +- src/qemu/qemu_migration.c | 17 +- src/qemu/qemu_monitor_json.c | 63 ++----- src/qemu/qemu_monitor_text.c | 15 +- src/qemu/qemu_process.c | 64 +++---- 11 files changed, 333 insertions(+), 571 deletions(-)
@@ -1912,12 +1899,11 @@ int virQEMUCapsGetMachineTypesCaps(virQEMUCapsPtr qemuCaps, if (VIR_ALLOC(mach) < 0) goto no_memory; if (qemuCaps->machineAliases[i]) { - if (!(mach->name = strdup(qemuCaps->machineAliases[i]))) - goto no_memory; - if (!(mach->canonical = strdup(qemuCaps->machineTypes[i]))) + if (VIR_STRDUP(mach->name, qemuCaps->machineAliases[i]) < 0 || + VIR_STRDUP(mach->canonical, qemuCaps->machineTypes[i]) < 0) goto no_memory;
silent->noisy - probably a good change, but may be worth s/no_memory/error/ in the label so I don't assume it's a double-oom.
+++ b/src/qemu/qemu_command.c @@ -8549,17 +8524,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; }
Perhaps worth shortening to: if (VIR_STRNDUP(arg, curr, next ? next - curr : strlen(curr)) < 0) goto error; but I'll leave that as your call.
@@ -9416,40 +9372,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;
Looks simpler as: if (VIR_STRNDUP(source->dta.udp.connectService, sv1, host2 ? host2 - svc1 : strlen(svc1)) < 0) goto error; Hmm, this makes me wonder if it is worth making VIR_STRNDUP slightly smarter, where if the length argument is -1, then it uses strlen internally, so we could get away with clients written as: if (VIR_STRNDUP(source->dta.udp.connectService, sv1, host2 ? host2 - svc1 : -1) < 0) After all, we've done magic like that for virBufferAdd (pass -1 instead of strlen, and virBuffer does the right thing on your behalf). But if we DO decide to add the magic, it should be in a standalone patch and with a testsuite addition.
@@ -9472,37 +9420,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))
Again, looks nicer as: if (VIR_STRNDUP(source->data.tcp.service, svc, opt ? opt - svc : strlen(svc)) < 0) [okay, so maybe the magic -1 really is nicer than making clients write strlen]
+ 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))
and another site
@@ -9555,13 +9491,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))
and another site
@@ -9584,13 +9516,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))
and another
@@ -9648,13 +9576,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;
and another.
@@ -10843,7 +10751,7 @@ static int qemuParseProcFileStrings(int pid_value, str[nstr-1] = NULL;
ret = nstr-1; - *list = str; + *list = (const char **) str;
Bummer that C's type system makes us add casts, but this one is correct - nothing you can do about it.
+++ b/src/qemu/qemu_conf.c @@ -1237,8 +1233,8 @@ qemuAddSharedDevice(virQEMUDriverPtr driver, if (!(new_entry = qemuSharedDeviceEntryCopy(entry))) goto cleanup;
- if ((VIR_EXPAND_N(new_entry->domains, new_entry->ref, 1) < 0) || - !(new_entry->domains[new_entry->ref - 1] = strdup(name))) { + if (VIR_EXPAND_N(new_entry->domains, new_entry->ref, 1) < 0 || + VIR_STRDUP(new_entry->domains[new_entry->ref - 1], name) < 0) { qemuSharedDeviceEntryFree(new_entry, NULL); virReportOOMError();
double-oom, but that's okay since a later pass over VIR_EXPAND_N will also touch this code.
@@ -1249,9 +1245,9 @@ qemuAddSharedDevice(virQEMUDriverPtr driver, goto cleanup; } } else { - if ((VIR_ALLOC(entry) < 0) || - (VIR_ALLOC_N(entry->domains, 1) < 0) || - !(entry->domains[0] = strdup(name))) { + if (VIR_ALLOC(entry) < 0 || + VIR_ALLOC_N(entry->domains, 1) < 0 || + VIR_STRDUP(entry->domains[0], name) < 0) { qemuSharedDeviceEntryFree(entry, NULL); virReportOOMError();
another double-oom, also okay.
+++ b/src/qemu/qemu_driver.c @@ -11250,9 +11223,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();
double-oom, but okay because of a later cleanup pass on virAsprintf
+++ b/src/qemu/qemu_process.c @@ -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"));
Since we only use msg in a VIR_DEBUG, this should use VIR_STRDUP_QUIET and update the message to use NULLSTR(msg) (ie. no need to report an OOM back to the user just because we failed to print a debug message).
} 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"));
same story here.
} 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"));
and here. The debug message in question, a few lines later, is: VIR_DEBUG("Domain %s %s while its monitor was disconnected;" " changing state to %s (%s)", vm->def->name, msg, virDomainStateTypeToString(newState), virDomainStateReasonToString(newState, newReason)); I pointed out a few ideas for improvement, but didn't spot any serious flaws. ACK with those tweaks. -- 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.2.1

On 05/20/2013 11:55 AM, Michal Privoznik wrote:
--- src/remote/remote_driver.c | 114 +++++++++++++++++---------------------------- 1 file changed, 44 insertions(+), 70 deletions(-)
@@ -497,24 +497,21 @@ doRemoteOpen(virConnectPtr conn, ...
if (conn->uri && conn->uri->user && - !(username = strdup(conn->uri->user))) - goto no_memory; + VIR_STRDUP(username, conn->uri->user) < 0) + goto failed;
Could be simplified to: if (conn->uri && VIR_STRDUP(username, conn->uri->user) < 0)
@@ -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,
Memory leak if sockname was already defined. Must be: if (!sockname && VIR_STRDUP(sockname, ...
@@ -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;
silent->noisy, when we are really just discarding the event on any error. Based on discussion earlier in the series, that means we are polluting the thread-local error object with no one to report it, but that the pollution will be cleaned up on the next real API that we handle. So I think I can live with the change to noisy. However, s/no_memory/error/ would be appropriate. ACK with those fixes. -- 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 | 27 +++++++++------ 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 | 78 +++++++++++++++++++++----------------------- src/rpc/virnettlscontext.c | 26 +++++++-------- 10 files changed, 92 insertions(+), 114 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..7315fdf 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 (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 b2c6e5b..8483cd5 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 @@ -514,22 +515,28 @@ void virNetMessageSaveError(virNetMessageErrorPtr rerr) if (verr) { rerr->code = verr->code; rerr->domain = verr->domain; - if (verr->message && VIR_ALLOC(rerr->message) == 0) - *rerr->message = strdup(verr->message); + 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); - if (verr->str2 && VIR_ALLOC(rerr->str2) == 0) - *rerr->str2 = strdup(verr->str2); - if (verr->str3 && VIR_ALLOC(rerr->str3) == 0) - *rerr->str3 = strdup(verr->str3); + if (verr->str1 && VIR_ALLOC(rerr->str1) == 0 && + VIR_STRDUP_QUIET(*rerr->str1, verr->str1) < 0) + VIR_FREE(verr->str1); + if (verr->str2 && VIR_ALLOC(rerr->str2) == 0 && + VIR_STRDUP_QUIET(*rerr->str2, verr->str2) < 0) + VIR_FREE(verr->str2); + if (verr->str3 && VIR_ALLOC(rerr->str3) == 0 && + VIR_STRDUP_QUIET(*rerr->str3, verr->str3) < 0) + VIR_FREE(verr->str2); 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")); + if (VIR_ALLOC(rerr->message) == 0 && + VIR_STRDUP_QUIET(*rerr->message, + _("Library function returned error but did not set virError")) < 0) + VIR_FREE(rerr->message); 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..eb2fb3e 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 (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 6d7c439..f339259 100644 --- a/src/rpc/virnetserverclient.c +++ b/src/rpc/virnetserverclient.c @@ -693,22 +693,16 @@ virNetServerClientCreateIdentity(virNetServerClientPtr client) #if WITH_SASL if (client->sasl) { const char *identity = virNetSASLSessionGetIdentity(client->sasl); - if (identity && - !(saslname = strdup(identity))) { - virReportOOMError(); + if (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 (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 67eb496..c0c81d0 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")) @@ -1191,10 +1191,8 @@ int virNetSocketGetSELinuxContext(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 189d928..c28a395 100644 --- a/src/rpc/virnetsshsession.c +++ b/src/rpc/virnetsshsession.c @@ -234,7 +234,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; } @@ -739,7 +739,7 @@ virNetSSHAuthenticateKeyboardInteractive(virNetSSHSessionPtr sess, "authentication credentials")); return -1; case VIR_NET_SSH_AUTHCB_OOM: - virReportOOMError(); + /* OOM error already reported */ return -1; case VIR_NET_SSH_AUTHCB_RETR_ERR: virReportError(VIR_ERR_SSH, "%s", @@ -960,12 +960,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; @@ -974,10 +976,9 @@ virNetSSHSessionAuthAddPasswordAuth(virNetSSHSessionPtr sess, virObjectUnlock(sess); return 0; -no_memory: +error: VIR_FREE(user); VIR_FREE(pass); - virReportOOMError(); virObjectUnlock(sess); return -1; } @@ -998,11 +999,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; @@ -1010,9 +1013,8 @@ virNetSSHSessionAuthAddAgentAuth(virNetSSHSessionPtr sess, virObjectUnlock(sess); return 0; -no_memory: +error: VIR_FREE(user); - virReportOOMError(); virObjectUnlock(sess); return -1; } @@ -1038,15 +1040,15 @@ 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 || + VIR_STRDUP(pass, password) < 0) + goto error; - if (password && !(pass = strdup(password))) - goto no_memory; - - if (!(auth = virNetSSHSessionAuthMethodNew(sess))) - goto no_memory; + if (!(auth = virNetSSHSessionAuthMethodNew(sess))) { + virReportOOMError(); + goto error; + } auth->username = user; auth->password = pass; @@ -1056,11 +1058,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; } @@ -1082,11 +1083,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; @@ -1095,9 +1098,8 @@ virNetSSHSessionAuthAddKeyboardAuth(virNetSSHSessionPtr sess, virObjectUnlock(sess); return 0; -no_memory: +error: VIR_FREE(user); - virReportOOMError(); virObjectUnlock(sess); return -1; @@ -1112,10 +1114,8 @@ virNetSSHSessionSetChannelCommand(virNetSSHSessionPtr sess, VIR_FREE(sess->channelCommand); - if (command && !(sess->channelCommand = strdup(command))) { - virReportOOMError(); + if (VIR_STRDUP(sess->channelCommand, command) < 0) ret = -1; - } virObjectUnlock(sess); return ret; @@ -1138,8 +1138,8 @@ virNetSSHSessionSetHostKeyVerification(virNetSSHSessionPtr sess, VIR_FREE(sess->hostname); - if (hostname && !(sess->hostname = strdup(hostname))) - goto no_memory; + if (VIR_STRDUP(sess->hostname, hostname) < 0) + goto error; /* load the known hosts file */ if (hostsfile) { @@ -1163,16 +1163,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 1a7ccb8..4a31ff6 100644 --- a/src/rpc/virnettlscontext.c +++ b/src/rpc/virnettlscontext.c @@ -837,23 +837,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); @@ -863,6 +863,7 @@ static int virNetTLSContextLocateCredentials(const char *pkipath, out_of_memory: virReportOOMError(); +error: VIR_FREE(*cacert); VIR_FREE(*cacrl); VIR_FREE(*key); @@ -1029,10 +1030,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, @@ -1169,11 +1168,8 @@ virNetTLSSessionPtr virNetTLSSessionNew(virNetTLSContextPtr ctxt, if (!(sess = virObjectLockableNew(virNetTLSSessionClass))) return NULL; - if (hostname && - !(sess->hostname = strdup(hostname))) { - virReportOOMError(); + if (VIR_STRDUP(sess->hostname, hostname) < 0) goto error; - } if ((err = gnutls_init(&sess->session, ctxt->isServer ? GNUTLS_SERVER : GNUTLS_CLIENT)) != 0) { -- 1.8.2.1

On 05/20/2013 11:55 AM, Michal Privoznik wrote:
--- src/rpc/gendispatch.pl | 21 ++++-------- src/rpc/virnetclient.c | 16 ++++----- src/rpc/virnetmessage.c | 27 +++++++++------ 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 | 78 +++++++++++++++++++++----------------------- src/rpc/virnettlscontext.c | 26 +++++++-------- 10 files changed, 92 insertions(+), 114 deletions(-)
ACK. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On 23.05.2013 00:26, Eric Blake wrote:
On 05/20/2013 11:55 AM, Michal Privoznik wrote:
--- src/rpc/gendispatch.pl | 21 ++++-------- src/rpc/virnetclient.c | 16 ++++----- src/rpc/virnetmessage.c | 27 +++++++++------ 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 | 78 +++++++++++++++++++++----------------------- src/rpc/virnettlscontext.c | 26 +++++++-------- 10 files changed, 92 insertions(+), 114 deletions(-)
ACK.
Since 04/13 got NACKed, I needed to squash this in before pushing. diff --git a/src/rpc/virnetsshsession.c b/src/rpc/virnetsshsession.c index c28a395..b6aedc8 100644 --- a/src/rpc/virnetsshsession.c +++ b/src/rpc/virnetsshsession.c @@ -234,10 +234,12 @@ virNetSSHKbIntCb(const char *name ATTRIBUTE_UNUSED, /* fill data structures for auth callback */ for (i = 0; i < num_prompts; i++) { - if (VIR_STRDUP(askcred[i].prompt, prompts[i].text) < 0) { + char *prompt; + if (VIR_STRDUP(prompt, prompts[i].text) < 0) { priv->authCbErr = VIR_NET_SSH_AUTHCB_OOM; goto cleanup; } + askcred[i].prompt = prompt; /* remove colon and trailing spaces from prompts, as default behavior * of libvirt's auth callback is to add them */ Michal

On 05/20/2013 01:55 PM, Michal Privoznik wrote:
--- src/rpc/gendispatch.pl | 21 ++++-------- src/rpc/virnetclient.c | 16 ++++----- src/rpc/virnetmessage.c | 27 +++++++++------ 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 | 78 +++++++++++++++++++++----------------------- src/rpc/virnettlscontext.c | 26 +++++++-------- 10 files changed, 92 insertions(+), 114 deletions(-)
diff --git a/src/rpc/gendispatch.pl b/src/rpc/gendispatch.pl [...snip...]
diff --git a/src/rpc/virnetmessage.c b/src/rpc/virnetmessage.c index b2c6e5b..8483cd5 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
@@ -514,22 +515,28 @@ void virNetMessageSaveError(virNetMessageErrorPtr rerr) if (verr) { rerr->code = verr->code; rerr->domain = verr->domain; - if (verr->message && VIR_ALLOC(rerr->message) == 0) - *rerr->message = strdup(verr->message); + 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); - if (verr->str2 && VIR_ALLOC(rerr->str2) == 0) - *rerr->str2 = strdup(verr->str2); - if (verr->str3 && VIR_ALLOC(rerr->str3) == 0) - *rerr->str3 = strdup(verr->str3); + if (verr->str1 && VIR_ALLOC(rerr->str1) == 0 && + VIR_STRDUP_QUIET(*rerr->str1, verr->str1) < 0) + VIR_FREE(verr->str1); + if (verr->str2 && VIR_ALLOC(rerr->str2) == 0 && + VIR_STRDUP_QUIET(*rerr->str2, verr->str2) < 0) + VIR_FREE(verr->str2); + if (verr->str3 && VIR_ALLOC(rerr->str3) == 0 && + VIR_STRDUP_QUIET(*rerr->str3, verr->str3) < 0) + VIR_FREE(verr->str2);
Coverity has a complaint in here: 525 if (verr->str2 && VIR_ALLOC(rerr->str2) == 0 && 526 VIR_STRDUP_QUIET(*rerr->str2, verr->str2) < 0) (1) Event original: "verr->str2" looks like the original copy. Also see events: [copy_paste_error] 527 VIR_FREE(verr->str2); 528 if (verr->str3 && VIR_ALLOC(rerr->str3) == 0 && 529 VIR_STRDUP_QUIET(*rerr->str3, verr->str3) < 0) (2) Event copy_paste_error: "str2" in "verr->str2" looks like a copy-paste error. Should it say "str3" instead? Also see events: [original] 530 VIR_FREE(verr->str2); 531 rerr->int1 = verr->int1; 532 rerr->int2 = verr->int2; The complaint is only on the last VIR_FREE(verr->str2); as a cut-n-paste of the one on line 527; however, it seems to me all those VIR_FREE()'s should be on "rerr" and not "verr", right? That is, there's a VIR_ALLOC(rerr->str#) for each section, then on failure shouldn't it be VIR_FREE(rerr->str#)? John
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")); + if (VIR_ALLOC(rerr->message) == 0 && + VIR_STRDUP_QUIET(*rerr->message, + _("Library function returned error but did not set virError")) < 0) + VIR_FREE(rerr->message); rerr->level = VIR_ERR_ERROR; } }
[...snip...]

--- src/security/security_apparmor.c | 20 ++-------- src/security/security_dac.c | 21 +++-------- src/security/security_nop.c | 7 +--- src/security/security_selinux.c | 79 +++++++++++----------------------------- src/security/virt-aa-helper.c | 4 +- 5 files changed, 35 insertions(+), 96 deletions(-) diff --git a/src/security/security_apparmor.c b/src/security/security_apparmor.c index 3680279..87c2777 100644 --- a/src/security/security_apparmor.c +++ b/src/security/security_apparmor.c @@ -445,24 +445,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 cleanup; - } /* 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) { @@ -949,10 +940,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 6e6fcad..543ddeb 100644 --- a/src/security/security_dac.c +++ b/src/security/security_dac.c @@ -78,11 +78,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, ':'); @@ -1104,18 +1101,10 @@ 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 && + VIR_STRDUP(seclabel->imagelabel, seclabel->label) < 0) { + VIR_FREE(seclabel->label); + 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 5d108b9..2d67652 100644 --- a/src/security/security_selinux.c +++ b/src/security/security_selinux.c @@ -203,10 +203,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, ':'); @@ -313,10 +311,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); @@ -386,10 +381,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); @@ -452,17 +445,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; @@ -521,11 +507,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'; @@ -545,11 +528,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'; @@ -644,11 +624,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: @@ -712,10 +693,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; @@ -1413,10 +1392,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); @@ -1431,10 +1408,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); @@ -1607,10 +1582,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); @@ -1625,10 +1598,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); @@ -2414,7 +2385,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) @@ -2428,11 +2399,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; @@ -2440,9 +2408,9 @@ virSecuritySELinuxGenImageLabel(virSecurityManagerPtr mgr, } cleanup: - context_free(ctx); - VIR_FREE(mcs); - return label; + context_free(ctx); + VIR_FREE(mcs); + return label; } static char * @@ -2465,11 +2433,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 5d48850..cee18f1 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.2.1

On 05/20/2013 11:55 AM, Michal Privoznik wrote:
--- src/security/security_apparmor.c | 20 ++-------- src/security/security_dac.c | 21 +++-------- src/security/security_nop.c | 7 +--- src/security/security_selinux.c | 79 +++++++++++----------------------------- src/security/virt-aa-helper.c | 4 +- 5 files changed, 35 insertions(+), 96 deletions(-)
ACK. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On 23.05.2013 00:42, Eric Blake wrote:
On 05/20/2013 11:55 AM, Michal Privoznik wrote:
--- src/security/security_apparmor.c | 20 ++-------- src/security/security_dac.c | 21 +++-------- src/security/security_nop.c | 7 +--- src/security/security_selinux.c | 79 +++++++++++----------------------------- src/security/virt-aa-helper.c | 4 +- 5 files changed, 35 insertions(+), 96 deletions(-)
ACK.
Thanks, pushed this far. Michal

--- src/util/virauth.c | 17 +-- src/util/virauthconfig.c | 8 +- src/util/virbitmap.c | 9 +- src/util/vircgroup.c | 37 ++--- 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/virfile.c | 28 ++-- src/util/virhash.c | 5 +- src/util/viridentity.c | 14 +- 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 | 27 ++-- src/util/virnetdevmacvlan.c | 16 +-- src/util/virnetdevtap.c | 11 +- src/util/virnetdevvportprofile.c | 4 +- src/util/virobject.c | 16 ++- src/util/virpci.c | 13 +- src/util/virscsi.c | 6 +- src/util/virsexpr.c | 37 ++--- src/util/virsocketaddr.c | 9 +- src/util/virstoragefile.c | 18 +-- src/util/virstring.c | 17 +-- src/util/virsysinfo.c | 293 +++++++++++++++------------------------ src/util/virtypedparam.c | 14 +- src/util/viruri.c | 58 ++++---- src/util/virutil.c | 57 +++----- src/util/virxml.c | 5 +- 34 files changed, 357 insertions(+), 570 deletions(-) diff --git a/src/util/virauth.c b/src/util/virauth.c index fdcefe1..e4bc11a 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 (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 07ea2c3..101d28c 100644 --- a/src/util/vircgroup.c +++ b/src/util/vircgroup.c @@ -116,19 +116,13 @@ 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 (VIR_STRDUP(group->controllers[i].linkPoint, + parent->controllers[i].linkPoint) < 0) + return -ENOMEM; } return 0; } @@ -177,7 +171,7 @@ static int virCgroupDetectMounts(virCgroupPtr group) struct stat sb; char *tmp2; - if (!(group->controllers[i].mountPoint = strdup(entry.mnt_dir))) + if (VIR_STRDUP(group->controllers[i].mountPoint, entry.mnt_dir) < 0) goto no_memory; tmp2 = strrchr(entry.mnt_dir, '/'); @@ -239,7 +233,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 +815,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,8 +1021,8 @@ static int virCgroupAddTaskStrController(virCgroupPtr group, int rc = 0; char *endp; - if (!(str = strdup(pidstr))) - return -1; + if (VIR_STRDUP(str, pidstr) < 0) + return -ENOMEM; cur = str; while (*cur != '\0') { @@ -1266,7 +1260,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; } @@ -2555,13 +2549,8 @@ static char *virCgroupIdentifyRoot(virCgroupPtr group) return NULL; } - tmp[0] = '\0'; - ret = strdup(group->controllers[i].mountPoint); - tmp[0] = '/'; - if (!ret) { - virReportOOMError(); - return NULL; - } + ignore_value(VIR_STRNDUP(ret, group->controllers[i].mountPoint, + tmp - group->controllers[i].mountPoint)); return ret; } diff --git a/src/util/vircommand.c b/src/util/vircommand.c index f6f27d9..246e146 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 (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 (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 3834ea8..9c95d57 100644 --- a/src/util/virebtables.c +++ b/src/util/virebtables.c @@ -52,6 +52,8 @@ #include "virstring.h" #include "virutil.h" +#define VIR_FROM_THIS VIR_FROM_NONE + #if HAVE_FIREWALLD static char *firewall_cmd_path = NULL; @@ -114,7 +116,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) { @@ -187,10 +189,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; @@ -208,7 +210,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; @@ -237,36 +239,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; } @@ -274,16 +276,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 4e1dc9a..1706630 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; @@ -667,7 +668,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); @@ -687,11 +688,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/virfile.c b/src/util/virfile.c index 4637919..a05e9ea 100644 --- a/src/util/virfile.c +++ b/src/util/virfile.c @@ -1059,7 +1059,7 @@ virFileFindMountPoint(const char *type) while (getmntent_r(f, &mb, mntbuf, sizeof(mntbuf))) { if (STREQ(mb.mnt_type, type)) { - ret = strdup(mb.mnt_dir); + ignore_value(VIR_STRDUP(ret, mb.mnt_dir)); goto cleanup; } } @@ -1299,11 +1299,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) < 0 ? -1 : 0 ; } *resultpath = canonicalize_file_name(linkpath); @@ -1377,10 +1374,10 @@ virFindFileInPath(const char *file) * copy of that path, after validating that it is executable */ if (IS_ABSOLUTE_FILE_NAME(file)) { + char *ret = NULL; if (virFileIsExecutable(file)) - return strdup(file); - else - return NULL; + ignore_value(VIR_STRDUP(ret, file)); + return ret; } /* If we are passed an anchored path (containing a /), then there @@ -1395,7 +1392,7 @@ virFindFileInPath(const char *file) /* copy PATH env so we can tweak it */ path = getenv("PATH"); - if (path == NULL || (path = strdup(path)) == NULL) + if (VIR_STRDUP(path, path) <= 0) return NULL; /* for each path segment, append the file to search for and test for @@ -2047,8 +2044,10 @@ virFileMakePathWithMode(const char *path, int ret = -1; char *tmp; - if ((tmp = strdup(path)) == NULL) + if (VIR_STRDUP(tmp, path) < 0) { + errno = ENOMEM; goto cleanup; + } ret = virFileMakePathHelper(tmp, mode); @@ -2257,7 +2256,7 @@ virFileAbsPath(const char *path, char **abspath) char *buf; if (path[0] == '/') { - if (!(*abspath = strdup(path))) + if (VIR_STRDUP(*abspath, path) < 0) return -1; } else { buf = getcwd(NULL, 0); @@ -2282,11 +2281,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: * // -> // 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 840485a..10334da 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); + if (VIR_STRDUP(seccontext, con) < 0) { + freecon(con); + goto cleanup; + } freecon(con); - if (!seccontext) { - virReportOOMError(); - goto cleanup; - } #endif if (!(ret = virIdentityNew())) @@ -246,10 +246,8 @@ int virIdentitySetAttr(virIdentityPtr ident, goto cleanup; } - if (!(ident->attrs[attr] = strdup(value))) { - virReportOOMError(); + if (VIR_STRDUP(ident->attrs[attr], value) < 0) goto cleanup; - } ret = 0; 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 b0fe2b0..16fbe9c 100644 --- a/src/util/viriptables.c +++ b/src/util/viriptables.c @@ -119,10 +119,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 9410b66..6b632c6 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, @@ -783,10 +783,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); @@ -840,8 +840,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; } @@ -1126,8 +1125,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 1732d0c..b6220bc 100644 --- a/src/util/virkeyfile.c +++ b/src/util/virkeyfile.c @@ -33,6 +33,7 @@ #include "virhash.h" #include "virkeyfile.h" #include "virerror.h" +#include "virstring.h" #define VIR_FROM_THIS VIR_FROM_CONF @@ -122,10 +123,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; @@ -168,10 +167,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; @@ -184,10 +181,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..b7a1c35 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 (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 62ff838..d939d71 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_QUIET(mdup, match) < 0) { i = -1; goto cleanup; } @@ -574,6 +573,8 @@ virLogDefineFilter(const char *match, virLogNbFilters++; cleanup: virLogUnlock(); + if (i < 0) + virReportOOMError(); return i; } @@ -664,13 +665,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) && + VIR_STRDUP(ndup, name) <= 0) + return -1; virLogLock(); if (VIR_REALLOC_N(virLogOutputs, virLogNbOutputs + 1)) { @@ -1047,8 +1044,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 +1325,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 +1341,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 +1418,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 5316520..a72b68c 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; @@ -924,16 +925,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..10566a1 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) < 0 ? -1 : 0; #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..cdc33c9 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,10 +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 + if (VIR_STRDUP(*netname, entry->d_name) > 0) ret = 0; break; } diff --git a/src/util/virscsi.c b/src/util/virscsi.c index bdd06fd..4870307 100644 --- a/src/util/virscsi.c +++ b/src/util/virscsi.c @@ -177,10 +177,8 @@ virSCSIDeviceGetDevName(const char *adapter, if (entry->d_name[0] == '.') continue; - if (!(name = strdup(entry->d_name))) { - virReportOOMError(); - goto cleanup; - } + ignore_value(VIR_STRDUP(name, entry->d_name)); + break; } cleanup: diff --git a/src/util/virsexpr.c b/src/util/virsexpr.c index 23b6781..fea1928 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) < 0 ? -1 : 0; + + *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 0c43397..9ef9dd4 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 1640d8c..1dd66e4 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 686cd49..4868a5f 100644 --- a/src/util/virsysinfo.c +++ b/src/util/virsysinfo.c @@ -145,32 +145,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 @@ -186,43 +180,37 @@ 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_STRNDUP(processor->processor_version, + cur, eol - cur) < 0) + return -1; } base = cur; } return 0; - -no_memory: - return -1; } /* virSysinfoRead for PowerPC @@ -271,32 +259,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 @@ -314,10 +296,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) { @@ -326,19 +306,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; } @@ -346,7 +327,7 @@ virSysinfoParseProcessor(const char *base, virSysinfoDefPtr ret) VIR_FREE(processor_type); return 0; -no_memory: +error: VIR_FREE(processor_type); return -1; } @@ -409,15 +390,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; } @@ -463,7 +440,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, '=', ',') || @@ -557,32 +535,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 @@ -597,51 +572,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 @@ -655,117 +626,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 @@ -779,9 +733,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) { @@ -791,87 +744,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: @@ -879,9 +819,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..bf374a6 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 (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..c0ee472 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 (VIR_STRDUP(ret->scheme, xmluri->scheme) < 0) + goto error; + if (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 (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 (VIR_STRDUP(ret->query, xmluri->query_raw) < 0) + goto error; #else - if (xmluri->query && - !(ret->query = strdup(xmluri->query))) - goto no_memory; + if (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 (VIR_STRDUP(ret->fragment, xmluri->fragment) < 0) + goto error; + if (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 7f4ecd6..29df561 100644 --- a/src/util/virutil.c +++ b/src/util/virutil.c @@ -609,8 +609,8 @@ char *virGetHostname(void) * 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 @@ -624,8 +624,8 @@ char *virGetHostname(void) 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. */ @@ -637,14 +637,14 @@ char *virGetHostname(void) * 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; @@ -698,15 +698,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; } @@ -751,12 +745,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; } @@ -1090,12 +1080,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; @@ -1125,12 +1111,7 @@ virGetWin32DirectoryRoot(char **path) strcpy(windowsdir, "C:\\"); } - if (!(*path = strdup(windowsdir))) { - virReportOOMError(); - ret = -1; - } - - return ret; + return VIR_STRDUP(*path, windowsdir) < 0 ? -1 : 0; } @@ -1163,12 +1144,8 @@ virGetUserDirectory(void) /* USERPROFILE is probably the closest equivalent to $HOME? */ dir = getenv("USERPROFILE"); - if (dir) { - if (!(ret = strdup(dir))) { - virReportOOMError(); - return NULL; - } - } + if (VIR_STRDUP(ret, dir) < 0) + return NULL; if (!ret && virGetWin32SpecialFolder(CSIDL_PROFILE, &ret) < 0) @@ -1920,7 +1897,7 @@ virGetFCHostNameByWWN(const char *sysfs_prefix, continue; } - ret = strdup(entry->d_name); + ignore_value(VIR_STRDUP(ret, entry->d_name)); break; } @@ -2006,7 +1983,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.2.1

On 05/20/2013 11:55 AM, Michal Privoznik wrote:
--- 34 files changed, 357 insertions(+), 570 deletions(-)
I've got my work cut out for me!
@@ -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;
Hmm, I've seen this three-line pattern (declare temp var, strdup "" into it, use the var) in several patches now. I think it might help to have a new function in virstring.h whose job in life is to return a malloc'd copy of an empty string, as a one-liner, so that callers don't have to mess with a temp var. And notice that it's slightly more efficient to just zero-initialize a malloc'd array of 1, instead of going through strdup machinery, when we know the output will be an empty string. Maybe: /* Return a malloc'd empty string, or NULL after reporting OOM */ char * virStringEmpty(void) { char *ret; // assuming we fix VIR_ALLOC to report oom... ignore_value(VIR_ALLOC(ret)); return ret; } then THIS code could use the shorter: if (cur < 0) return virStringEmpty(); But if you decide to go that route, it's probably worth a separate cleanup pass, so this commit is not delayed.
+++ b/src/util/vircgroup.c @@ -116,19 +116,13 @@ 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;
double-oom, since this function was previously silent and callers already expected to do their own error reporting. This whole file has an unusual paradigm compared to most source files, it may be best to split this file into a separate patch (so that you aren't holding up the rest of src/util/*) and either use VIR_STRDUP_QUIET or start to tackle the bigger issue of tracing through callers to behave better when leaf functions report errors.
- if (parent->controllers[i].linkPoint) { - group->controllers[i].linkPoint = - strdup(parent->controllers[i].linkPoint); - - if (!group->controllers[i].linkPoint) - return -ENOMEM; - } + if (VIR_STRDUP(group->controllers[i].linkPoint, + parent->controllers[i].linkPoint) < 0) + return -ENOMEM;
again, double-oom
@@ -177,7 +171,7 @@ static int virCgroupDetectMounts(virCgroupPtr group) struct stat sb; char *tmp2;
- if (!(group->controllers[i].mountPoint = strdup(entry.mnt_dir))) + if (VIR_STRDUP(group->controllers[i].mountPoint, entry.mnt_dir) < 0) goto no_memory;
no_memory label is redudant; VIR_STRDUP guarantees that 'errno == ENOMEM' if it returns -1, as do VIR_ALLOC and virAsprintf. (Hmm, maybe we should enhance './configure --enable-test-oom' to specifically test that; although it may be a surprising amount of work to get that to happen). This is a silent->noisy change, and again an instance where the cgroup callers are doing their own error reporting; and the no_memory label is a bit awkward because it is not doing its own OOM reporting. Just deleting the no_memory label, and using 'goto error' will make the code a bit less confusing. And it reiterates my thought that src/util/vircgroup.c is enough of an oddball to warrant being split into its own patch. So with that, I'll quit pointing out silent->noisy changes in this file, and just point out other problems.
@@ -1027,8 +1021,8 @@ static int virCgroupAddTaskStrController(virCgroupPtr group, int rc = 0; char *endp;
- if (!(str = strdup(pidstr))) - return -1; + if (VIR_STRDUP(str, pidstr) < 0) + return -ENOMEM;
Yikes! Are we mixing -1 and -errno in the same function? That's an independent bug, and probably better to isolate that fix into an independent commit.
+++ 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;
double-oom. More precisely, we DON'T want to report oom until virCommandRun sees cmd->has_error==ENOMEM, so that callers have the option of building up a virCommand but ditching it halfway through if they encounter some other (more important) error. Thus, this should use VIR_STRDUP_QUIET.
@@ -1049,7 +1048,7 @@ virCommandSetSELinuxLabel(virCommandPtr cmd,
#if defined(WITH_SECDRIVER_SELINUX) VIR_FREE(cmd->seLinuxLabel); - if (label && !(cmd->seLinuxLabel = strdup(label))) + if (VIR_STRDUP(cmd->seLinuxLabel, label) < 0) cmd->has_error = ENOMEM;
VIR_STRDUP_QUIET
#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 (VIR_STRDUP(cmd->appArmorProfile, profile) < 0) cmd->has_error = ENOMEM;
QUIET
#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;
QUIET
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;
QUIET
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;
QUIET
+ 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;
QUIET
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;
QUIET
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;
QUIET
} } @@ -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;
QUIET
+++ b/src/util/virebtables.c @@ -187,10 +189,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;
silent->noisy, caller was already doing its own reporting based on errno value. Probably a good change, but it means we probably ought to eventually touch up qemuStateInitialize to not duplicate error handling.
@@ -237,36 +239,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;
Not for this patch, but why are we building up argv manually instead of using virCommand?
+++ 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"))); }
This use of QUIET is correct.
@@ -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)
Simplify: if (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)
and so on.
@@ -687,11 +688,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));
Can lose the surrounding if.
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));
and so on.
+++ b/src/util/virfile.c @@ -1059,7 +1059,7 @@ virFileFindMountPoint(const char *type)
while (getmntent_r(f, &mb, mntbuf, sizeof(mntbuf))) { if (STREQ(mb.mnt_type, type)) { - ret = strdup(mb.mnt_dir); + ignore_value(VIR_STRDUP(ret, mb.mnt_dir)); goto cleanup;
silent->noisy. This function has a bug: it says it returns NULL with errno set, but then it does: if (!ret) errno = ENOENT; cleanup: endmntent(f); return ret; and endmntent is allowed to clobber errno. But I think the intent is that we DO want this function to be silent (meaning this should use QUIET), because some callers ignore certain errors.
@@ -1299,11 +1299,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) < 0 ? -1 : 0 ;
silent->noisy; looks like it needs to use _QUIET because callers ignore some errors.
@@ -1377,10 +1374,10 @@ virFindFileInPath(const char *file) * copy of that path, after validating that it is executable */ if (IS_ABSOLUTE_FILE_NAME(file)) { + char *ret = NULL; if (virFileIsExecutable(file)) - return strdup(file); - else - return NULL; + ignore_value(VIR_STRDUP(ret, file));
silent->noisy; I think some callers ignore failure, so QUIET may be better.
@@ -1395,7 +1392,7 @@ virFindFileInPath(const char *file) /* copy PATH env so we can tweak it */ path = getenv("PATH");
- if (path == NULL || (path = strdup(path)) == NULL) + if (VIR_STRDUP(path, path) <= 0) return NULL;
and again.
@@ -2047,8 +2044,10 @@ virFileMakePathWithMode(const char *path, int ret = -1; char *tmp;
- if ((tmp = strdup(path)) == NULL) + if (VIR_STRDUP(tmp, path) < 0) { + errno = ENOMEM; goto cleanup; + }
silent->noisy, but this one is probably okay.
@@ -2257,7 +2256,7 @@ virFileAbsPath(const char *path, char **abspath) char *buf;
if (path[0] == '/') { - if (!(*abspath = strdup(path))) + if (VIR_STRDUP(*abspath, path) < 0) return -1;
silent->noisy, but probably okay
+++ b/src/util/viriptables.c @@ -119,10 +119,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;
silent->noisy; probably okay, but we should adjust callers at some point
+++ 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;
silent->noisy, but probably a good change. True for most of this file.
+++ b/src/util/virlog.c @@ -557,8 +557,7 @@ virLogDefineFilter(const char *match, } }
- mdup = strdup(match); - if (mdup == NULL) { + if (VIR_STRDUP_QUIET(mdup, match) < 0) { i = -1; goto cleanup; } @@ -574,6 +573,8 @@ virLogDefineFilter(const char *match, virLogNbFilters++; cleanup: virLogUnlock(); + if (i < 0) + virReportOOMError();
silent->noisy; there are other failure paths where we are still silent, but it's probably better to be noisy. I think you did this construct so that teh VIR_ALLOC_N also converts from silent->noisy, where a future OOM cleanup path would then switch to VIR_STRDUP instead of VIR_STRDUP_QUIET, although I'd rather live with double-oom now than forget to drop QUIET later.
@@ -664,13 +665,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) && + VIR_STRDUP(ndup, name) <= 0) + return -1;
Hmm; this means you are silent->noisy on OOM, but still silent if name was NULL. It might be better to be consistently noisy, even if that means you can't use the <= as planned.
@@ -1047,8 +1044,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;
silent->noisy, but probably good
@@ -1329,8 +1325,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;
silent->noisy, but rest of function isn't consistently noisy
+++ 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;
As long as you are touching this, kill the double space.
+++ 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))
if (VIR_STRNDUP(ret->u.value, str, len > 0 ? len : strlen(str)) < 0)
+++ b/src/util/virstring.c @@ -109,6 +109,7 @@ char **virStringSplit(const char *string,
no_memory: virReportOOMError(); +error: for (i = 0 ; i < ntokens ; i++)
Might have a merge conflict with the semicolon cleanup.
+++ b/src/util/virsysinfo.c @@ -145,32 +145,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;
silent->noisy, but probably a good change.
@@ -186,43 +180,37 @@ 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;
silent->noisy, but probably good
@@ -271,32 +259,26 @@ virSysinfoParseSystem(const char *base, virSysinfoDefPtr ret) @@ -314,10 +296,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;
and more silent->noisy; probably the whole file is impacted.
base = cur;
while ((tmp_base = strstr(base, "processor")) != NULL) { @@ -326,19 +306,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; }
Another silent->noisy, and here you were dealing with VIR_EXPAND_N.
@@ -463,7 +440,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;
silent->noisy, but probably good. Everything else looked good. There were a few problems to fix up before pushing, and maybe it's worth resubmitting vircgroup cleanups (or doing an explicit followup), but I can live with giving: ACK I agree that we want this series in before we freeze. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On 23.05.2013 23:10, Eric Blake wrote:
On 05/20/2013 11:55 AM, Michal Privoznik wrote:
--- 34 files changed, 357 insertions(+), 570 deletions(-)
I've got my work cut out for me!
@@ -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;
Hmm, I've seen this three-line pattern (declare temp var, strdup "" into it, use the var) in several patches now. I think it might help to have a new function in virstring.h whose job in life is to return a malloc'd copy of an empty string, as a one-liner, so that callers don't have to mess with a temp var. And notice that it's slightly more efficient to just zero-initialize a malloc'd array of 1, instead of going through strdup machinery, when we know the output will be an empty string. Maybe:
/* Return a malloc'd empty string, or NULL after reporting OOM */ char * virStringEmpty(void) { char *ret; // assuming we fix VIR_ALLOC to report oom... ignore_value(VIR_ALLOC(ret)); return ret; }
then THIS code could use the shorter:
if (cur < 0) return virStringEmpty();
But if you decide to go that route, it's probably worth a separate cleanup pass, so this commit is not delayed.
+++ b/src/util/vircgroup.c @@ -116,19 +116,13 @@ 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;
double-oom, since this function was previously silent and callers already expected to do their own error reporting. This whole file has an unusual paradigm compared to most source files, it may be best to split this file into a separate patch (so that you aren't holding up the rest of src/util/*) and either use VIR_STRDUP_QUIET or start to tackle the bigger issue of tracing through callers to behave better when leaf functions report errors.
- if (parent->controllers[i].linkPoint) { - group->controllers[i].linkPoint = - strdup(parent->controllers[i].linkPoint); - - if (!group->controllers[i].linkPoint) - return -ENOMEM; - } + if (VIR_STRDUP(group->controllers[i].linkPoint, + parent->controllers[i].linkPoint) < 0) + return -ENOMEM;
again, double-oom
@@ -177,7 +171,7 @@ static int virCgroupDetectMounts(virCgroupPtr group) struct stat sb; char *tmp2;
- if (!(group->controllers[i].mountPoint = strdup(entry.mnt_dir))) + if (VIR_STRDUP(group->controllers[i].mountPoint, entry.mnt_dir) < 0) goto no_memory;
no_memory label is redudant; VIR_STRDUP guarantees that 'errno == ENOMEM' if it returns -1, as do VIR_ALLOC and virAsprintf. (Hmm, maybe we should enhance './configure --enable-test-oom' to specifically test that; although it may be a surprising amount of work to get that to happen). This is a silent->noisy change, and again an instance where the cgroup callers are doing their own error reporting; and the no_memory label is a bit awkward because it is not doing its own OOM reporting. Just deleting the no_memory label, and using 'goto error' will make the code a bit less confusing. And it reiterates my thought that src/util/vircgroup.c is enough of an oddball to warrant being split into its own patch.
So with that, I'll quit pointing out silent->noisy changes in this file, and just point out other problems.
Okay, I've separated vircgroup.c into its specific commit and s/VIR_STRDUP/VIR_STRNDUP/ within it. The whole file seems a bit awkward to me to say the least. The less I have to touch it the better :) Michal

--- 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 | 68 ++++++++++++------------------------------------ src/xen/xm_internal.c | 9 +++---- src/xen/xs_internal.c | 44 ++++++++++++------------------- 7 files changed, 56 insertions(+), 124 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 cc54f7a..84a9fcc 100644 --- a/src/xen/xen_driver.c +++ b/src/xen/xen_driver.c @@ -408,10 +408,8 @@ xenUnifiedConnectOpen(virConnectPtr conn, virConnectAuthPtr auth, unsigned int f priv->opened[XEN_UNIFIED_INOTIFY_OFFSET] = 1; #endif - if (!(priv->saveDir = strdup(XEN_SAVE_DIR))) { - virReportOOMError(); + if (VIR_STRDUP(priv->saveDir, XEN_SAVE_DIR) < 0) goto error; - } if (virFileMakePath(priv->saveDir) < 0) { VIR_ERROR(_("Errored to create save dir '%s': %s"), priv->saveDir, @@ -2165,8 +2163,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; @@ -2182,6 +2180,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 68a3ef4..590575e 100644 --- a/src/xen/xen_hypervisor.c +++ b/src/xen/xen_hypervisor.c @@ -1141,16 +1141,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; @@ -2534,14 +2530,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 e13c572..0b2c622 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 @@ -58,12 +58,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; @@ -103,11 +100,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; @@ -118,8 +112,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 aec57f5..96758cc 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++; } @@ -1384,14 +1383,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); @@ -2100,12 +2093,7 @@ xenDaemonLookupByUUID(virConnectPtr conn, const unsigned char *uuid) else id = -1; - if (domname) { - name = strdup(domname); - - if (name == NULL) - virReportOOMError(); - } + ignore_value(VIR_STRDUP(name, domname)); sexpr_free(root); } @@ -2260,12 +2248,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: @@ -2279,10 +2264,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: @@ -2586,12 +2569,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, @@ -2750,9 +2730,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; } @@ -2772,19 +2750,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); @@ -2938,10 +2910,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; @@ -2997,19 +2967,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 66a6c4c..e64a9dd 100644 --- a/src/xen/xm_internal.c +++ b/src/xen/xm_internal.c @@ -241,8 +241,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; } @@ -1047,10 +1046,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) { @@ -1140,7 +1137,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 496c30b..eab18f1 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 @@ -428,11 +429,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; } } @@ -481,10 +478,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); @@ -504,10 +498,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); @@ -559,7 +550,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; } } @@ -665,22 +656,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; @@ -688,15 +679,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.2.1

On 05/20/2013 07:55 PM, Michal Privoznik wrote:
--- 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 | 68 ++++++++++++------------------------------------ src/xen/xm_internal.c | 9 +++---- src/xen/xs_internal.c | 44 ++++++++++++------------------- 7 files changed, 56 insertions(+), 124 deletions(-)
diff --git a/src/xen/xm_internal.c b/src/xen/xm_internal.c index 66a6c4c..e64a9dd 100644 --- a/src/xen/xm_internal.c +++ b/src/xen/xm_internal.c @@ -1140,7 +1137,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)
VIR_STRDUP_QUIET
ctx->oom = 1; else ctx->count++;
diff --git a/src/xen/xs_internal.c b/src/xen/xs_internal.c index 496c30b..eab18f1 100644 --- a/src/xen/xs_internal.c +++ b/src/xen/xs_internal.c @@ -559,7 +550,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; } }
This changes it from quiet to noisy, but none of the callers report an OOM error. ACK Jan

On 23.05.2013 13:28, Ján Tomko wrote:
On 05/20/2013 07:55 PM, Michal Privoznik wrote:
--- 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 | 68 ++++++++++++------------------------------------ src/xen/xm_internal.c | 9 +++---- src/xen/xs_internal.c | 44 ++++++++++++------------------- 7 files changed, 56 insertions(+), 124 deletions(-)
diff --git a/src/xen/xm_internal.c b/src/xen/xm_internal.c index 66a6c4c..e64a9dd 100644 --- a/src/xen/xm_internal.c +++ b/src/xen/xm_internal.c @@ -1140,7 +1137,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)
VIR_STRDUP_QUIET
ctx->oom = 1; else ctx->count++;
Would it be possible to rather: diff --git a/src/xen/xm_internal.c b/src/xen/xm_internal.c index 41eb928..7c05911 100644 --- a/src/xen/xm_internal.c +++ b/src/xen/xm_internal.c @@ -1171,8 +1171,6 @@ xenXMListDefinedDomains(virConnectPtr conn, char **const names, int maxnames) if (ctx.oom) { for (i = 0; i < ctx.count; i++) VIR_FREE(ctx.names[i]); - - virReportOOMError(); goto cleanup; } Michal

On 05/23/2013 05:07 PM, Michal Privoznik wrote:
On 23.05.2013 13:28, Ján Tomko wrote:
On 05/20/2013 07:55 PM, Michal Privoznik wrote:
--- 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 | 68 ++++++++++++------------------------------------ src/xen/xm_internal.c | 9 +++---- src/xen/xs_internal.c | 44 ++++++++++++------------------- 7 files changed, 56 insertions(+), 124 deletions(-)
diff --git a/src/xen/xm_internal.c b/src/xen/xm_internal.c index 66a6c4c..e64a9dd 100644 --- a/src/xen/xm_internal.c +++ b/src/xen/xm_internal.c @@ -1140,7 +1137,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)
VIR_STRDUP_QUIET
ctx->oom = 1; else ctx->count++;
Would it be possible to rather:
diff --git a/src/xen/xm_internal.c b/src/xen/xm_internal.c index 41eb928..7c05911 100644 --- a/src/xen/xm_internal.c +++ b/src/xen/xm_internal.c @@ -1171,8 +1171,6 @@ xenXMListDefinedDomains(virConnectPtr conn, char **const names, int maxnames) if (ctx.oom) { for (i = 0; i < ctx.count; i++) VIR_FREE(ctx.names[i]); - - virReportOOMError(); goto cleanup; }
Sure, I don't see why it wouldn't. Jan

On 05/23/2013 09:07 AM, Michal Privoznik wrote:
Would it be possible to rather:
diff --git a/src/xen/xm_internal.c b/src/xen/xm_internal.c index 41eb928..7c05911 100644 --- a/src/xen/xm_internal.c +++ b/src/xen/xm_internal.c @@ -1171,8 +1171,6 @@ xenXMListDefinedDomains(virConnectPtr conn, char **const names, int maxnames) if (ctx.oom) { for (i = 0; i < ctx.count; i++) VIR_FREE(ctx.names[i]); - - virReportOOMError(); goto cleanup;
Yes, I like that better. ACK with that change. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

--- 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..cc8da49 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.2.1

On 05/20/2013 07:55 PM, Michal Privoznik wrote:
--- src/xenapi/xenapi_driver.c | 59 ++++++++++++++++++++-------------------------- src/xenapi/xenapi_utils.c | 39 +++++++++++++++--------------- 2 files changed, 46 insertions(+), 52 deletions(-)
ACK Jan

--- src/xenxs/xen_sxpr.c | 200 ++++++++++++++++++++++----------------------------- src/xenxs/xen_xm.c | 91 +++++++++++------------ 2 files changed, 125 insertions(+), 166 deletions(-) diff --git a/src/xenxs/xen_sxpr.c b/src/xenxs/xen_sxpr.c index 9a76d04..aa99a61 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 (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 (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 (VIR_STRDUP(net->data.bridge.brname, tmp) < 0) + goto cleanup; + if (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 (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 (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 (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 (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; @@ -833,13 +811,11 @@ xenParseSxprGraphicsOld(virDomainDefPtr def, virDomainGraphicsListenSetAddress(graphics, 0, listenAddr, -1, true)) goto error; - if (vncPasswd && - !(graphics->data.vnc.auth.passwd = strdup(vncPasswd))) - goto no_memory; + if (VIR_STRDUP(graphics->data.vnc.auth.passwd, vncPasswd) < 0) + goto error; - if (keymap && - !(graphics->data.vnc.keymap = strdup(keymap))) - goto no_memory; + if (VIR_STRDUP(graphics->data.vnc.keymap, keymap) < 0) + goto error; if (VIR_ALLOC_N(def->graphics, 1) < 0) goto no_memory; @@ -856,12 +832,10 @@ xenParseSxprGraphicsOld(virDomainDefPtr def, goto no_memory; graphics->type = VIR_DOMAIN_GRAPHICS_TYPE_SDL; - if (display && - !(graphics->data.sdl.display = strdup(display))) - goto no_memory; - if (xauth && - !(graphics->data.sdl.xauth = strdup(xauth))) - goto no_memory; + if (VIR_STRDUP(graphics->data.sdl.display, display) < 0) + goto error; + if (VIR_STRDUP(graphics->data.sdl.xauth, xauth) < 0) + goto error; if (VIR_ALLOC_N(def->graphics, 1) < 0) goto no_memory; @@ -926,12 +900,10 @@ xenParseSxprGraphicsNew(virDomainDefPtr def, if (graphics->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL) { 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; - if (xauth && - !(graphics->data.sdl.xauth = strdup(xauth))) - goto no_memory; + if (VIR_STRDUP(graphics->data.sdl.display, display) < 0) + goto error; + if (VIR_STRDUP(graphics->data.sdl.xauth, xauth) < 0) + goto error; } else { int port; const char *listenAddr = sexpr_node(node, "device/vfb/vnclisten"); @@ -960,13 +932,11 @@ xenParseSxprGraphicsNew(virDomainDefPtr def, virDomainGraphicsListenSetAddress(graphics, 0, listenAddr, -1, true)) goto error; - if (vncPasswd && - !(graphics->data.vnc.auth.passwd = strdup(vncPasswd))) - goto no_memory; + if (VIR_STRDUP(graphics->data.vnc.auth.passwd, vncPasswd) < 0) + goto error; - if (keymap && - !(graphics->data.vnc.keymap = strdup(keymap))) - goto no_memory; + if (VIR_STRDUP(graphics->data.vnc.keymap, keymap) < 0) + goto error; } if (VIR_ALLOC_N(def->graphics, 1) < 0) @@ -1180,8 +1150,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 +1159,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 +1327,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 +1363,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..c28b79e 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,30 @@ 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; + VIR_STRDUP(net->script, script) < 0) + goto cleanup; if (model[0] && - !(net->model = strdup(model))) + 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; + VIR_STRDUP(net->ifname, vifname) < 0) + goto cleanup; if (VIR_REALLOC_N(def->nets, def->nnets+1) < 0) goto no_memory; @@ -1019,21 +1009,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 +1183,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.2.1

On 05/20/2013 07:55 PM, Michal Privoznik wrote:
--- src/xenxs/xen_sxpr.c | 200 ++++++++++++++++++++++----------------------------- src/xenxs/xen_xm.c | 91 +++++++++++------------ 2 files changed, 125 insertions(+), 166 deletions(-)
diff --git a/src/xenxs/xen_sxpr.c b/src/xenxs/xen_sxpr.c index 9a76d04..aa99a61 100644 --- a/src/xenxs/xen_sxpr.c +++ b/src/xenxs/xen_sxpr.c @@ -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;
Change offset to offset2 at the beginning of the condition. Or you could do it with just one VIR_STRNDUP call: offset++; if (VIR_STRNDUP(def->source.data.tcp.service, offset, offset2 ? offset2 - offset : strlen(offset)) < 0) goto error;
if (offset2 && strstr(offset2, ",server")) def->source.data.tcp.listen = true;
ACK Jan

--- cfg.mk | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/cfg.mk b/cfg.mk index bb93c6a..c714915 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_STRDUP, not strdup' \ + $(_sc_search_regexp) + # Prefer virSetUIDGID. sc_prohibit_setuid: @prohibit='\<set(re)?[ug]id\> *\(' \ @@ -874,6 +879,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.2.1

On 20.05.2013 19:55, Michal Privoznik wrote:
--- cfg.mk | 8 ++++++++ 1 file changed, 8 insertions(+)
diff --git a/cfg.mk b/cfg.mk index bb93c6a..c714915 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_STRDUP, not strdup' \ + $(_sc_search_regexp) + # Prefer virSetUIDGID. sc_prohibit_setuid: @prohibit='\<set(re)?[ug]id\> *\(' \ @@ -874,6 +879,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$$) +
If 14/13 is accepted, then this line needs to be: ^(docs/|examples/|python/|src/util/virstring\.c$$)
exclude_file_name_regexp--sc_prohibit_close = \ (\.p[yl]$$|^docs/|^(src/util/virfile\.c|src/libvirt\.c|tests/vircgroupmock\.c)$$)

On 05/20/2013 11:55 AM, Michal Privoznik wrote:
--- cfg.mk | 8 ++++++++ 1 file changed, 8 insertions(+)
diff --git a/cfg.mk b/cfg.mk index bb93c6a..c714915 100644 --- a/cfg.mk +++ b/cfg.mk @@ -387,6 +387,11 @@ sc_prohibit_asprintf: halt='use strdup instead of virAsprintf with "%s"' \
s/strdup/VIR_STRDUP/, so someone following this advice doesn't trigger yet another round of syntax failure.
$(_sc_search_regexp)
+sc_prohibit_strdup: + @prohibit='\<strn?dup\> *\(' \
"\> *(" is redundant; you can omit the \> and still get the same regex matching power.
+ halt='use VIR_STRDUP, not strdup' \ + $(_sc_search_regexp) + # Prefer virSetUIDGID. sc_prohibit_setuid: @prohibit='\<set(re)?[ug]id\> *\(' \ @@ -874,6 +879,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$$)
ACK with your amendment due to 14/13 and with the above tweaks; but obviously don't apply until we've actually fixed the rest of the code :) -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

On 23.05.2013 21:34, Eric Blake wrote:
On 05/20/2013 11:55 AM, Michal Privoznik wrote:
--- cfg.mk | 8 ++++++++ 1 file changed, 8 insertions(+)
diff --git a/cfg.mk b/cfg.mk index bb93c6a..c714915 100644 --- a/cfg.mk +++ b/cfg.mk @@ -387,6 +387,11 @@ sc_prohibit_asprintf: halt='use strdup instead of virAsprintf with "%s"' \
s/strdup/VIR_STRDUP/, so someone following this advice doesn't trigger yet another round of syntax failure.
$(_sc_search_regexp)
+sc_prohibit_strdup: + @prohibit='\<strn?dup\> *\(' \
"\> *(" is redundant; you can omit the \> and still get the same regex matching power.
+ halt='use VIR_STRDUP, not strdup' \ + $(_sc_search_regexp) + # Prefer virSetUIDGID. sc_prohibit_setuid: @prohibit='\<set(re)?[ug]id\> *\(' \ @@ -874,6 +879,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$$)
ACK with your amendment due to 14/13 and with the above tweaks; but obviously don't apply until we've actually fixed the rest of the code :)
I think we did fix the rest of the code - at least I've not hit any issue with syntax-check. Thanks for all the fish - I mean review. Michal

--- In case we want virsh included to these changes. tools/virsh.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tools/virsh.c b/tools/virsh.c index 6f0c1ef..26d37c6 100644 --- a/tools/virsh.c +++ b/tools/virsh.c @@ -122,9 +122,7 @@ _vshStrdup(vshControl *ctl, const char *s, const char *filename, int line) { char *x; - if (s == NULL) - return NULL; - if ((x = strdup(s))) + if (VIR_STRDUP(x, s) >= 0) return x; vshError(ctl, _("%s: %d: failed to allocate %lu bytes"), filename, line, (unsigned long)strlen(s)); -- 1.8.2.1

On 05/23/2013 10:32 AM, Michal Privoznik wrote:
---
In case we want virsh included to these changes.
Yes, we do.
tools/virsh.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/tools/virsh.c b/tools/virsh.c index 6f0c1ef..26d37c6 100644 --- a/tools/virsh.c +++ b/tools/virsh.c @@ -122,9 +122,7 @@ _vshStrdup(vshControl *ctl, const char *s, const char *filename, int line) { char *x;
- if (s == NULL) - return NULL; - if ((x = strdup(s))) + if (VIR_STRDUP(x, s) >= 0)
ACK. Wow - the 0 return value actually made sense :)
return x; vshError(ctl, _("%s: %d: failed to allocate %lu bytes"), filename, line, (unsigned long)strlen(s));
-- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
participants (4)
-
Eric Blake
-
John Ferlan
-
Ján Tomko
-
Michal Privoznik