Bug Summary

File:src/usr.bin/units/units.c
Warning:line 204, column 1
Potential memory leak

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name units.c -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 1 -pic-is-pie -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -target-feature +retpoline-indirect-calls -target-feature +retpoline-indirect-branches -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/usr.bin/units/obj -resource-dir /usr/local/lib/clang/13.0.0 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -fdebug-compilation-dir=/usr/src/usr.bin/units/obj -ferror-limit 19 -fwrapv -D_RET_PROTECTOR -ret-protector -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c /usr/src/usr.bin/units/units.c
1/* $OpenBSD: units.c,v 1.22 2015/10/09 01:37:09 deraadt Exp $ */
2/* $NetBSD: units.c,v 1.6 1996/04/06 06:01:03 thorpej Exp $ */
3
4/*
5 * units.c Copyright (c) 1993 by Adrian Mariano (adrian@cam.cornell.edu)
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. The name of the author may not be used to endorse or promote products
13 * derived from this software without specific prior written permission.
14 * Disclaimer: This software is provided by the author "as is". The author
15 * shall not be liable for any damages caused in any way by this software.
16 *
17 * I would appreciate (though I do not require) receiving a copy of any
18 * improvements you might make to this program.
19 */
20
21#include <ctype.h>
22#include <stdio.h>
23#include <string.h>
24#include <stdlib.h>
25#include <unistd.h>
26#include <err.h>
27
28#define UNITSFILE"/usr/share/misc/units.lib" "/usr/share/misc/units.lib"
29
30#define VERSION"1.0" "1.0"
31
32#define MAXUNITS1000 1000
33#define MAXPREFIXES100 100
34
35#define MAXSUBUNITS500 500
36
37#define PRIMITIVECHAR'!' '!'
38
39char *powerstring = "^";
40
41struct {
42 char *uname;
43 char *uval;
44} unittable[MAXUNITS1000];
45
46struct unittype {
47 char *numerator[MAXSUBUNITS500];
48 char *denominator[MAXSUBUNITS500];
49 double factor;
50};
51
52struct {
53 char *prefixname;
54 char *prefixval;
55} prefixtable[MAXPREFIXES100];
56
57
58char *NULLUNIT = "";
59
60int unitcount;
61int prefixcount;
62
63char *dupstr(char *);
64void readunits(char *);
65void initializeunit(struct unittype *);
66int addsubunit(char *[], char *);
67void showunit(struct unittype *);
68void zeroerror(void);
69int addunit(struct unittype *, char *, int);
70int compare(const void *, const void *);
71void sortunit(struct unittype *);
72void cancelunit(struct unittype *);
73char *lookupunit(char *);
74int reduceproduct(struct unittype *, int);
75int reduceunit(struct unittype *);
76int compareproducts(char **, char **);
77int compareunits(struct unittype *, struct unittype *);
78int completereduce(struct unittype *);
79void showanswer(struct unittype *, struct unittype *);
80void usage(void);
81
82char *
83dupstr(char *str)
84{
85 char *ret;
86
87 ret = strdup(str);
45
Memory is allocated
88 if (!ret) {
46
Assuming 'ret' is non-null
47
Taking false branch
89 fprintf(stderr(&__sF[2]), "Memory allocation error\n");
90 exit(3);
91 }
92 return (ret);
93}
94
95
96void
97readunits(char *userfile)
98{
99 char line[512], *lineptr;
100 int len, linenum, i;
101 FILE *unitfile;
102
103 unitcount = 0;
104 linenum = 0;
105
106 if (userfile) {
107 unitfile = fopen(userfile, "r");
108 if (!unitfile) {
109 fprintf(stderr(&__sF[2]), "Unable to open units file '%s'\n",
110 userfile);
111 exit(1);
112 }
113 } else {
114 unitfile = fopen(UNITSFILE"/usr/share/misc/units.lib", "r");
115 if (!unitfile) {
116 fprintf(stderr(&__sF[2]), "Can't find units file '%s'\n",
117 UNITSFILE"/usr/share/misc/units.lib");
118 exit(1);
119 }
120 }
121 while (!feof(unitfile)(!__isthreaded ? (((unitfile)->_flags & 0x0020) != 0) :
(feof)(unitfile))
) {
122 if (!fgets(line, sizeof(line), unitfile))
123 break;
124 linenum++;
125 lineptr = line;
126 if (*lineptr == '/')
127 continue;
128 lineptr += strspn(lineptr, " \n\t");
129 len = strcspn(lineptr, " \n\t");
130 lineptr[len] = 0;
131 if (!strlen(lineptr))
132 continue;
133 if (lineptr[strlen(lineptr) - 1] == '-') { /* it's a prefix */
134 if (prefixcount == MAXPREFIXES100) {
135 fprintf(stderr(&__sF[2]),
136 "Memory for prefixes exceeded in line %d\n",
137 linenum);
138 continue;
139 }
140
141 lineptr[strlen(lineptr) - 1] = 0;
142 for (i = 0; i < prefixcount; i++) {
143 if (!strcmp(prefixtable[i].prefixname, lineptr))
144 break;
145 }
146 if (i < prefixcount) {
147 fprintf(stderr(&__sF[2]), "Redefinition of prefix '%s' "
148 "on line %d ignored\n", lineptr, linenum);
149 continue; /* skip duplicate prefix */
150 }
151
152 prefixtable[prefixcount].prefixname = dupstr(lineptr);
153 lineptr += len + 1;
154 lineptr += strspn(lineptr, " \n\t");
155 len = strcspn(lineptr, "\n\t");
156 if (len == 0) {
157 fprintf(stderr(&__sF[2]), "Unexpected end of prefix on "
158 "line %d\n", linenum);
159 free(prefixtable[prefixcount].prefixname);
160 continue;
161 }
162 lineptr[len] = 0;
163 prefixtable[prefixcount++].prefixval = dupstr(lineptr);
164 } else { /* it's not a prefix */
165 if (unitcount == MAXUNITS1000) {
166 fprintf(stderr(&__sF[2]),
167 "Memory for units exceeded in line %d\n",
168 linenum);
169 continue;
170 }
171
172 for (i = 0; i < unitcount; i++) {
173 if (!strcmp(unittable[i].uname, lineptr))
174 break;
175 }
176 if (i < unitcount) {
177 fprintf(stderr(&__sF[2]), "Redefinition of unit '%s' "
178 "on line %d ignored\n", lineptr, linenum);
179 continue; /* skip duplicate unit */
180 }
181
182 unittable[unitcount].uname = dupstr(lineptr);
183 lineptr += len + 1;
184 lineptr += strspn(lineptr, " \n\t");
185 if (!strlen(lineptr)) {
186 fprintf(stderr(&__sF[2]), "Unexpected end of unit on "
187 "line %d\n", linenum);
188 free(unittable[unitcount].uname);
189 continue;
190 }
191 len = strcspn(lineptr, "\n\t");
192 lineptr[len] = 0;
193 unittable[unitcount++].uval = dupstr(lineptr);
194 }
195 }
196 fclose(unitfile);
197}
198
199void
200initializeunit(struct unittype *theunit)
201{
202 theunit->factor = 1.0;
203 theunit->numerator[0] = theunit->denominator[0] = NULL((void *)0);
204}
62
Potential memory leak
205
206
207int
208addsubunit(char *product[], char *toadd)
209{
210 char **ptr;
211
212 for (ptr = product; *ptr && *ptr != NULLUNIT; ptr++);
213 if (ptr >= product + MAXSUBUNITS500) {
42
Taking false branch
214 fprintf(stderr(&__sF[2]), "Memory overflow in unit reduction\n");
215 return 1;
216 }
217 if (!*ptr)
43
Taking true branch
218 *(ptr + 1) = 0;
219 *ptr = dupstr(toadd);
44
Calling 'dupstr'
48
Returned allocated memory
220 return 0;
221}
222
223
224void
225showunit(struct unittype *theunit)
226{
227 char **ptr;
228 int printedslash;
229 int counter = 1;
230
231 printf("\t%.8g", theunit->factor);
232 for (ptr = theunit->numerator; *ptr; ptr++) {
233 if (ptr > theunit->numerator && **ptr &&
234 !strcmp(*ptr, *(ptr - 1)))
235 counter++;
236 else {
237 if (counter > 1)
238 printf("%s%d", powerstring, counter);
239 if (**ptr)
240 printf(" %s", *ptr);
241 counter = 1;
242 }
243 }
244 if (counter > 1)
245 printf("%s%d", powerstring, counter);
246 counter = 1;
247 printedslash = 0;
248 for (ptr = theunit->denominator; *ptr; ptr++) {
249 if (ptr > theunit->denominator && **ptr &&
250 !strcmp(*ptr, *(ptr - 1)))
251 counter++;
252 else {
253 if (counter > 1)
254 printf("%s%d", powerstring, counter);
255 if (**ptr) {
256 if (!printedslash)
257 printf(" /");
258 printedslash = 1;
259 printf(" %s", *ptr);
260 }
261 counter = 1;
262 }
263 }
264 if (counter > 1)
265 printf("%s%d", powerstring, counter);
266 printf("\n");
267}
268
269
270void
271zeroerror(void)
272{
273 fprintf(stderr(&__sF[2]), "Unit reduces to zero\n");
274}
275
276/*
277 Adds the specified string to the unit.
278 Flip is 0 for adding normally, 1 for adding reciprocal.
279
280 Returns 0 for successful addition, nonzero on error.
281*/
282
283int
284addunit(struct unittype *theunit, char *toadd, int flip)
285{
286 char *scratch, *savescr;
287 char *item;
288 char *divider, *slash;
289 int doingtop;
290
291 savescr = scratch = dupstr(toadd);
292 for (slash = scratch + 1; *slash; slash++)
31
Loop condition is false. Execution continues on line 297
293 if (*slash == '-' &&
294 (tolower((unsigned char)*(slash - 1)) != 'e' ||
295 !strchr(".0123456789", *(slash + 1))))
296 *slash = ' ';
297 slash = strchr(scratch, '/');
298 if (slash)
32
Assuming 'slash' is null
33
Taking false branch
299 *slash = 0;
300 doingtop = 1;
301 do {
302 item = strtok(scratch, " *\t\n/");
303 while (item) {
34
Loop condition is true. Entering loop body
52
Loop condition is true. Entering loop body
304 if (strchr("0123456789.", *item)) { /* item is a number */
35
Assuming the condition is false
36
Taking false branch
53
Assuming the condition is true
54
Taking true branch
305 double num;
306
307 divider = strchr(item, '|');
308 if (divider) {
55
Assuming 'divider' is non-null
56
Taking true branch
309 *divider = 0;
310 num = atof(item);
311 if (!num) {
57
Assuming the condition is true
58
Taking true branch
312 zeroerror();
313 free(savescr);
314 return 1;
315 }
316 if (doingtop ^ flip)
317 theunit->factor *= num;
318 else
319 theunit->factor /= num;
320 num = atof(divider + 1);
321 if (!num) {
322 zeroerror();
323 free(savescr);
324 return 1;
325 }
326 if (doingtop ^ flip)
327 theunit->factor /= num;
328 else
329 theunit->factor *= num;
330 } else {
331 num = atof(item);
332 if (!num) {
333 zeroerror();
334 free(savescr);
335 return 1;
336 }
337 if (doingtop ^ flip)
338 theunit->factor *= num;
339 else
340 theunit->factor /= num;
341
342 }
343 } else { /* item is not a number */
344 int repeat = 1;
345
346 if (strchr("23456789",
37
Assuming the condition is false
38
Taking false branch
347 item[strlen(item) - 1])) {
348 repeat = item[strlen(item) - 1] - '0';
349 item[strlen(item) - 1] = 0;
350 }
351 for (; repeat; repeat--)
39
Loop condition is true. Entering loop body
51
Loop condition is false. Execution continues on line 359
352 if (addsubunit(doingtop ^ flip
40
'?' condition is true
41
Calling 'addsubunit'
49
Returned allocated memory via 1st parameter
50
Taking false branch
353 ? theunit->numerator
354 : theunit->denominator, item)) {
355 free(savescr);
356 return 1;
357 }
358 }
359 item = strtok(NULL((void *)0), " *\t/\n");
360 }
361 doingtop--;
362 if (slash) {
363 scratch = slash + 1;
364 } else
365 doingtop--;
366 } while (doingtop >= 0);
367 free(savescr);
368 return 0;
369}
370
371
372int
373compare(const void *item1, const void *item2)
374{
375 return strcmp(*(char **) item1, *(char **) item2);
376}
377
378
379void
380sortunit(struct unittype *theunit)
381{
382 char **ptr;
383 int count;
384
385 for (count = 0, ptr = theunit->numerator; *ptr; ptr++, count++);
386 qsort(theunit->numerator, count, sizeof(char *), compare);
387 for (count = 0, ptr = theunit->denominator; *ptr; ptr++, count++);
388 qsort(theunit->denominator, count, sizeof(char *), compare);
389}
390
391
392void
393cancelunit(struct unittype *theunit)
394{
395 char **den, **num;
396 int comp;
397
398 den = theunit->denominator;
399 num = theunit->numerator;
400
401 while (*num && *den) {
402 comp = strcmp(*den, *num);
403 if (!comp) {
404 *den++ = NULLUNIT;
405 *num++ = NULLUNIT;
406 } else if (comp < 0)
407 den++;
408 else
409 num++;
410 }
411}
412
413
414
415
416/*
417 Looks up the definition for the specified unit.
418 Returns a pointer to the definition or a null pointer
419 if the specified unit does not appear in the units table.
420*/
421
422static char buffer[500]; /* buffer for lookupunit answers with
423 prefixes */
424
425char *
426lookupunit(char *unit)
427{
428 size_t len;
429 int i;
430 char *copy;
431
432 for (i = 0; i < unitcount; i++) {
433 if (!strcmp(unittable[i].uname, unit))
434 return unittable[i].uval;
435 }
436
437 len = strlen(unit);
438 if (len == 0)
439 return NULL((void *)0);
440 if (unit[len - 1] == '^') {
441 copy = dupstr(unit);
442 copy[len - 1] = '\0';
443 for (i = 0; i < unitcount; i++) {
444 if (!strcmp(unittable[i].uname, copy)) {
445 strlcpy(buffer, copy, sizeof(buffer));
446 free(copy);
447 return buffer;
448 }
449 }
450 free(copy);
451 }
452 if (unit[len - 1] == 's') {
453 copy = dupstr(unit);
454 copy[len - 1] = '\0';
455 --len;
456 for (i = 0; i < unitcount; i++) {
457 if (!strcmp(unittable[i].uname, copy)) {
458 strlcpy(buffer, copy, sizeof(buffer));
459 free(copy);
460 return buffer;
461 }
462 }
463 if (len != 0 && copy[len - 1] == 'e') {
464 copy[len - 1] = 0;
465 for (i = 0; i < unitcount; i++) {
466 if (!strcmp(unittable[i].uname, copy)) {
467 strlcpy(buffer, copy, sizeof(buffer));
468 free(copy);
469 return buffer;
470 }
471 }
472 }
473 free(copy);
474 }
475 for (i = 0; i < prefixcount; i++) {
476 len = strlen(prefixtable[i].prefixname);
477 if (!strncmp(prefixtable[i].prefixname, unit, len)) {
478 if (!strlen(unit + len) || lookupunit(unit + len)) {
479 snprintf(buffer, sizeof(buffer), "%s %s",
480 prefixtable[i].prefixval, unit + len);
481 return buffer;
482 }
483 }
484 }
485 return NULL((void *)0);
486}
487
488
489
490/*
491 reduces a product of symbolic units to primitive units.
492 The three low bits are used to return flags:
493
494 bit 0 (1) set on if reductions were performed without error.
495 bit 1 (2) set on if no reductions are performed.
496 bit 2 (4) set on if an unknown unit is discovered.
497*/
498
499
500#define ERROR4 4
501
502int
503reduceproduct(struct unittype *theunit, int flip)
504{
505 char *toadd, **product;
506 int didsomething = 2;
507
508 if (flip)
509 product = theunit->denominator;
510 else
511 product = theunit->numerator;
512
513 for (; *product; product++) {
514
515 for (;;) {
516 if (!strlen(*product))
517 break;
518 toadd = lookupunit(*product);
519 if (!toadd) {
520 printf("unknown unit '%s'\n", *product);
521 return ERROR4;
522 }
523 if (strchr(toadd, PRIMITIVECHAR'!'))
524 break;
525 didsomething = 1;
526 if (*product != NULLUNIT) {
527 free(*product);
528 *product = NULLUNIT;
529 }
530 if (addunit(theunit, toadd, flip))
531 return ERROR4;
532 }
533 }
534 return didsomething;
535}
536
537
538/*
539 Reduces numerator and denominator of the specified unit.
540 Returns 0 on success, or 1 on unknown unit error.
541*/
542
543int
544reduceunit(struct unittype *theunit)
545{
546 int ret;
547
548 ret = 1;
549 while (ret & 1) {
550 ret = reduceproduct(theunit, 0) | reduceproduct(theunit, 1);
551 if (ret & 4)
552 return 1;
553 }
554 return 0;
555}
556
557
558int
559compareproducts(char **one, char **two)
560{
561 while (*one || *two) {
562 if (!*one && *two != NULLUNIT)
563 return 1;
564 if (!*two && *one != NULLUNIT)
565 return 1;
566 if (*one == NULLUNIT)
567 one++;
568 else if (*two == NULLUNIT)
569 two++;
570 else if (strcmp(*one, *two))
571 return 1;
572 else
573 one++, two++;
574 }
575 return 0;
576}
577
578
579/* Return zero if units are compatible, nonzero otherwise */
580
581int
582compareunits(struct unittype *first, struct unittype *second)
583{
584 return compareproducts(first->numerator, second->numerator) ||
585 compareproducts(first->denominator, second->denominator);
586}
587
588
589int
590completereduce(struct unittype *unit)
591{
592 if (reduceunit(unit))
593 return 1;
594 sortunit(unit);
595 cancelunit(unit);
596 return 0;
597}
598
599
600void
601showanswer(struct unittype *have, struct unittype *want)
602{
603 if (compareunits(have, want)) {
604 printf("conformability error\n");
605 showunit(have);
606 showunit(want);
607 } else
608 printf("\t* %.8g\n\t/ %.8g\n", have->factor / want->factor,
609 want->factor / have->factor);
610}
611
612
613void
614usage(void)
615{
616 fprintf(stderr(&__sF[2]),
617 "usage: units [-qv] [-f filename] [[count] from-unit to-unit]\n");
618 exit(3);
619}
620
621
622int
623main(int argc, char **argv)
624{
625
626 struct unittype have, want;
627 char havestr[81], wantstr[81];
628 int optchar;
629 char *userfile = 0;
630 int quiet = 0;
631
632 extern char *optarg;
633 extern int optind;
634
635 if (pledge("stdio rpath", NULL((void *)0)) == -1)
1
Assuming the condition is false
2
Taking false branch
636 err(1, "pledge");
637
638 while ((optchar = getopt(argc, argv, "vqf:")) != -1) {
3
Assuming the condition is true
4
Loop condition is true. Entering loop body
7
Assuming the condition is false
8
Loop condition is false. Execution continues on line 659
639 switch (optchar) {
5
Control jumps to 'case 102:' at line 640
640 case 'f':
641 userfile = optarg;
642 break;
6
Execution continues on line 638
643 case 'q':
644 quiet = 1;
645 break;
646 case 'v':
647 fprintf(stderr(&__sF[2]),
648 "units version %s Copyright (c) 1993 by Adrian Mariano\n",
649 VERSION"1.0");
650 fprintf(stderr(&__sF[2]),
651 "This program may be freely distributed\n");
652 usage();
653 default:
654 usage();
655 break;
656 }
657 }
658
659 argc -= optind;
660 argv += optind;
661
662 if (argc != 3 && argc != 2 && argc != 0)
9
Assuming 'argc' is not equal to 3
10
Assuming 'argc' is not equal to 2
11
Assuming 'argc' is equal to 0
12
Taking false branch
663 usage();
664
665 readunits(userfile);
666
667 if (pledge("stdio", NULL((void *)0)) == -1)
13
Assuming the condition is false
14
Taking false branch
668 err(1, "pledge");
669
670 if (argc
14.1
'argc' is not equal to 3
== 3) {
15
Taking false branch
671 strlcpy(havestr, argv[0], sizeof(havestr));
672 strlcat(havestr, " ", sizeof(havestr));
673 strlcat(havestr, argv[1], sizeof(havestr));
674 argc--;
675 argv++;
676 argv[0] = havestr;
677 }
678
679 if (argc
15.1
'argc' is not equal to 2
== 2) {
16
Taking false branch
680 strlcpy(havestr, argv[0], sizeof(havestr));
681 strlcpy(wantstr, argv[1], sizeof(wantstr));
682 initializeunit(&have);
683 addunit(&have, havestr, 0);
684 completereduce(&have);
685 initializeunit(&want);
686 addunit(&want, wantstr, 0);
687 completereduce(&want);
688 showanswer(&have, &want);
689 } else {
690 if (!quiet
16.1
'quiet' is 0
)
17
Taking true branch
691 printf("%d units, %d prefixes\n", unitcount,
692 prefixcount);
693 for (;;) {
18
Loop condition is true. Entering loop body
694 do {
22
Loop condition is false. Exiting loop
695 initializeunit(&have);
696 if (!quiet
18.1
'quiet' is 0
)
19
Taking true branch
697 printf("You have: ");
698 if (!fgets(havestr, sizeof(havestr), stdin(&__sF[0]))) {
20
Assuming the condition is false
21
Taking false branch
699 if (!quiet)
700 putchar('\n')(!__isthreaded ? __sputc('\n', (&__sF[1])) : (putc)('\n',
(&__sF[1])))
;
701 exit(0);
702 }
703 } while (addunit(&have, havestr, 0) ||
704 completereduce(&have));
705 do {
26
Loop condition is true. Execution continues on line 706
60
Loop condition is true. Execution continues on line 706
706 initializeunit(&want);
61
Calling 'initializeunit'
707 if (!quiet
22.1
'quiet' is 0
26.1
'quiet' is 0
)
23
Taking true branch
27
Taking true branch
708 printf("You want: ");
709 if (!fgets(wantstr, sizeof(wantstr), stdin(&__sF[0]))) {
24
Assuming the condition is false
25
Taking false branch
28
Assuming the condition is false
29
Taking false branch
710 if (!quiet)
711 putchar('\n')(!__isthreaded ? __sputc('\n', (&__sF[1])) : (putc)('\n',
(&__sF[1])))
;
712 exit(0);
713 }
714 } while (addunit(&want, wantstr, 0) ||
30
Calling 'addunit'
59
Returned allocated memory
715 completereduce(&want));
716 showanswer(&have, &want);
717 }
718 }
719 return (0);
720}