ethtool: clean up and fix
Subsystems (3)
v2 cover ethtool: clean up and fix
This series is an update to the ethtool application code, and was triggered by running some static analysis tools and doing some general refactor on the ethtool code to make it clearer.
The tools run were:
$ scan-build make $ cppcheck $ make CFLAGS+='-fsanitize=address,undefined' LDFLAGS+='-lubsan -lasan'
The big change in this series is a refactor of all the various bit shifts from (1 << foo) to BIT(foo). The goal was to make the code more readable and maintainable, while fixing a few small bugs and hopefully preventing more in the future from people forgetting to add 1UL to a 1 being used in a bitshift.
It includes a uapi sync/update to match a patch that was sent to the kernel separately in the following link:
v2: first external version, updated commit message for 7/13
v1: internal version
Jesse Brandeburg (13):
ethtool: convert boilerplate licenses to SPDX
ethtool: fix trivial issue in allocation
ethtool: disallow passing null to find_option
ethtool: commonize power related strings
ethtool: fix extra warnings
ethtool: fix uninitialized local variable use
ethtool: avoid null pointer dereference
ethtool: fix runtime errors found by sanitizers
ethtool: merge uapi changes to implement BIT and friends
ethtool: refactor bit shifts to use BIT and BIT_ULL
ethtool: fix missing free of memory after failure
ethtool: fix leak of memory after realloc
ethtool: fix bug and use standard string parsing
amd8111e.c | 198 ++++++++--------- cmis.c | 10 +- de2104x.c | 410 +++++++++++++++++------------------ ethtool.c | 38 ++-- fsl_enetc.c | 2 - internal.h | 26 +-- json_print.c | 6 +- json_print.h | 6 +- natsemi.c | 358 +++++++++++++++--------------- netlink/bitset.c | 6 +- netlink/features.c | 4 +- netlink/monitor.c | 4 +- netlink/msgbuff.c | 39 ++-- netlink/parser.c | 13 +- netlink/permaddr.c | 2 +- netlink/settings.c | 10 +- netlink/stats.c | 2 +- qsfp.c | 21 +- qsfp.h | 353 +++++++++++++++--------------- realtek.c | 48 ++-- rxclass.c | 4 +- sfc.c | 7 +- sff-common.c | 6 +- sff-common.h | 9 +- sfpdiag.c | 67 +++--- sfpid.c | 151 +++++++------ stmmac.c | 5 +- test-cmdline.c | 5 +- test-common.c | 14 +- test-features.c | 5 +- tse.c | 7 +- uapi/linux/ethtool.h | 112 ++++++---- uapi/linux/ethtool_netlink.h | 6 +- 33 files changed, 961 insertions(+), 993 deletions(-)
base-commit: 3acf7eee7ade666289f98311befe334bb57d3765
Signature · 1 line
2.31.1
PATCH v2 1/13 ethtool: convert boilerplate licenses to SPDX
Used scancode (ScanCode-Toolkit) to find some licenses that have old boilerplate style.
In the interests of enabling better automated code License scanning, convert these to SPDX as the Linux kernel source has done.
--- json_print.c | 6 +----- json_print.h | 6 +----- qsfp.c | 6 +----- qsfp.h | 7 +------ sfc.c | 5 +---- sff-common.c | 6 +----- sff-common.h | 6 +----- sfpid.c | 5 +---- stmmac.c | 5 +---- test-cmdline.c | 5 +---- test-common.c | 5 +---- test-features.c | 5 +---- tse.c | 5 +---- 13 files changed, 13 insertions(+), 59 deletions(-)
json_print.c +1 -5
@@ -1,11 +1,7 @@ +// SPDX-License-Identifier: GPL-2.0-or-later /* * json_print.c "print regular or json output, based on json_writer". * -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version -* 2 of the License, or (at your option) any later version. -* * Authors: Julien Fortin, <[email protected]> */
json_print.h +1 -5
@@ -1,11 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * json_print.h "print regular or json output, based on json_writer". * -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version -* 2 of the License, or (at your option) any later version. -* * Authors: Julien Fortin, <[email protected]> */
qsfp.c +1 -5
@@ -1,3 +1,4 @@ +// SPDX-License-Identifier: GPL-2.0-or-later /* * qsfp.c: Implements SFF-8636 based QSFP+/QSFP28 Diagnostics Memory map. *
@@ -5,11 +6,6 @@* Aurelien Guillaume <[email protected]> (C) 2012 * Copyright (C) 2014 Cumulus networks Inc. * -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Freeoftware Foundation; either version 2 of the License, or -* (at your option) any later version. -* * Vidya Ravipati <[email protected]> * This implementation is loosely based on current SFP parser * and SFF-8636 spec Rev 2.7 (ftp://ftp.seagate.com/pub/sff/SFF-8636.PDF)
qsfp.h +1 -6
@@ -1,13 +1,8 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * SFF 8636 standards based QSFP EEPROM Field Definitions * * Vidya Ravipati <[email protected]> -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 2 of the License, or -* (at your option) any later version. -* */ #ifndef QSFP_H__
sfc.c +1 -4
@@ -1,10 +1,7 @@ +// SPDX-License-Identifier: GPL-2.0-only /**************************************************************************** * Support for Solarflare Solarstorm network controllers and boards * Copyright 2010-2012 Solarflare Communications Inc. -* -* This program is free software; you can redistribute it and/or modify it -* under the terms of the GNU General Public License version 2 as published -* by the Free Software Foundation, incorporated herein by reference. */ #include <stdio.h>
sff-common.c +1 -5
@@ -1,3 +1,4 @@ +// SPDX-License-Identifier: GPL-2.0-or-later /* * sff-common.c: Implements SFF-8024 Rev 4.0 i.e. Specifcation * of pluggable I/O configuration
@@ -9,11 +10,6 @@* Aurelien Guillaume <[email protected]> (C) 2012 * Copyright (C) 2014 Cumulus networks Inc. * -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Freeoftware Foundation; either version 2 of the License, or -* (at your option) any later version. -* * Vidya Sagar Ravipati <[email protected]> * This implementation is loosely based on current SFP parser * and SFF-8024 Rev 4.0 spec (ftp://ftp.seagate.com/pub/sff/SFF-8024.PDF)
sff-common.h +1 -5
@@ -1,3 +1,4 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * sff-common.h: Implements SFF-8024 Rev 4.0 i.e. Specifcation * of pluggable I/O configuration
@@ -9,11 +10,6 @@* Aurelien Guillaume <[email protected]> (C) 2012 * Copyright (C) 2014 Cumulus networks Inc. * -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Freeoftware Foundation; either version 2 of the License, or -* (at your option) any later version. -* * Vidya Sagar Ravipati <[email protected]> * This implementation is loosely based on current SFP parser * and SFF-8024 specs (ftp://ftp.seagate.com/pub/sff/SFF-8024.PDF)
sfpid.c +1 -4
@@ -1,10 +1,7 @@ +// SPDX-License-Identifier: GPL-2.0-only /**************************************************************************** * Support for Solarflare Solarstorm network controllers and boards * Copyright 2010 Solarflare Communications Inc. -* -* This program is free software; you can redistribute it and/or modify it -* under the terms of the GNU General Public License version 2 as published -* by the Free Software Foundation, incorporated herein by reference. */ #include <stdio.h>
stmmac.c +1 -4
@@ -1,13 +1,10 @@ +// SPDX-License-Identifier: GPL-2.0-only /**************************************************************************** * Support for the Synopsys MAC 10/100/1000 on-chip Ethernet controllers * * Copyright (C) 2007-2009 STMicroelectronics Ltd * * Author: Giuseppe Cavallaro <[email protected]> -* -* This program is free software; you can redistribute it and/or modify it -* under the terms of the GNU General Public License version 2 as published -* by the Free Software Foundation, incorporated herein by reference. */ #include <stdio.h>
test-cmdline.c +1 -4
@@ -1,10 +1,7 @@ +// SPDX-License-Identifier: GPL-2.0-only /**************************************************************************** * Test cases for ethtool command-line parsing * Copyright 2011 Solarflare Communications Inc. -* -* This program is free software; you can redistribute it and/or modify it -* under the terms of the GNU General Public License version 2 as published -* by the Free Software Foundation, incorporated herein by reference. */ #include <stdio.h>
test-common.c +1 -4
@@ -1,12 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0-only /**************************************************************************** * Common test functions for ethtool * Copyright 2011 Solarflare Communications Inc. * * Partly derived from kernel <linux/list.h>. -* -* This program is free software; you can redistribute it and/or modify it -* under the terms of the GNU General Public License version 2 as published -* by the Free Software Foundation, incorporated herein by reference. */ #include <assert.h>
test-features.c +1 -4
@@ -1,10 +1,7 @@ +// SPDX-License-Identifier: GPL-2.0-only /**************************************************************************** * Test cases for ethtool features * Copyright 2012 Solarflare Communications Inc. -* -* This program is free software; you can redistribute it and/or modify it -* under the terms of the GNU General Public License version 2 as published -* by the Free Software Foundation, incorporated herein by reference. */ #include <errno.h>
tse.c +1 -4
@@ -1,13 +1,10 @@ +// SPDX-License-Identifier: GPL-2.0-only /**************************************************************************** * Support for the Altera Triple Speed Ethernet 10/100/1000 Controller * * Copyright (C) 2014 Altera Corporation * * Author: Vince Bridgers <[email protected]> -* -* This program is free software; you can redistribute it and/or modify it -* under the terms of the GNU General Public License version 2 as published -* by the Free Software Foundation, incorporated herein by reference. */ #include <stdio.h>
Signature · 1 line
2.31.1
Re: [PATCH ethtool v2 01/13] ethtool: convert boilerplate licenses to SPDX
Quoted 7 lines · Jesse Brandeburg
Used scancode (ScanCode-Toolkit) to find some licenses that have old boilerplate style.
In the interests of enabling better automated code License scanning, convert these to SPDX as the Linux kernel source has done.
Signed-off-by Jesse Brandeburg <[email protected]>
PATCH v2 2/13 ethtool: fix trivial issue in allocation
In reply to Jesse BrandeburgFix the following warning by changing the type being multiplied by to the type being assigned to.
Description: Result of 'calloc' is converted to a pointer of type 'unsigned long', which is incompatible with sizeof operand type 'long'
File: /home/jbrandeb/git/ethtool/rxclass.c
Line: 527
--- rxclass.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
rxclass.c +1 -1
@@ -524,7 +524,7 @@ static int rmgr_init(struct cmd_context *ctx, struct rmgr_ctrl *rmgr) }/* initialize bitmap for storage of valid locations */ - rmgr->slot =calloc (1 ,BITS_TO_LONGS (rmgr->size) *sizeof (long )); + rmgr->slot =calloc (1 ,BITS_TO_LONGS (rmgr->size) *sizeof (unsigned long ));if (!rmgr->slot) {perror ("rmgr: Cannot allocate memory for RX class rules" );return -1 ;
Signature · 1 line
2.31.1
Re: [PATCH ethtool v2 02/13] ethtool: fix trivial issue in allocation
Quoted 19 lines · Jesse Brandeburg
Fix the following warning by changing the type being multiplied by to the type being assigned to.
Description: Result of 'calloc' is converted to a pointer of type 'unsigned long', which is incompatible with sizeof operand type 'long'
File:/home/jbrandeb/git/ethtool/rxclass.c
Line: 527Fixes 5a3279e43f2b ("rxclass: Replace global rmgr with automatic variable/parameter")Signed-off-by Jesse Brandeburg <[email protected]>--- rxclass.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)rxclass.c +0
-0
rxclass.c static int rmgr_init(struct cmd_context *ctx, struct rmgr_ctrl *rmgr) · line 527
Quoted 5 lines
rxclass.c +1
-1@@ -524,7 +524,7 @@ static int rmgr_init(struct cmd_context *ctx, struct rmgr_ctrl *rmgr) }/* initialize bitmap for storage of valid locations */ - rmgr->slot =calloc (1 ,BITS_TO_LONGS (rmgr->size) *sizeof (long )); + rmgr->slot =calloc (1 ,BITS_TO_LONGS (rmgr->size) *sizeof (unsigned long ));
While at it, maybe we should take the cleanup one step further and use sizeof(*rmgr->slot) or sizeof(rmgr->slot[0]) instead. And perhaps it would also make sense to follow the logic of calloc() arguments and use
calloc(BITS_TO_LONGS(rmgr->size), sizeof(rmgr->slot[0]))
Michal
Quoted 6 lines
rxclass.c +0
-0if (!rmgr->slot) {perror ("rmgr: Cannot allocate memory for RX class rules" );return -1 ;Signature · 1 line
2.31.1
PATCH v2 3/13 ethtool: disallow passing null to find_option
In reply to Jesse BrandeburgAfter testing with this code in the debugger, it is technically possible to pass a NULL argument to ethtool which then prods it to call strncmp with a NULL value, which triggers this warning:
Description: Null pointer passed to 1st parameter expecting 'nonnull'
File: /git/ethtool/ethtool.c
Line: 6129
Since segfaults are bad, let's just add a check for NULL when parsing the initial arguments. The other cases of a NULL option are seemingly handled.
--- ethtool.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
ethtool.c +1 -1
@@ -6389,7 +6389,7 @@ int main(int argc, char **argp)* name to get settings for (which we don't expect to begin * with '-'). */ -if (argc ==0 ) +if (argc ==0 || *argp ==NULL )exit_bad_args (); k =find_option (*argp);
Signature · 1 line
2.31.1
Re: [PATCH ethtool v2 03/13] ethtool: disallow passing null to find_option
Quoted 8 lines · Jesse Brandeburg
After testing with this code in the debugger, it is technically possible to pass a NULL argument to ethtool which then prods it to call strncmp with a NULL value, which triggers this warning:
Description: Null pointer passed to 1st parameter expecting 'nonnull'
File: /git/ethtool/ethtool.c
Line: 6129
Quoted 6 lines
Since segfaults are bad, let's just add a check for NULL when parsing the initial arguments. The other cases of a NULL option are seemingly handled.
Fixes 127f80691f96 ("Move argument parsing to sub-command functions")Signed-off-by Jesse Brandeburg <[email protected]>
Learning about (kernel) mainline commit dcd46d897adb ("exec: Force single empty string when argv is empty"), I'm not opposed to mistrusting kernel provided argc and argv[] but rather than hunting all places where we might possibly hit a null pointer in argv[] (mind that we may iterate over argv[] up to three times), I would simply check the whole array at the beginning of main() with something like
k = 0;
while (k <= argc && argv[k])
k++;
if (k != argc) {
fprintf(stderr, "ethtool: inconsistent command line (OS bug?)\n");
return 1;
}and be done with it.
Michal
Quoted 20 lines
--- ethtool.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)ethtool.c +1
-1@@ -6389,7 +6389,7 @@ int main(int argc, char **argp)* name to get settings for (which we don't expect to begin * with '-'). */ -if (argc ==0 ) +if (argc ==0 || *argp ==NULL )exit_bad_args (); k =find_option (*argp);Signature · 1 line
2.31.1
PATCH v2 4/13 ethtool: commonize power related strings
In reply to Jesse BrandeburgWhen looking into the implementation of the qsfp.h file, I found three pieces of code all doing the same thing and using similar, but bespoke strings.
Just make one set of strings for all three places to use. I made an effort to see if there was any size change due to making this change but I see no difference.
--- cmis.c | 10 ++-------- qsfp.c | 15 +++++++-------- sff-common.h | 3 +++ sfpdiag.c | 9 ++------- 4 files changed, 14 insertions(+), 23 deletions(-)
cmis.c +2 -8
@@ -727,16 +727,10 @@ cmis_show_dom_chan_lvl_rx_power_bank(const struct cmis_memory_map *map,for (i =0 ; i <CMIS_CHANNELS_PER_BANK ; i++) {int chan = bank *CMIS_CHANNELS_PER_BANK + i; -char *rx_power_str;char fmt_str[80 ]; -if (!sd->rx_power_type) - rx_power_str ="Receiver signal OMA" ; -else - rx_power_str ="Rcvr signal avg optical power" ; - -snprintf (fmt_str,80 ,"%s (Channel %d)" , rx_power_str, - chan +1 ); +snprintf (fmt_str,80 ,"%s (Channel %d)" , sd->rx_power_type ? + rx_power_average : rx_power_oma, chan +1 );PRINT_xX_PWR (fmt_str, sd->scd[chan].rx_power); } }
qsfp.c +7 -8
@@ -798,7 +798,6 @@ out:static void sff8636_show_dom (const struct sff8636_memory_map *map) {struct sff_diags sd = {0 }; -char *rx_power_string =NULL ;char power_string[MAX_DESC_SIZE ];int i;
@@ -846,14 +845,14 @@ static void sff8636_show_dom(const struct sff8636_memory_map *map)PRINT_xX_PWR (power_string, sd.scd[i].tx_power); } -if (!sd.rx_power_type) - rx_power_string ="Receiver signal OMA" ; -else - rx_power_string ="Rcvr signal avg optical power" ; -for (i =0 ; i <SFF8636_MAX_CHANNEL_NUM ; i++) { -snprintf (power_string,MAX_DESC_SIZE ,"%s(Channel %d)" , - rx_power_string, i+1 ); +int chars; + + chars =snprintf (power_string,MAX_DESC_SIZE , + sd.rx_power_type ? + rx_power_average : rx_power_oma); +snprintf (power_string + chars,MAX_DESC_SIZE - chars, +"(Channel %d)" , i +1 );PRINT_xX_PWR (power_string, sd.scd[i].rx_power); }
sff-common.h +3 -0
@@ -188,6 +188,9 @@ struct sff_diags {struct sff_channel_diags scd[MAX_CHANNEL_NUM ]; }; +static const char rx_power_oma[] ="Receiver Signal OMA" ; +static const char rx_power_average[] ="Receiver Signal average optical power" ; +double convert_mw_to_dbm (double mw); void sff_show_value_with_unit(const __u8 *id, unsigned int reg, const char *name, unsigned int mult,
sfpdiag.c +2 -7
@@ -242,7 +242,6 @@ static void sff8472_parse_eeprom(const __u8 *id, struct sff_diags *sd)void sff8472_show_all (const __u8 *id) {struct sff_diags sd = {0 }; -char *rx_power_string =NULL ;int i;sff8472_parse_eeprom (id, &sd);
@@ -256,12 +255,8 @@ void sff8472_show_all(const __u8 *id)PRINT_BIAS ("Laser bias current" , sd.bias_cur[MCURR ]);PRINT_xX_PWR ("Laser output power" , sd.tx_power[MCURR ]); -if (!sd.rx_power_type) - rx_power_string ="Receiver signal OMA" ; -else - rx_power_string ="Receiver signal average optical power" ; - -PRINT_xX_PWR (rx_power_string, sd.rx_power[MCURR ]); +PRINT_xX_PWR (sd.rx_power_type ? rx_power_average : rx_power_oma, + sd.rx_power[MCURR ]);PRINT_TEMP ("Module temperature" , sd.sfp_temp[MCURR ]);PRINT_VCC ("Module voltage" , sd.sfp_voltage[MCURR ]);
Signature · 1 line
2.31.1
Re: [PATCH ethtool v2 04/13] ethtool: commonize power related strings
Quoted 9 lines · Jesse Brandeburg
When looking into the implementation of the
qsfp.hfile, I found three pieces of code all doing the same thing and using similar, but bespoke strings.Just make one set of strings for all three places to use. I made an effort to see if there was any size change due to making this change but I see no difference.
Signed-off-by Jesse Brandeburg <[email protected]>
Perhaps you might go one step further and replace the whole repeating
sd->rx_power_type ? rx_power_average : rx_power_oma
pattern with an inline helper.
Michal
PATCH v2 5/13 ethtool: fix extra warnings
In reply to Jesse Brandeburg'$ scan-build make' reports
netlink/permaddr.c:44:2: warning: Value stored to 'ifinfo' is never read [deadcode.DeadStores]
ifinfo = mnl_nlmsg_put_extra_header(nlhdr, sizeof(*ifinfo));
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~So just remove the extra assignment which is never used.
--- netlink/permaddr.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
netlink/permaddr.c +1 -1
@@ -41,7 +41,7 @@ static int permaddr_prep_request(struct nl_socket *nlsk) nlhdr->nlmsg_type =RTM_GETLINK ; nlhdr->nlmsg_flags = nlm_flags; msgbuff->nlhdr = nlhdr; - ifinfo =mnl_nlmsg_put_extra_header (nlhdr,sizeof (*ifinfo)); +mnl_nlmsg_put_extra_header (nlhdr,sizeof (*ifinfo));if (devname) {uint16_t type =IFLA_IFNAME ;
Signature · 1 line
2.31.1
Re: [PATCH ethtool v2 05/13] ethtool: fix extra warnings
Quoted 19 lines · Jesse Brandeburg
'$ scan-build make' reports
netlink/permaddr.c:44:2: warning: Value stored to 'ifinfo' is never read [deadcode.DeadStores]ifinfo = mnl_nlmsg_put_extra_header(nlhdr, sizeof(*ifinfo)); ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~So just remove the extra assignment which is never used.
Fixes 7f3585b22a4b ("netlink: add handler for permaddr (-P)")Signed-off-by Jesse Brandeburg <[email protected]>--- netlink/permaddr.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)netlink/permaddr.c +0
-0
netlink/permaddr.c static int permaddr_prep_request(struct nl_socket *nlsk) · line 44
Quoted 5 lines
netlink/permaddr.c +1
-1@@ -41,7 +41,7 @@ static int permaddr_prep_request(struct nl_socket *nlsk) nlhdr->nlmsg_type =RTM_GETLINK ; nlhdr->nlmsg_flags = nlm_flags; msgbuff->nlhdr = nlhdr; - ifinfo =mnl_nlmsg_put_extra_header (nlhdr,sizeof (*ifinfo)); +mnl_nlmsg_put_extra_header (nlhdr,sizeof (*ifinfo));
Good point. But looking at the code, the variable isn't in fact used at all, except of the two occurences of sizeof(*ifinfo). So we can just as well replace them with sizeof(struct ifinfomsg) and drop the variable.
Michal
Quoted 6 lines
netlink/permaddr.c +0
-0if (devname) {uint16_t type =IFLA_IFNAME ;Signature · 1 line
2.31.1
PATCH v2 6/13 ethtool: fix uninitialized local variable use
In reply to Jesse Brandeburg'$ scan-build make' reports:
netlink/parser.c:252:25: warning: The left operand of '*' is a garbage value [core.UndefinedBinaryOperatorResult]
cm = (uint32_t)(meters * 100 + 0.5);
~~~~~~ ^This is a little more complicated than it seems, but for some unexplained reason, parse_float always returns integers but was declared to return a float. This is confusing at best. In the case of the error above, parse_float could conceivably return without initializing it's output variable, and because the function return variable was declared as float but downgraded to an int via assignment (-Wconversion anyone?) upon the return, the return value could be ignored.
To fix the bug above, declare an initial value for meters, and make sure that parse_float() always returns an integer value.
It would probably be even more ideal if parse_float always initialized it's output variables before even checking for input errors, but that's for some future day.
--- netlink/parser.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
netlink/parser.c +2 -3
@@ -54,8 +54,7 @@ static bool __prefix_0x(const char *p)return p[0 ] =='0' && (p[1 ] =='x' || p[1 ] =='X' ); } -static float parse_float (const char *arg,float *result,float min, -float max) +static int parse_float (const char *arg,float *result,float min,float max) {char *endptr;float val;
@@ -237,7 +236,7 @@ int nl_parse_direct_m2cm(struct nl_context *nlctx, uint16_t type, struct nl_msg_buff *msgbuff, void *dest) { const char *arg = *nlctx->argp; -float meters; +float meters =0 ;uint32_t cm;int ret;
Signature · 1 line
2.31.1
Re: [PATCH ethtool v2 06/13] ethtool: fix uninitialized local variable use
Quoted 9 lines · Jesse Brandeburg
'$ scan-build make' reports:
netlink/parser.c:252:25: warning: The left operand of '*' is a garbage value [core.UndefinedBinaryOperatorResult]cm = (uint32_t)(meters * 100 + 0.5); ~~~~~~ ^This is a little more complicated than it seems, but for some unexplained reason,
parse_floatalways returns integers but was declared to return a float.
Looks like i got that wrong. Duh!
Quoted 6 lines
This is confusing at best. In the case of the error
above,parse_floatcould conceivably return without initializing it's output variable, and because the function return variable was declared as float but downgraded to an int via assignment (-Wconversion anyone?) upon the return, the return value could be ignored.
Quoted 6 lines
To fix the bug above, declare an initial value for meters, and make sure that
parse_float()always returns an integer value.It would probably be even more ideal if
parse_floatalways initialized it's output variables before even checking for input errors, but that's for some future day.
It is also following the pattern of other parse_foo functions. None of them set the result in case of errors.
Quoted 23 lines
CC Andrew Lunn <[email protected]>Fixes 9561db9b76f4 ("Add cable test TDR support")Signed-off-by Jesse Brandeburg <[email protected]>--- netlink/parser.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)netlink/parser.c +1
-2@@ -54,8 +54,7 @@ static bool __prefix_0x(const char *p)return p[0 ] =='0' && (p[1 ] =='x' || p[1 ] =='X' ); } -static float parse_float (const char *arg,float *result,float min, -float max) +static int parse_float (const char *arg,float *result,float min,float max) {char *endptr;float val;
netlink/parser.c int nl_parse_direct_m2cm(struct nl_context *nlctx, uint16_t type, · line 241
Quoted 7 lines
netlink/parser.c +1
-1@@ -237,7 +236,7 @@ int nl_parse_direct_m2cm(struct nl_context *nlctx, uint16_t type, struct nl_msg_buff *msgbuff, void *dest) { const char *arg = *nlctx->argp; -float meters; +float meters =0 ;uint32_t cm;int ret;
Should this actually be 0.0? Otherwise if -Wconversion gets turned on, you have an int being converted to a float?
Anyway:
Andrew
PATCH v2 7/13 ethtool: avoid null pointer dereference
In reply to Jesse Brandeburg'$ scan-build make' reports:
Description: Array access (from variable 'arg') results in a null pointer dereference
File: /git/ethtool/netlink/parser.c
Line: 782
Description: Dereference of null pointer (loaded from variable 'p')
File: /git/ethtool/netlink/parser.c
Line: 794
Both of these bugs are prevented by checking the input in nl_parse_char_bitset(), which is called from nl_sset() via the kernel callback, specifically for the parsing of the wake-on-lan options (-s wol). None of the other functions in this file seem to have the issue of deferencing data without checking for validity first. This could "technically" allow nlctxt->argp to be NULL, and scan-build is limited in it's ability to parse for bugs only at file scope in this case. This particular bug should be unlikely to happen because the kernel builds/parses the netlink structure before handing it to the application. However in the interests of being able to run this scan-build tool regularly, I'm still sending the initial version of this patch as I tried several other ways to fix the bug with an earlier check for NULL in nl_sset, but it won't prevent the scan-build error due to the file scope problem.
---
v2: updated commit message with more nuance after feedback from ethtool maintainer. I'd be open to fixing this a different way but this seemed the most straight-forward with the smallest amount of code changed.
v1: original version
--- netlink/parser.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
netlink/parser.c +2 -2
@@ -874,7 +874,7 @@ int nl_parse_bitset(struct nl_context *nlctx, uint16_t type, const void *data,* optionally followed by '/' and another numeric value (mask, unless no_mask * is set), or a string consisting of characters corresponding to bit indices. * The @data parameter points to struct char_bitset_parser_data. Generates -* biset nested attribute. Fails if type is zero or if @dest is not null. +* bitset nested attribute. Fails if type is zero or if @dest is not null. */ int nl_parse_char_bitset(struct nl_context *nlctx, uint16_t type, const void *data, struct nl_msg_buff *msgbuff,
@@ -882,7 +882,7 @@ int nl_parse_char_bitset(struct nl_context *nlctx, uint16_t type, {const struct char_bitset_parser_data *parser_data = data; -if (!type || dest) { +if (!type || dest || !*nlctx->argp) {fprintf (stderr,"ethtool (%s): internal error parsing '%s'\n" , nlctx->cmd, nlctx->param);return -EFAULT ;
Signature · 1 line
2.31.1
Re: [PATCH ethtool v2 07/13] ethtool: avoid null pointer dereference
Quoted 11 lines · Jesse Brandeburg
'$ scan-build make' reports:
Description: Array access (from variable 'arg') results in a null pointer dereference
File: /git/ethtool/netlink/parser.c
Line: 782Description: Dereference of null pointer (loaded from variable 'p')
File: /git/ethtool/netlink/parser.c
Line: 794
Quoted 9 lines
Both of these bugs are prevented by checking the input in
nl_parse_char_bitset(), which is called fromnl_sset()via the kernel callback, specifically for the parsing of the wake-on-lan options (-s wol). None of the other functions in this file seem to have the issue of deferencing data without checking for validity first. This could "technically" allownlctxt->argpto be NULL, and scan-build is limited in it's ability to parse for bugs only at file scope in this case. This particular bug should be unlikely to happen because the kernel builds/parses the netlink structure before handing it to the
Again: this has nothing to do with netlink, this is command line parser, nlctx->argp is a member of argv[] array. And as execve() (which is the only syscall in the exec* family, the rest are wrappers) does not pass argc, only argv[], argc is actually determined by kernel so for it to be actually null, you would need a serious bug in kernel first.
Even if we want to be safe against buggy kernel passing garbage as command line arguments, I still believe we should do that earlier, in the general code, not deep in a specific helper function. Also, you only check for null but that does not catch an invalid pointer in argv[] which, unlike a null pointer, could do an actual harm. And I don't see how that could be checked, I'm afraid we have to trust kernel.
Michal
Quoted 43 lines
application. However in the interests of being able to run this scan-build tool regularly, I'm still sending the initial version of this patch as I tried several other ways to fix the bug with an earlier check for NULL in
nl_sset, but it won't prevent the scan-build error due to the file scope problem.CC Michal Kubecek <[email protected]>Fixes 81a30f416ec7 ("netlink: add bitset command line parser handlers")Signed-off-by Jesse Brandeburg <[email protected]>---
v2: updated commit message with more nuance after feedback from ethtool maintainer. I'd be open to fixing this a different way but this seemed the most straight-forward with the smallest amount of code changed.
v1: original version--- netlink/parser.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)netlink/parser.c +2
-2@@ -874,7 +874,7 @@ int nl_parse_bitset(struct nl_context *nlctx, uint16_t type, const void *data,* optionally followed by '/' and another numeric value (mask, unless no_mask * is set), or a string consisting of characters corresponding to bit indices. * The @data parameter points to struct char_bitset_parser_data. Generates -* biset nested attribute. Fails if type is zero or if @dest is not null. +* bitset nested attribute. Fails if type is zero or if @dest is not null. */ int nl_parse_char_bitset(struct nl_context *nlctx, uint16_t type, const void *data, struct nl_msg_buff *msgbuff,@@ -882,7 +882,7 @@ int nl_parse_char_bitset(struct nl_context *nlctx, uint16_t type, {const struct char_bitset_parser_data *parser_data = data; -if (!type || dest) { +if (!type || dest || !*nlctx->argp) {fprintf (stderr,"ethtool (%s): internal error parsing '%s'\n" , nlctx->cmd, nlctx->param);return -EFAULT ;Signature · 1 line
2.31.1
Re: [PATCH ethtool v2 07/13] ethtool: avoid null pointer dereference
Quoted 22 lines · Michal Kubecek
Quoted 11 lines · Jesse Brandeburg
'$ scan-build make' reports:
Description: Array access (from variable 'arg') results in a null pointer dereference
File: /git/ethtool/netlink/parser.c
Line: 782Description: Dereference of null pointer (loaded from variable 'p')
File: /git/ethtool/netlink/parser.c
Line: 794Quoted 9 lines
Both of these bugs are prevented by checking the input in
nl_parse_char_bitset(), which is called fromnl_sset()via the kernel callback, specifically for the parsing of the wake-on-lan options (-s wol). None of the other functions in this file seem to have the issue of deferencing data without checking for validity first. This could "technically" allownlctxt->argpto be NULL, and scan-build is limited in it's ability to parse for bugs only at file scope in this case. This particular bug should be unlikely to happen because the kernel builds/parses the netlink structure before handing it to the
Quoted 5 lines
Again: this has nothing to do with netlink, this is command line parser,
nlctx->argpis a member of argv[] array. And asexecve()(which is the only syscall in the exec* family, the rest are wrappers) does not pass argc, only argv[], argc is actually determined by kernel so for it to be actually null, you would need a serious bug in kernel first.
Thank you for explaining! I can drop this patch, but it's disappointing that one fairly cheap conditional will prevent us from being able to cleanly run scan-build. If you have any other suggestions please let me know (and see below)
I spent some time today trying to get the command line to pass a NULL value but I couldn't do it, and elsewhere in the code the checks for argc prevent the NULL value or no value from getting into the ethtool code parsing the commands, so in this case it's not really a false positive, but taken care of by other code that isn't observable to the scan-build virtual machine. The good news is I don't see a real issue here.
Quoted 6 lines
Even if we want to be safe against buggy kernel passing garbage as command line arguments, I still believe we should do that earlier, in the general code, not deep in a specific helper function. Also, you only check for null but that does not catch an invalid pointer in argv[] which, unlike a null pointer, could do an actual harm. And I don't see how that could be checked, I'm afraid we have to trust kernel.
OK, let's trust the kernel, but can we still fix this issue in order to be able to add scan-build to a list of tools to run cleanly in automation?
some TL;DR details in case there is someone else that has a suggestion!
Here is the callchain, for reference:
This is from the command
# ethtool -s eth0 wol pumbag
#0 nl_parse_char_bitset #1 in nl_parser at netlink/parser.c:1099 #2 in nl_sset at netlink/settings.c:1247 #3 in netlink_run_handler at netlink/netlink.c:493 #4 in main at ethtool.c:6425
and in the #0 frame above, *nlctx->argp = "pumbag"
in the callchain above, scan-build doesn't like us de-referencing argp because it doesn't have proof it's not null.
Further I tried putting the check in every element of the stack frame above and they all fail the scan-build check still, probably because the pointer is advanced to the "pumbag" argument later in the code.
Anyway, I'm still working on the v3 of the series.
Re: [PATCH ethtool v2 07/13] ethtool: avoid null pointer dereference
Quoted 10 lines · Jesse Brandeburg
Here is the callchain, for reference:
This is from the command# ethtool -s eth0 wol pumbag#0 nl_parse_char_bitset #1 in nl_parser at netlink/parser.c:1099 #2 in nl_sset at netlink/settings.c:1247 #3 in netlink_run_handler at netlink/netlink.c:493 #4 in main at ethtool.c:6425
Quoted 7 lines
and in the #0 frame above,
*nlctx->argp= "pumbag"
in the callchain above, scan-build doesn't like us de-referencing argp because it doesn't have proof it's not null.Further I tried putting the check in every element of the stack frame above and they all fail the scan-build check still, probably because the pointer is advanced to the "pumbag" argument later in the code.
This should be guaranteed by min_argc beeing set to 1 in the relevant member of sset_params[] array in netlink/setings.c. The dispatcher code in nl_parser() checks that there are at least ->min_argc parameters left before calling specific ->handler(). So as long as argc and argv[] are consistent, we should be safe.
But I suppose we cannot expect the static checker to be smart enough to see through that logic.
Michal
PATCH v2 8/13 ethtool: fix runtime errors found by sanitizers
In reply to Jesse BrandeburgThe sanitizers[1] found a couple of things, but this change addresses some bit shifts that cannot be contained by the target type.
The mistake is that the code is using unsigned int a = (1 << N) all over the place, but the appropriate way to code this is unsigned int an assignment of (1UL << N) especially if N can ever be 31.
Fix the most egregious of these problems by changing "1" to "1UL", as per it would be if we had used the BIT() macro.
[1] make CFLAGS+='-fsanitize=address,undefined' \
LDFLAGS+='-lubsan -lasan'--- amd8111e.c | 2 +- internal.h | 4 ++-- netlink/features.c | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-)
amd8111e.c +1 -1
@@ -75,7 +75,7 @@ typedef enum { }CMD3_BITS ; typedef enum { - INTR = (1 << 31), + INTR = (1UL << 31), PCSINT = (1 << 28), LCINT = (1 << 27), APINT5 = (1 << 26),
internal.h +2 -2
@@ -205,14 +205,14 @@ static inline int ethtool_link_mode_test_bit(unsigned int nr, const u32 *mask) {if (nr >=ETHTOOL_LINK_MODE_MASK_MAX_KERNEL_NBITS )return !!0 ; -return !!(mask[nr /32 ] & (1 << (nr %32 ))); +return !!(mask[nr /32 ] & (1UL << (nr %32 ))); }static inline int ethtool_link_mode_set_bit (unsigned int nr,u32 *mask) {if (nr >=ETHTOOL_LINK_MODE_MASK_MAX_KERNEL_NBITS )return -1 ; - mask[nr /32 ] |= (1 << (nr %32 )); + mask[nr /32 ] |= (1UL << (nr %32 ));return 0 ; }
netlink/features.c +2 -2
@@ -57,7 +57,7 @@ static int prepare_feature_results(const struct nlattr *const *tb,static bool feature_on (const uint32_t *bitmap,unsigned int idx) { -return bitmap[idx /32 ] & (1 << (idx %32 )); +return bitmap[idx /32 ] & (1UL << (idx %32 )); } static void dump_feature(const struct feature_results *results,
@@ -302,7 +302,7 @@ static void set_sf_req_mask(struct nl_context *nlctx, unsigned int idx) {struct sfeatures_context *sfctx = nlctx->cmd_private; - sfctx->req_mask[idx /32 ] |= (1 << (idx %32 )); + sfctx->req_mask[idx /32 ] |= (1UL << (idx %32 )); } static int fill_legacy_flag(struct nl_context *nlctx, const char *flag_name,
Signature · 1 line
2.31.1
Re: [PATCH ethtool v2 08/13] ethtool: fix runtime errors found by sanitizers
Quoted 25 lines · Jesse Brandeburg
The sanitizers[1] found a couple of things, but this change addresses some bit shifts that cannot be contained by the target type.
The mistake is that the code is using unsigned int a = (1 << N) all over the place, but the appropriate way to code this is unsigned int an assignment of (1UL << N) especially if N can ever be 31.
Fix the most egregious of these problems by changing "1" to "1UL", as per it would be if we had used the
BIT()macro.[1] make CFLAGS+='-fsanitize=address,undefined' \ LDFLAGS+='-lubsan -lasan'Signed-off-by Jesse Brandeburg <[email protected]>--- amd8111e.c | 2 +- internal.h | 4 ++-- netlink/features.c | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-)amd8111e.c +0
-0
amd8111e.c typedef enum { · line 81
Quoted 8 lines
amd8111e.c +1
-1@@ -75,7 +75,7 @@ typedef enum { }CMD3_BITS ; typedef enum { - INTR = (1 << 31), + INTR = (1UL << 31), PCSINT = (1 << 28), LCINT = (1 << 27), APINT5 = (1 << 26),
While the signedness issue only directly affects only INTR value, I would rather prefer to keep the code consistent and fix the whole enum. Also, as you intend to introduce the BIT() macro in the series anyway, wouldn't it be cleaner to move this patch after the UAPI update and use BIT() instead?
Michal
Re: [PATCH ethtool v2 08/13] ethtool: fix runtime errors found by sanitizers
Quoted 13 lines · Michal Kubecek
amd8111e.c typedef enum { · line 81
Quoted 5 lines · Jesse Brandeburg
amd8111e.c +1
-1-INTR = (1 <<31 ), +INTR = (1UL <<31 ),PCSINT = (1 <<28 ),LCINT = (1 <<27 ), APINT5 = (1 << 26),While the signedness issue only directly affects only INTR value, I would rather prefer to keep the code consistent and fix the whole enum. Also, as you intend to introduce the
BIT()macro in the series anyway, wouldn't it be cleaner to move this patch after the UAPI update and useBIT()instead?
I had done it this way to separate the "most minimal fix" from the "refactor", as I figure that is a clearer way to delineate changes. Also, this specifically addresses the issues found by the undefined behavior sanitizer.
I'll do it whichever way you like, but you're correct, later in this series I fix up all the BIT() usages. Maybe we can just leave this patch as is, knowing the full fix comes during the refactor in 10/13 ?
Re: [PATCH ethtool v2 08/13] ethtool: fix runtime errors found by sanitizers
Quoted 15 lines · Jesse Brandeburg
Quoted 13 lines · Michal Kubecek
amd8111e.c typedef enum { · line 81
Quoted 5 lines · Jesse Brandeburg
amd8111e.c +1
-1-INTR = (1 <<31 ), +INTR = (1UL <<31 ),PCSINT = (1 <<28 ),LCINT = (1 <<27 ), APINT5 = (1 << 26),While the signedness issue only directly affects only INTR value, I would rather prefer to keep the code consistent and fix the whole enum. Also, as you intend to introduce the
BIT()macro in the series anyway, wouldn't it be cleaner to move this patch after the UAPI update and useBIT()instead?
Quoted 8 lines
I had done it this way to separate the "most minimal fix" from the "refactor", as I figure that is a clearer way to delineate changes. Also, this specifically addresses the issues found by the undefined behavior sanitizer.
I'll do it whichever way you like, but you're correct, later in this series I fix up all the
BIT()usages. Maybe we can just leave this patch as is, knowing the full fix comes during the refactor in 10/13 ?
As we end up with BIT() everywhere anyway, I'm OK with either option, leaving this patch as it is or dropping it. When I was writing that comment, I had seen 09/13 (introduction of BIT()) but not 10/13 (refactoring everything to use it).
Michal
Re: [PATCH ethtool v2 08/13] ethtool: fix runtime errors found by sanitizers
Quoted 8 lines · Michal Kubecek
Quoted 3 lines
I'll do it whichever way you like, but you're correct, later in this series I fix up all the
BIT()usages. Maybe we can just leave this patch as is, knowing the full fix comes during the refactor in 10/13 ?As we end up with
BIT()everywhere anyway, I'm OK with either option, leaving this patch as it is or dropping it. When I was writing that comment, I had seen 09/13 (introduction ofBIT()) but not 10/13 (refactoring everything to use it).
Ok, thanks. Also Jakub pointed out to me there is a UAPI compliant _BITUL()/_BITULL() function in include/uapi/linux/const.h, which I'll switch 9 and 10 to using. Wish that function had been a tad more discoverable.
PATCH v2 9/13 ethtool: merge uapi changes to implement BIT and friends
In reply to Jesse BrandeburgI was looking into some errors reported by the runtime sanitizers and found a couple of places where (1 << 31) was being used. This is a shift of a bit into the sign-bit of an integer. This is undefined behavior for the C-specification, and can be easily fixed with using (1UL << 31) instead. A better way to do this is to use the BIT() macro, which already has the 1UL in it (see future patch in series).
Convert and sync with the same changes made upstream to the uapi file, to implement ethtool use BIT() and friends.
This required an unfortunate bit of extra fussing around declaring "same definition" versions of the BIT* macros so that the UAPI file will compile both under the kernel and in user-space (here).
A local declaration of BIT() had to be moved out of fsl_enetc.c when the implementation was moved to a header.
NOTE:
This change will be followed by a larger conversion patch, but *this* commit only has the UAPI file changes and the initial implementation to keep the work separate from the application only changes.
--- fsl_enetc.c | 2 - uapi/linux/ethtool.h | 112 +++++++++++++++++++++-------------- uapi/linux/ethtool_netlink.h | 6 +- 3 files changed, 70 insertions(+), 50 deletions(-)
fsl_enetc.c +0 -2
@@ -5,8 +5,6 @@#include <stdio.h> #include "internal.h" -#define BIT (x) (1U << (x)) -enum enetc_bdr_type {TX ,RX };#define ENETC_SIMR 0#define ENETC_SIPMAR0 0x80
uapi/linux/ethtool.h +67 -45
179 lines not on this page · raw message
uapi/linux/ethtool_netlink.h +3 -3
@@ -103,11 +103,11 @@ enum {/* request header */ /* use compact bitsets in reply */ -#define ETHTOOL_FLAG_COMPACT_BITSETS (1 << 0) +#define ETHTOOL_FLAG_COMPACT_BITSETS BIT(0)/* provide optional reply for SET or ACT requests */ -#define ETHTOOL_FLAG_OMIT_REPLY (1 << 1) +#define ETHTOOL_FLAG_OMIT_REPLY BIT(1)/* request statistics, if supported by the driver */ -#define ETHTOOL_FLAG_STATS (1 << 2) +#define ETHTOOL_FLAG_STATS BIT(2)#define ETHTOOL_FLAG_ALL (ETHTOOL_FLAG_COMPACT_BITSETS | \ ETHTOOL_FLAG_OMIT_REPLY | \
Signature · 1 line
2.31.1
Re: [PATCH ethtool v2 09/13] ethtool: merge uapi changes to implement BIT and friends
Quoted 9 lines · Jesse Brandeburg
I was looking into some errors reported by the runtime sanitizers and found a couple of places where (1 << 31) was being used. This is a shift of a bit into the sign-bit of an integer. This is undefined behavior for the C-specification, and can be easily fixed with using (1UL << 31) instead. A better way to do this is to use the
BIT()macro, which already has the 1UL in it (see future patch in series).Convert and sync with the same changes made upstream to the uapi file, to implement ethtool use
BIT()and friends.
Please follow the guidelines on updating UAPI header copies in "Submitting patches" section of
https://www.kernel.org/pub/software/network/ethtool/devel.html
Fixing fsl_enetc.c within the UAPI update is OK (and definitely better than trying to avoid it) but please update all UAPI header copies to the state of the same kernel tree commit which will be indicated in the commit message.
Michal
Quoted 13 lines
This required an unfortunate bit of extra fussing around declaring "same definition" versions of the BIT* macros so that the UAPI file will compile both under the kernel and in user-space (here).
A local declaration of
BIT()had to be moved out offsl_enetc.cwhen the implementation was moved to a header.NOTE:
This change will be followed by a larger conversion patch, but *this* commit only has the UAPI file changes and the initial implementation to keep the work separate from the application only changes.Signed-off-by Jesse Brandeburg <[email protected]>
Re: [PATCH ethtool v2 09/13] ethtool: merge uapi changes to implement BIT and friends
Quoted 14 lines · Michal Kubecek
Quoted 9 lines · Jesse Brandeburg
I was looking into some errors reported by the runtime sanitizers and found a couple of places where (1 << 31) was being used. This is a shift of a bit into the sign-bit of an integer. This is undefined behavior for the C-specification, and can be easily fixed with using (1UL << 31) instead. A better way to do this is to use the
BIT()macro, which already has the 1UL in it (see future patch in series).Convert and sync with the same changes made upstream to the uapi file, to implement ethtool use
BIT()and friends.Please follow the guidelines on updating UAPI header copies in "Submitting patches" section of
Quoted 6 lines
https://www.kernel.org/pub/software/network/ethtool/devel.html
Fixing
fsl_enetc.cwithin the UAPI update is OK (and definitely better than trying to avoid it) but please update all UAPI header copies to the state of the same kernel tree commit which will be indicated in the commit message.
I'll respin the uapi changes in the kernel to use uapi/linux/const.h and wait to see how that series goes then.
PATCH v2 10/13 ethtool: refactor bit shifts to use BIT and BIT_ULL
In reply to Jesse BrandeburgA previous patch fixed bit shifts into the sign bit. Formalize this change and enable clearer code with a conversion of all (1 << foo) to BIT(foo). This aligns better with the kernel and makes mistakes less likely due to forgetting the '1UL' during (1UL << foo) usage.
There were a couple of places changed with 1ULL << foo that got changed to BIT_ULL(foo).
Most of the changes were made by a complicated regular expression that helped me find the issues (vim style regex):
s/\(\s\+\)(\?\s*1\(U\|UL\)\?\s*<<\s*\([0-9A-Za-z_]\+\))\?/\1BIT(\3)/
--- amd8111e.c | 198 +++++++++++----------- de2104x.c | 410 ++++++++++++++++++++++----------------------- ethtool.c | 18 +- internal.h | 26 +-- natsemi.c | 358 +++++++++++++++++++-------------------- netlink/bitset.c | 6 +- netlink/features.c | 4 +- netlink/monitor.c | 4 +- netlink/parser.c | 4 +- netlink/settings.c | 10 +- netlink/stats.c | 2 +- qsfp.h | 346 +++++++++++++++++++------------------- realtek.c | 48 +++--- rxclass.c | 2 +- sfc.c | 2 +- sfpdiag.c | 58 +++---- sfpid.c | 146 ++++++++-------- tse.c | 2 +- 18 files changed, 822 insertions(+), 822 deletions(-)
amd8111e.c +99 -99
@@ -5,20 +5,20 @@ typedef enum { /* VAL2 */ - RDMD0 = (1 << 16), + RDMD0 = BIT(16), /* VAL1 */ - TDMD3 = (1 << 11), - TDMD2 = (1 << 10), - TDMD1 = (1 << 9), - TDMD0 = (1 << 8), + TDMD3 = BIT(11), + TDMD2 = BIT(10), + TDMD1 = BIT(9), + TDMD0 = BIT(8), /* VAL0 */ - UINTCMD = (1 << 6), - RX_FAST_SPND = (1 << 5), - TX_FAST_SPND = (1 << 4), - RX_SPND = (1 << 3), - TX_SPND = (1 << 2), - INTREN = (1 << 1), - RUN = (1 << 0), + UINTCMD = BIT(6), + RX_FAST_SPND = BIT(5), + TX_FAST_SPND = BIT(4), + RX_SPND = BIT(3), + TX_SPND = BIT(2), + INTREN = BIT(1), + RUN = BIT(0), CMD0_CLEAR = 0x000F0F7F, /* Command style register */
@@ -26,27 +26,27 @@ typedef enum { typedef enum { /* VAL3 */ - CONDUIT_MODE = (1 << 29), + CONDUIT_MODE = BIT(29), /* VAL2 */ - RPA = (1 << 19), - DRCVPA = (1 << 18), - DRCVBC = (1 << 17), - PROM = (1 << 16), + RPA = BIT(19), + DRCVPA = BIT(18), + DRCVBC = BIT(17), + PROM = BIT(16), /* VAL1 */ - ASTRP_RCV = (1 << 13), - RCV_DROP0 = (1 << 12), - EMBA = (1 << 11), - DXMT2PD = (1 << 10), - LTINTEN = (1 << 9), - DXMTFCS = (1 << 8), + ASTRP_RCV = BIT(13), + RCV_DROP0 = BIT(12), + EMBA = BIT(11), + DXMT2PD = BIT(10), + LTINTEN = BIT(9), + DXMTFCS = BIT(8), /* VAL0 */ - APAD_XMT = (1 << 6), - DRTY = (1 << 5), - INLOOP = (1 << 4), - EXLOOP = (1 << 3), - REX_RTRY = (1 << 2), - REX_UFLO = (1 << 1), - REX_LCOL = (1 << 0), + APAD_XMT = BIT(6), + DRTY = BIT(5), + INLOOP = BIT(4), + EXLOOP = BIT(3), + REX_RTRY = BIT(2), + REX_UFLO = BIT(1), + REX_LCOL = BIT(0), CMD2_CLEAR = 0x3F7F3F7F, /* Command style register */
@@ -54,79 +54,79 @@ typedef enum {typedef enum {/* VAL3 */ -ASF_INIT_DONE_ALIAS = (1 <<29 ), +ASF_INIT_DONE_ALIAS =BIT (29 ),/* VAL2 */ -JUMBO = (1 <<21 ), -VSIZE = (1 <<20 ), -VLONLY = (1 <<19 ), -VL_TAG_DEL = (1 <<18 ), +JUMBO =BIT (21 ), +VSIZE =BIT (20 ), +VLONLY =BIT (19 ), +VL_TAG_DEL =BIT (18 ),/* VAL1 */ -EN_PMGR = (1 <<14 ), -INTLEVEL = (1 <<13 ), -FORCE_FULL_DUPLEX = (1 <<12 ), -FORCE_LINK_STATUS = (1 <<11 ), -APEP = (1 <<10 ), -MPPLBA = (1 <<9 ), +EN_PMGR =BIT (14 ), +INTLEVEL =BIT (13 ), +FORCE_FULL_DUPLEX =BIT (12 ), +FORCE_LINK_STATUS =BIT (11 ), +APEP =BIT (10 ), +MPPLBA =BIT (9 ),/* VAL0 */ -RESET_PHY_PULSE = (1 <<2 ), -RESET_PHY = (1 <<1 ), -PHY_RST_POL = (1 <<0 ), +RESET_PHY_PULSE =BIT (2 ), +RESET_PHY =BIT (1 ), +PHY_RST_POL =BIT (0 ), }CMD3_BITS ;typedef enum { -INTR = (1UL <<31 ), -PCSINT = (1 <<28 ), -LCINT = (1 <<27 ), -APINT5 = (1 <<26 ), -APINT4 = (1 <<25 ), -APINT3 = (1 <<24 ), -TINT_SUM = (1 <<23 ), -APINT2 = (1 <<22 ), -APINT1 = (1 <<21 ), -APINT0 = (1 <<20 ), -MIIPDTINT = (1 <<19 ), -MCCINT = (1 <<17 ), -MREINT = (1 <<16 ), -RINT_SUM = (1 <<15 ), -SPNDINT = (1 <<14 ), -MPINT = (1 <<13 ), -SINT = (1 <<12 ), -TINT3 = (1 <<11 ), -TINT2 = (1 <<10 ), -TINT1 = (1 <<9 ), -TINT0 = (1 <<8 ), -UINT = (1 <<7 ), -STINT = (1 <<4 ), -RINT0 = (1 <<0 ), +INTR =BIT (31 ), +PCSINT =BIT (28 ), +LCINT =BIT (27 ), +APINT5 =BIT (26 ), +APINT4 =BIT (25 ), +APINT3 =BIT (24 ), +TINT_SUM =BIT (23 ), +APINT2 =BIT (22 ), +APINT1 =BIT (21 ), +APINT0 =BIT (20 ), +MIIPDTINT =BIT (19 ), +MCCINT =BIT (17 ), +MREINT =BIT (16 ), +RINT_SUM =BIT (15 ), +SPNDINT =BIT (14 ), +MPINT =BIT (13 ), +SINT =BIT (12 ), +TINT3 =BIT (11 ), +TINT2 =BIT (10 ), +TINT1 =BIT (9 ), +TINT0 =BIT (8 ), +UINT =BIT (7 ), +STINT =BIT (4 ), +RINT0 =BIT (0 ), }INT0_BITS ; typedef enum { /* VAL3 */ - LCINTEN = (1 << 27), - APINT5EN = (1 << 26), - APINT4EN = (1 << 25), - APINT3EN = (1 << 24), + LCINTEN = BIT(27), + APINT5EN = BIT(26), + APINT4EN = BIT(25), + APINT3EN = BIT(24), /* VAL2 */ - APINT2EN = (1 << 22), - APINT1EN = (1 << 21), - APINT0EN = (1 << 20), - MIIPDTINTEN = (1 << 19), - MCCIINTEN = (1 << 18), - MCCINTEN = (1 << 17), - MREINTEN = (1 << 16), + APINT2EN = BIT(22), + APINT1EN = BIT(21), + APINT0EN = BIT(20), + MIIPDTINTEN = BIT(19), + MCCIINTEN = BIT(18), + MCCINTEN = BIT(17), + MREINTEN = BIT(16), /* VAL1 */ - SPNDINTEN = (1 << 14), - MPINTEN = (1 << 13), - TINTEN3 = (1 << 11), - SINTEN = (1 << 12), - TINTEN2 = (1 << 10), - TINTEN1 = (1 << 9), - TINTEN0 = (1 << 8), + SPNDINTEN = BIT(14), + MPINTEN = BIT(13), + TINTEN3 = BIT(11), + SINTEN = BIT(12), + TINTEN2 = BIT(10), + TINTEN1 = BIT(9), + TINTEN0 = BIT(8), /* VAL0 */ - STINTEN = (1 << 4), - RINTEN0 = (1 << 0), + STINTEN = BIT(4), + RINTEN0 = BIT(0), INTEN0_CLEAR = 0x1F7F7F1F, /* Command style register */
@@ -134,17 +134,17 @@ typedef enum {typedef enum { -PMAT_DET = (1 <<12 ), -MP_DET = (1 <<11 ), -LC_DET = (1 <<10 ), -SPEED_MASK = (1 <<9 )|(1 <<8 )|(1 <<7 ), -FULL_DPLX = (1 <<6 ), -LINK_STATS = (1 <<5 ), -AUTONEG_COMPLETE = (1 <<4 ), -MIIPD = (1 <<3 ), -RX_SUSPENDED = (1 <<2 ), -TX_SUSPENDED = (1 <<1 ), -RUNNING = (1 <<0 ), +PMAT_DET =BIT (12 ), +MP_DET =BIT (11 ), +LC_DET =BIT (10 ), +SPEED_MASK =BIT (9 ) |BIT (8 ) |BIT (7 ), +FULL_DPLX =BIT (6 ), +LINK_STATS =BIT (5 ), +AUTONEG_COMPLETE =BIT (4 ), +MIIPD =BIT (3 ), +RX_SUSPENDED =BIT (2 ), +TX_SUSPENDED =BIT (1 ), +RUNNING =BIT (0 ), }STAT0_BITS ;
de2104x.c +205 -205
562 lines not on this page · raw message
ethtool.c +9 -9
@@ -128,7 +128,7 @@ struct feature_defs {#define FEATURE_BITS_TO_BLOCKS (n_bits) DIV_ROUND_UP(n_bits, 32U)#define FEATURE_WORD (blocks, index, field) ((blocks)[(index) / 32U].field) -#define FEATURE_FIELD_FLAG (index) (1U << (index) % 32U) +#define FEATURE_FIELD_FLAG (index) (BIT((index)) % 32U)#define FEATURE_BIT_SET (blocks, index, field) \ (FEATURE_WORD(blocks, index, field) |= FEATURE_FIELD_FLAG(index))#define FEATURE_BIT_CLEAR (blocks, index, field) \
@@ -1667,7 +1667,7 @@ static int dump_tsinfo(const struct ethtool_ts_info *info)fprintf (stdout,"Capabilities:\n" );for (i =0 ; i <N_SOTS ; i++) { -if (info->so_timestamping & (1 << i)) +if (info->so_timestamping &BIT (i))fprintf (stdout,"\t%s\n" , so_timestamping_labels[i]); }
@@ -1686,7 +1686,7 @@ static int dump_tsinfo(const struct ethtool_ts_info *info)fprintf (stdout,"\n" );for (i =0 ; i <N_TX_TYPES ; i++) { -if (info->tx_types & (1 << i)) +if (info->tx_types &BIT (i))fprintf (stdout,"\t%s\n" , tx_type_labels[i]); }
@@ -1698,7 +1698,7 @@ static int dump_tsinfo(const struct ethtool_ts_info *info)fprintf (stdout,"\n" );for (i =0 ; i <N_RX_FILTERS ; i++) { -if (info->rx_filters & (1 << i)) +if (info->rx_filters &BIT (i))fprintf (stdout,"\t%s\n" , rx_filter_labels[i]); }
@@ -1719,7 +1719,7 @@ get_stringset(struct cmd_context *ctx, enum ethtool_stringset set_id, sset_info.hdr.cmd =ETHTOOL_GSSET_INFO ; sset_info.hdr.reserved =0 ; - sset_info.hdr.sset_mask =1ULL << set_id; + sset_info.hdr.sset_mask =BIT_ULL (set_id);if (send_ioctl (ctx, &sset_info) ==0 ) {const u32 *sset_lengths = sset_info.hdr.data;
@@ -4029,7 +4029,7 @@ static int do_grxfh(struct cmd_context *ctx)for (i =0 ; i < hfuncs->len; i++)printf (" %s: %s\n" , (const char *)hfuncs->data + i *ETH_GSTRING_LEN , - (rss->hfunc & (1 << i)) ?"on" :"off" ); + (rss->hfunc &BIT (i)) ?"on" :"off" ); out:free (hfuncs);
@@ -4315,7 +4315,7 @@ static int do_srxfh(struct cmd_context *ctx) i * ETH_GSTRING_LEN);if (!strncmp (hfunc_name, req_hfunc_name,ETH_GSTRING_LEN )) - req_hfunc = (u32 )1 << i; + req_hfunc =BIT (i); }if (!req_hfunc) {
@@ -4722,7 +4722,7 @@ static int do_gprivflags(struct cmd_context *ctx)printf ("%-*s: %s\n" , max_len, (const char *)strings->data + i *ETH_GSTRING_LEN , - (flags.data & (1U << i)) ?"on" :"off" ); + (flags.data &BIT (i)) ?"on" :"off" ); rc =0 ;
@@ -4769,7 +4769,7 @@ static int do_sprivflags(struct cmd_context *ctx) i * ETH_GSTRING_LEN); cmdline[i].type =CMDL_FLAG ; cmdline[i].wanted_val = &wanted_flags; - cmdline[i].flag_val =1U << i; + cmdline[i].flag_val =BIT (i); cmdline[i].seen_val = &seen_flags; }parse_generic_cmdline (ctx, &any_changed, cmdline, strings->len);
internal.h +13 -13
@@ -97,17 +97,17 @@ static inline u64 cpu_to_be64(u64 value)static inline void set_bit (unsigned int nr,unsigned long *addr) { - addr[nr /BITS_PER_LONG ] |=1UL << (nr %BITS_PER_LONG ); + addr[nr /BITS_PER_LONG ] |=BIT_ULL (nr %BITS_PER_LONG ); }static inline void clear_bit (unsigned int nr,unsigned long *addr) { - addr[nr /BITS_PER_LONG ] &= ~(1UL << (nr %BITS_PER_LONG )); + addr[nr /BITS_PER_LONG ] &= ~BIT_ULL (nr %BITS_PER_LONG ); }static inline int test_bit (unsigned int nr,const unsigned long *addr) { -return !!((1UL << (nr %BITS_PER_LONG )) & +return !!(BIT_ULL (nr %BITS_PER_LONG ) & (((unsigned long *)addr)[nr /BITS_PER_LONG ])); }
@@ -130,19 +130,19 @@ enum {static inline bool debug_on (unsigned long debug,unsigned int bit) { -return (debug & (1 << bit)); +return (debug &BIT (bit)); }/* Internal values for old-style offload flags. Values and names * must not clash with the flags defined for ETHTOOL_{G,S}FLAGS. */ -#define ETH_FLAG_RXCSUM (1 << 0) -#define ETH_FLAG_TXCSUM (1 << 1) -#define ETH_FLAG_SG (1 << 2) -#define ETH_FLAG_TSO (1 << 3) -#define ETH_FLAG_UFO (1 << 4) -#define ETH_FLAG_GSO (1 << 5) -#define ETH_FLAG_GRO (1 << 6) +#define ETH_FLAG_RXCSUM BIT(0) +#define ETH_FLAG_TXCSUM BIT(1) +#define ETH_FLAG_SG BIT(2) +#define ETH_FLAG_TSO BIT(3) +#define ETH_FLAG_UFO BIT(4) +#define ETH_FLAG_GSO BIT(5) +#define ETH_FLAG_GRO BIT(6)#define ETH_FLAG_INT_MASK (ETH_FLAG_RXCSUM | ETH_FLAG_TXCSUM | \ ETH_FLAG_SG | ETH_FLAG_TSO | ETH_FLAG_UFO | \ ETH_FLAG_GSO | ETH_FLAG_GRO),
@@ -205,14 +205,14 @@ static inline int ethtool_link_mode_test_bit(unsigned int nr, const u32 *mask) {if (nr >=ETHTOOL_LINK_MODE_MASK_MAX_KERNEL_NBITS )return !!0 ; -return !!(mask[nr /32 ] & (1UL << (nr %32 ))); +return !!(mask[nr /32 ] &BIT (nr %32 )); }static inline int ethtool_link_mode_set_bit (unsigned int nr,u32 *mask) {if (nr >=ETHTOOL_LINK_MODE_MASK_MAX_KERNEL_NBITS )return -1 ; - mask[nr /32 ] |= (1UL << (nr %32 )); + mask[nr /32 ] |=BIT (nr %32 );return 0 ; }
natsemi.c +179 -179
441 lines not on this page · raw message
netlink/bitset.c +3 -3
@@ -75,7 +75,7 @@ bool bitset_get_bit(const struct nlattr *bitset, bool mask, unsigned int idx,if (idx >=8 *mnl_attr_get_payload_len (bits))return false; -return bitmap[idx /32 ] & (1U << (idx %32 )); +return bitmap[idx /32 ] &BIT (idx %32 ); } bits = bitset_tb[ETHTOOL_A_BITSET_BITS ];
@@ -227,9 +227,9 @@ int walk_bitset(const struct nlattr *bitset, const struct stringset *labels, val_bm =mnl_attr_get_payload (bits); mask_bm = mask ?mnl_attr_get_payload (mask) :NULL ;for (idx =0 ; idx < count; idx++) -if (!mask_bm || (mask_bm[idx /32 ] & (1 << (idx %32 )))) +if (!mask_bm || (mask_bm[idx /32 ] &BIT (idx %32 )))cb (idx,get_string (labels, idx), - val_bm[idx /32 ] & (1 << (idx %32 )), data); + val_bm[idx /32 ] &BIT (idx %32 ), data);return 0 ; }
netlink/features.c +2 -2
@@ -57,7 +57,7 @@ static int prepare_feature_results(const struct nlattr *const *tb,static bool feature_on (const uint32_t *bitmap,unsigned int idx) { -return bitmap[idx /32 ] & (1UL << (idx %32 )); +return bitmap[idx /32 ] &BIT (idx %32 ); } static void dump_feature(const struct feature_results *results,
@@ -302,7 +302,7 @@ static void set_sf_req_mask(struct nl_context *nlctx, unsigned int idx) {struct sfeatures_context *sfctx = nlctx->cmd_private; - sfctx->req_mask[idx /32 ] |= (1UL << (idx %32 )); + sfctx->req_mask[idx /32 ] |=BIT (idx %32 ); } static int fill_legacy_flag(struct nl_context *nlctx, const char *flag_name,
netlink/monitor.c +2 -2
@@ -87,12 +87,12 @@ static void clear_filter(struct nl_context *nlctx)static bool test_filter_cmd (const struct nl_context *nlctx,unsigned int cmd) { -return nlctx->filter_cmds[cmd /32 ] & (1U << (cmd %32 )); +return nlctx->filter_cmds[cmd /32 ] &BIT (cmd %32 ); }static void set_filter_cmd (struct nl_context *nlctx,unsigned int cmd) { - nlctx->filter_cmds[cmd /32 ] |= (1U << (cmd %32 )); + nlctx->filter_cmds[cmd /32 ] |=BIT (cmd %32 ); }static void set_filter_all (struct nl_context *nlctx)
netlink/parser.c +2 -2
@@ -910,12 +910,12 @@ static const struct param_parser *find_parser(const struct param_parser *params,static bool __parser_bit (const uint64_t *map,unsigned int idx) { -return map[idx /64 ] & (1 << (idx %64 )); +return map[idx /64 ] &BIT (idx %64 ); }static void __parser_set (uint64_t *map,unsigned int idx) { - map[idx /64 ] |= (1 << (idx %64 )); + map[idx /64 ] |=BIT (idx %64 ); } static void __parser_set_group(const struct param_parser *params,
netlink/settings.c +5 -5
@@ -275,7 +275,7 @@ int dump_link_modes(struct nl_context *nlctx, const struct nlattr *bitset,const uint32_t *raw_data =mnl_attr_get_payload (bits);char buff[14 ]; -if (!(raw_data[idx /32 ] & (1U << (idx %32 )))) +if (!(raw_data[idx /32 ] &BIT (idx %32 )))continue ;if (!lm_class_match (idx, class))continue ;
@@ -782,9 +782,9 @@ void wol_modes_cb(unsigned int idx, const char *name __maybe_unused, bool val,if (idx >=32 )return ; - wol->supported |= (1U << idx); + wol->supported |=BIT (idx);if (val) - wol->wolopts |= (1U << idx); + wol->wolopts |=BIT (idx); }int wol_reply_cb (const struct nlmsghdr *nlhdr,void *data)
@@ -832,7 +832,7 @@ void msgmask_cb(unsigned int idx, const char *name __maybe_unused, bool val,if (idx >=32 )return ;if (val) - *msg_mask |= (1U << idx); + *msg_mask |=BIT (idx); } void msgmask_cb2(unsigned int idx __maybe_unused, const char *name,
@@ -1172,7 +1172,7 @@ static int linkmodes_reply_advert_all_cb(const struct nlmsghdr *nlhdr,/* keep only "real" link modes */ for (i =0 ; i < modes_count; i++)if (!lm_class_match (i,LM_CLASS_REAL )) - supported_modes[i /32 ] &= ~((uint32_t )1 << (i %32 )); + supported_modes[i /32 ] &= ~BIT (i %32 ); req_bitset =ethnla_nest_start (req_msgbuff,ETHTOOL_A_LINKMODES_OURS );if (!req_bitset)
netlink/stats.c +1 -1
@@ -244,7 +244,7 @@ static int stats_parse_all_groups(struct nl_context *nlctx, uint16_t type,return -ENOMEM ;for (i =0 ; i < nbits; i++) - bits[i /32 ] |=1U << (i %32 ); + bits[i /32 ] |=BIT (i %32 ); ret = -EMSGSIZE ; nest =ethnla_nest_start (msgbuff, type);
qsfp.h +173 -173
499 lines not on this page · raw message
realtek.c +24 -24
77 lines not on this page · raw message
rxclass.c +1 -1
@@ -446,7 +446,7 @@ static int rmgr_find_empty_slot(struct rmgr_ctrl *rmgr,* If loc rolls over it should be greater than or equal to rmgr->size * and as such we know we have reached the end of the list. */ -if (!~(rmgr->slot[slot_num] | (~1UL << rmgr->size %BITS_PER_LONG ))) { +if (!~(rmgr->slot[slot_num] | ~BIT_ULL (rmgr->size %BITS_PER_LONG ))) { loc -=1 + (loc %BITS_PER_LONG ); slot_num--; }
sfc.c +1 -1
@@ -3773,7 +3773,7 @@ print_field_value(const struct efx_nic_reg_field *field, const u8 *buf) digit = buf[left >>3 ];if ((left &7 ) + sig_bits >8 ) digit |= buf[(left >>3 ) +1 ] <<8 ; - digit = (digit >> (left &7 )) & ((1 << sig_bits) -1 ); + digit = (digit >> (left &7 )) & (BIT (sig_bits) -1 );printf ("%x" , digit); sig_bits =4 ;/* for all subsequent digits */ }
sfpdiag.c +29 -29
71 lines not on this page · raw message
sfpid.c +73 -73
253 lines not on this page · raw message
tse.c +1 -1
@@ -17,7 +17,7 @@int bitset (u32 val,int bit) { -if (val & (1 << bit)) +if (val &BIT (bit))return 1 ;return 0 ; }
Signature · 1 line
2.31.1
PATCH v2 11/13 ethtool: fix missing free of memory after failure
In reply to Jesse Brandeburgcppcheck warns:
test-common.c:106:2: error: Common realloc mistake: 'block' nulled but not freed upon failure [memleakOnRealloc]
block = realloc(block, sizeof(*block) + size);
^
Fix the issue by storing a local copy of the old pointer and using that to free the original if the realloc fails, as the manual for realloc() suggests.
--- test-common.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
test-common.c +6 -3
@@ -97,15 +97,18 @@ void test_free(void *ptr)void *test_realloc (void *ptr,size_t size) { -struct list_head *block =NULL ; +struct list_head *block =NULL , *oldblock;if (ptr) { block = (struct list_head *)ptr -1 ;list_del (block); } - block =realloc (block,sizeof (*block) + size); -if (!block) + oldblock = block; + block =realloc (oldblock,sizeof (*oldblock) + size); +if (!block) { +free (oldblock);return NULL ; + }list_add (block, &malloc_list);return block +1 ; }
Signature · 1 line
2.31.1
Re: [PATCH ethtool v2 11/13] ethtool: fix missing free of memory after failure
Quoted 10 lines · Jesse Brandeburg
cppcheck warns:
test-common.c:106:2: error: Common realloc mistake: 'block' nulled but not freed upon failure [memleakOnRealloc]
block =realloc(block, sizeof(*block) + size);
^Fix the issue by storing a local copy of the old pointer and using that to free the original if the realloc fails, as the manual for
realloc()suggests.Signed-off-by Jesse Brandeburg <[email protected]>
Quoted 33 lines
--- test-common.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)test-common.c +6
-3@@ -97,15 +97,18 @@ void test_free(void *ptr)void *test_realloc (void *ptr,size_t size) { -struct list_head *block =NULL ; +struct list_head *block =NULL , *oldblock;if (ptr) { block = (struct list_head *)ptr -1 ;list_del (block); } - block =realloc (block,sizeof (*block) + size); -if (!block) + oldblock = block; + block =realloc (oldblock,sizeof (*oldblock) + size); +if (!block) { +free (oldblock);return NULL ; + }list_add (block, &malloc_list);return block +1 ; }Signature · 1 line
2.31.1
PATCH v2 12/13 ethtool: fix leak of memory after realloc
In reply to Jesse Brandeburgcppcheck finds:netlink/msgbuff.c:63:2: error: Memory leak: nbuff [memleak]
return 0;
^
This is a pretty common problem with realloc() and just requires handling the return code correctly which makes us refactor to reuse the structure free/reinit code that already exists in msgbuf_done().
This fixes the code flow by doing the right thing if realloc() succeeds and if it fails then being sure to free the original memory and replicate the steps the original code took.
--- netlink/msgbuff.c | 39 ++++++++++++++++++--------------------- 1 file changed, 18 insertions(+), 21 deletions(-)
netlink/msgbuff.c +18 -21
@@ -15,6 +15,20 @@#define MAX_MSG_SIZE (4 << 20)/* 4 MB */ +/** +* msg_done() - destroy a message buffer +* @msgbuff: message buffer +* +* Free the buffer and reset size and remaining size. +*/ +void msgbuff_done (struct nl_msg_buff *msgbuff) +{ +free (msgbuff->buff); + msgbuff->buff =NULL ; + msgbuff->size =0 ; + msgbuff->left =0 ; +} +/** * msgbuff_realloc() - reallocate buffer if needed * @msgbuff: message buffer
@@ -43,19 +57,16 @@ int msgbuff_realloc(struct nl_msg_buff *msgbuff, unsigned int new_size)if (new_size >MAX_MSG_SIZE )return -EMSGSIZE ; nbuff =realloc (msgbuff->buff, new_size); -if (!nbuff) { - msgbuff->buff =NULL ; - msgbuff->size =0 ; - msgbuff->left =0 ; -return -ENOMEM ; - } -if (nbuff != msgbuff->buff) { +if (nbuff) {if (new_size > old_size)memset (nbuff + old_size,'\0' , new_size - old_size); msgbuff->nlhdr = (struct nlmsghdr *)(nbuff + nlhdr_off); msgbuff->genlhdr = (struct genlmsghdr *)(nbuff + genlhdr_off); msgbuff->payload = nbuff + payload_off; msgbuff->buff = nbuff; + }else { +msgbuff_done (msgbuff); +return -ENOMEM ; } msgbuff->size = new_size; msgbuff->left += (new_size - old_size);
@@ -240,17 +251,3 @@ void msgbuff_init(struct nl_msg_buff *msgbuff) {memset (msgbuff,'\0' ,sizeof (*msgbuff)); } - -/** -* msg_done() - destroy a message buffer -* @msgbuff: message buffer -* -* Free the buffer and reset size and remaining size. -*/ -void msgbuff_done (struct nl_msg_buff *msgbuff) -{ -free (msgbuff->buff); - msgbuff->buff =NULL ; - msgbuff->size =0 ; - msgbuff->left =0 ; -}
Signature · 1 line
2.31.1
Re: [PATCH ethtool v2 12/13] ethtool: fix leak of memory after realloc
Quoted 4 lines · Jesse Brandeburg
cppcheck finds:
netlink/msgbuff.c:63:2: error: Memory leak: nbuff [memleak]
return 0;
^
This reported error is misleading, the commit message should make it clear that the leak it addresses is not of nbuff but of the original msgbuff->buff (on failure).
Quoted 17 lines
This is a pretty common problem with
realloc()and just requires handling the return code correctly which makes us refactor to reuse the structure free/reinit code that already exists inmsgbuf_done().This fixes the code flow by doing the right thing if
realloc()succeeds and if it fails then being sure to free the original memory and replicate the steps the original code took.Signed-off-by Jesse Brandeburg <[email protected]>--- netlink/msgbuff.c | 39 ++++++++++++++++++--------------------- 1 file changed, 18 insertions(+), 21 deletions(-)netlink/msgbuff.c +0
-0
[...]
Quoted 14 lines
netlink/msgbuff.c +1
-7@@ -43,19 +57,16 @@ int msgbuff_realloc(struct nl_msg_buff *msgbuff, unsigned int new_size)if (new_size >MAX_MSG_SIZE )return -EMSGSIZE ; nbuff =realloc (msgbuff->buff, new_size); -if (!nbuff) { - msgbuff->buff =NULL ; - msgbuff->size =0 ; - msgbuff->left =0 ; -return -ENOMEM ; - } -if (nbuff != msgbuff->buff) { +if (nbuff) {if (new_size > old_size)memset (nbuff + old_size,'\0' , new_size - old_size);
netlink/msgbuff.c int msgbuff_realloc(struct nl_msg_buff *msgbuff, unsigned int new_size) · line 72
Quoted 10 lines
netlink/msgbuff.c +3
-0msgbuff->nlhdr = (struct nlmsghdr *)(nbuff + nlhdr_off); msgbuff->genlhdr = (struct genlmsghdr *)(nbuff + genlhdr_off); msgbuff->payload = nbuff + payload_off; msgbuff->buff = nbuff; + }else { +msgbuff_done (msgbuff); +return -ENOMEM ; } msgbuff->size = new_size; msgbuff->left += (new_size - old_size);
If nbuff is null (reallocation failed), we bail out anyway so there is no point putting part of the followin code inside an if and leaving the rest outside. Also, while it makes sense to zero the new part of the buffer even if the buffer is not moved, there is no reason to reinitialize all the pointers. How about this:
if (!nbuff) {
msgbuff_done(msgbuff);
return -ENOMEM;
}
if (new_size > old_size)
memset(nbuff + old_size, '\0', new_size - old_size);
if (nbuff != msgbuff->buff) {
msgbuff->nlhdr = (struct nlmsghdr *)(nbuff + nlhdr_off);
msgbuff->genlhdr = (struct genlmsghdr *)(nbuff + genlhdr_off);
msgbuff->payload = nbuff + payload_off;
msgbuff->buff = nbuff;
}
msgbuff->size = new_size;
msgbuff->left += (new_size - old_size);Or we could forget about the "if (nbuff != msgbuff->buff)" test and assign the four pointers to values they already have in case the block stays in place. The code would look a bit tidier and the difference would be negligible.
And looking at the code again, the "new_size > old_size" check can be omitted too as we already have
if (new_size <= old_size) return 0;
before the realloc() call. This is a relic from a development version where realloc() was also used to shrink the buffer if new requested size was smaller than current.
Michal
PATCH v2 13/13 ethtool: fix bug and use standard string parsing
In reply to Jesse BrandeburgThe parse_reset function was open-coding string parsing routines and can be converted to using standard routines. It was trying to be tricky and parse partial strings to make things like "mgmt" and "mgmt-shared" strings mostly use the same code. This is better done with strncmp().
This also fixes an array overflow bug where it's possible for the for loop to access past the end of the input array, which is bad.
--- ethtool.c | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-)
ethtool.c +11 -7
@@ -5280,17 +5280,21 @@ static int do_get_phy_tunable(struct cmd_context *ctx)static __u32 parse_reset (char *val,__u32 bitset,char *arg,__u32 *data) {__u32 bitval =0 ; -int i; +int vallen =strlen (val); +int strret;/* Check for component match */ -for (i =0 ; val[i] !='\0' ; i++) -if (arg[i] != val[i]) -return 0 ; + strret =strncmp (arg, val, vallen); +if (strret <0 ) +return 0 ; -/* Check if component has -shared specified or not */ -if (arg[i] =='\0' ) +/* if perfect match to val +* else +* Check if component has -shared specified or not +*/ +if (strret ==0 ) bitval = bitset; -else if (!strcmp (arg+i,"-shared" )) +else if (!strcmp (arg + vallen,"-shared" )) bitval = bitset <<ETH_RESET_SHARED_SHIFT ;if (bitval) {
Signature · 1 line
2.31.1
Re: [PATCH ethtool v2 13/13] ethtool: fix bug and use standard string parsing
Quoted 22 lines · Jesse Brandeburg
The
parse_resetfunction was open-coding string parsing routines and can be converted to using standard routines. It was trying to be tricky and parse partial strings to make things like "mgmt" and "mgmt-shared" strings mostly use the same code. This is better done withstrncmp().This also fixes an array overflow bug where it's possible for the for loop to access past the end of the input array, which is bad.
Signed-off-by Jesse Brandeburg <[email protected]>--- ethtool.c | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-)ethtool.c +0
-1@@ -5280,17 +5280,21 @@ static int do_get_phy_tunable(struct cmd_context *ctx)static __u32 parse_reset (char *val,__u32 bitset,char *arg,__u32 *data) {__u32 bitval =0 ; -int i;
ethtool.c static int do_get_phy_tunable(struct cmd_context *ctx) · line 5289
Quoted 10 lines
ethtool.c +5
-3+int vallen =strlen (val); +int strret;/* Check for component match */ -for (i =0 ; val[i] !='\0' ; i++) -if (arg[i] != val[i]) -return 0 ; + strret =strncmp (arg, val, vallen); +if (strret <0 ) +return 0 ;
Shouldn't this be "if (strret)"? Unless I missed something, this would lead to e.g. "zzzz-shared" being matched for "mgmt-shared" (with usual locale) because you would get strret > 0 here and strcmp() == 0 below.
ethtool.c static int do_get_phy_tunable(struct cmd_context *ctx) · line 5296
Quoted 9 lines
ethtool.c +5
-2-/* Check if component has -shared specified or not */ -if (arg[i] =='\0' ) +/* if perfect match to val +* else +* Check if component has -shared specified or not +*/ +if (strret ==0 ) bitval = bitset;
And this should be "if (!arg[vallen])", I believe.
Michal
Quoted 8 lines
ethtool.c +1
-1-else if (!strcmp (arg+i,"-shared" )) +else if (!strcmp (arg + vallen,"-shared" )) bitval = bitset <<ETH_RESET_SHARED_SHIFT ;if (bitval) {Signature · 1 line
2.31.1