Subject: 64 bit shell arithmetic
To: NetBSD Tech Userlevel <tech-userlevel@netbsd.org>
From: Markus Mayer <mmayer@redback.com>
List: tech-userlevel
Date: 03/23/2007 17:17:37
Hi,

It looks like I discovered a problem with shell arithmetic with large
number (numbers larger than "signed long").

Here is an example (determine the amount of RAM and convert it into
megabytes):

# total_ram=`/sbin/sysctl hw.usermem64 | sed -e 's/.* = //'`
# echo $total_ram
8388505600
# ram_mb=$(($total_ram/1048576))
# echo $ram_mb
-192

-192 MB is obviously wrong.

I am assuming this is related to this code in usr/src/bin/sh/arith_lex.l

extern int yylval;
[...]
0x[0-9a-fA-F]+	{ yylval = strtol(yytext, 0, 0); return(ARITH_NUM); }
0[0-7]*		{ yylval = strtol(yytext, 0, 0); return(ARITH_NUM); }
[1-9][0-9]*	{ yylval = strtol(yytext, 0, 0); return(ARITH_NUM); }

Is there a fairly easy way to "fix" this issue?

It does work with bash and ksh, but this is supposed to be a small 
footprint system so I'd rather not include either of those.

Regards,
-Markus

-- 
Markus Mayer
Redback Networks Inc.
(604) 629-7251