summaryrefslogtreecommitdiff
path: root/src/mpicalc.c
blob: ebd1bbb943b901cd4a9dde80fd5f92499f4ee2b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
/* mpicalc.c - Simple RPN calculator using gcry_mpi functions
 * Copyright (C) 1997, 1998, 1999, 2004, 2006, 2013  Werner Koch
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

/*
   This program is a simple RPN calculator which was originally used
   to develop the mpi functions of GnuPG.  Values must be given in
   hex.  Operation is like dc(1) except that the input/output radix is
   always 16 and you can use a '-' to prefix a negative number.
   Addition operators: ++ and --.  All operators must be delimited by
   a blank.
 */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#ifdef _GCRYPT_IN_LIBGCRYPT
# undef _GCRYPT_IN_LIBGCRYPT
# include "gcrypt.h"
#else
# include <gcrypt.h>
#endif


#define MPICALC_VERSION "2.0"
#define NEED_LIBGCRYPT_VERSION "1.6.0"

#define STACKSIZE  500
static gcry_mpi_t stack[STACKSIZE];
static int stackidx;


static int
scan_mpi (gcry_mpi_t retval, const char *string)
{
  gpg_error_t err;
  gcry_mpi_t val;

  err = gcry_mpi_scan (&val, GCRYMPI_FMT_HEX, string, 0, NULL);
  if (err)
    {
      fprintf (stderr, "scanning input failed: %s\n", gpg_strerror (err));
      return -1;
    }
  mpi_set (retval, val);
  mpi_release (val);
  return 0;
}


static void
print_mpi (gcry_mpi_t a)
{
  gpg_error_t err;
  char *buf;
  void *bufaddr = &buf;

  err = gcry_mpi_aprint (GCRYMPI_FMT_HEX, bufaddr, NULL, a);
  if (err)
    fprintf (stderr, "[error printing number: %s]\n", gpg_strerror (err));
  else
    {
      fputs (buf, stdout);
      gcry_free (buf);
    }
}



static void
do_add (void)
{
  if (stackidx < 2)
    {
      fputs ("stack underflow\n", stderr);
      return;
    }
  mpi_add (stack[stackidx - 2], stack[stackidx - 2], stack[stackidx - 1]);
  stackidx--;
}

static void
do_sub (void)
{
  if (stackidx < 2)
    {
      fputs ("stack underflow\n", stderr);
      return;
    }
  mpi_sub (stack[stackidx - 2], stack[stackidx - 2], stack[stackidx - 1]);
  stackidx--;
}

static void
do_inc (void)
{
  if (stackidx < 1)
    {
      fputs ("stack underflow\n", stderr);
      return;
    }
  mpi_add_ui (stack[stackidx - 1], stack[stackidx - 1], 1);
}

static void
do_dec (void)
{
  if (stackidx < 1)
    {
      fputs ("stack underflow\n", stderr);
      return;
    }
  /* mpi_sub_ui( stack[stackidx-1], stack[stackidx-1], 1 ); */
}

static void
do_mul (void)
{
  if (stackidx < 2)
    {
      fputs ("stack underflow\n", stderr);
      return;
    }
  mpi_mul (stack[stackidx - 2], stack[stackidx - 2], stack[stackidx - 1]);
  stackidx--;
}

static void
do_mulm (void)
{
  if (stackidx < 3)
    {
      fputs ("stack underflow\n", stderr);
      return;
    }
  mpi_mulm (stack[stackidx - 3], stack[stackidx - 3],
	    stack[stackidx - 2], stack[stackidx - 1]);
  stackidx -= 2;
}

static void
do_div (void)
{
  if (stackidx < 2)
    {
      fputs ("stack underflow\n", stderr);
      return;
    }
  mpi_fdiv (stack[stackidx - 2], NULL,
            stack[stackidx - 2], stack[stackidx - 1]);
  stackidx--;
}

static void
do_rem (void)
{
  if (stackidx < 2)
    {
      fputs ("stack underflow\n", stderr);
      return;
    }
  mpi_mod (stack[stackidx - 2],
           stack[stackidx - 2], stack[stackidx - 1]);
  stackidx--;
}

static void
do_powm (void)
{
  gcry_mpi_t a;
  if (stackidx < 3)
    {
      fputs ("stack underflow\n", stderr);
      return;
    }
  a = mpi_new (0);
  mpi_powm (a, stack[stackidx - 3], stack[stackidx - 2], stack[stackidx - 1]);
  mpi_release (stack[stackidx - 3]);
  stack[stackidx - 3] = a;
  stackidx -= 2;
}

static void
do_inv (void)
{
  gcry_mpi_t a;

  if (stackidx < 2)
    {
      fputs ("stack underflow\n", stderr);
      return;
    }
  a = mpi_new (0);
  mpi_invm (a, stack[stackidx - 2], stack[stackidx - 1]);
  mpi_set (stack[stackidx - 2], a);
  mpi_release (a);
  stackidx--;
}

static void
do_gcd (void)
{
  gcry_mpi_t a;

  if (stackidx < 2)
    {
      fputs ("stack underflow\n", stderr);
      return;
    }
  a = mpi_new (0);
  mpi_gcd (a, stack[stackidx - 2], stack[stackidx - 1]);
  mpi_set (stack[stackidx - 2], a);
  mpi_release (a);
  stackidx--;
}

static void
do_rshift (void)
{
  if (stackidx < 1)
    {
      fputs ("stack underflow\n", stderr);
      return;
    }
  mpi_rshift (stack[stackidx - 1], stack[stackidx - 1], 1);
}


static void
do_nbits (void)
{
  unsigned int n;

  if (stackidx < 1)
    {
      fputs ("stack underflow\n", stderr);
      return;
    }
  n = mpi_get_nbits (stack[stackidx - 1]);
  mpi_set_ui (stack[stackidx - 1], n);
}


static void
do_primecheck (void)
{
  gpg_error_t err;

  if (stackidx < 1)
    {
      fputs ("stack underflow\n", stderr);
      return;
    }
  err = gcry_prime_check (stack[stackidx - 1], 0);
  mpi_set_ui (stack[stackidx - 1], !err);
  if (err && gpg_err_code (err) != GPG_ERR_NO_PRIME)
    fprintf (stderr, "checking prime failed: %s\n", gpg_strerror (err));
}


static int
my_getc (void)
{
  static int shown;
  int c;

  for (;;)
    {
      if ((c = getc (stdin)) == EOF)
        return EOF;
      if (!(c & 0x80))
        return c;

      if (!shown)
        {
          shown = 1;
          fputs ("note: Non ASCII characters are ignored\n", stderr);
        }
    }
}


static void
print_help (void)
{
  fputs ("+   add           [0] := [1] + [0]          {-1}\n"
         "-   subtract      [0] := [1] - [0]          {-1}\n"
         "*   multiply      [0] := [1] * [0]          {-1}\n"
         "/   divide        [0] := [1] - [0]          {-1}\n"
         "%   modulo        [0] := [1] % [0]          {-1}\n"
         ">   right shift   [0] := [0] >> 1           {0}\n"
         "++  increment     [0] := [0]++              {0}\n"
         "--  decrement     [0] := [0]--              {0}\n"
         "m   multiply mod  [0] := [2] * [1] mod [0]  {-2}\n"
         "^   power mod     [0] := [2] ^ [1] mod [0]  {-2}\n"
         "I   inverse mod   [0] := [1]^-1 mod [0]     {-1}\n"
         "G   gcd           [0] := gcd([1],[0])       {-1}\n"
         "i   remove item   [0] := [1]                {-1}\n"
         "d   dup item      [-1] := [0]               {+1}\n"
         "r   reverse       [0] := [1], [1] := [0]    {0}\n"
         "b   # of bits     [0] := nbits([0])         {0}\n"
         "P   prime check   [0] := is_prime([0])?1:0  {0}\n"
         "c   clear stack\n"
         "p   print top item\n"
         "f   print the stack\n"
         "#   ignore until end of line\n"
         "?   print this help\n"
         , stdout);
}



int
main (int argc, char **argv)
{
  const char *pgm;
  int last_argc = -1;
  int print_config = 0;
  int i, c;
  int state = 0;
  char strbuf[4096];
  int stridx = 0;

  if (argc)
    {
      pgm = strrchr (*argv, '/');
      if (pgm)
        pgm++;
      else
        pgm = *argv;
      argc--; argv++;
    }
  else
    pgm = "?";

  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--version")
               || !strcmp (*argv, "--help"))
        {
          printf ("%s " MPICALC_VERSION "\n"
                  "libgcrypt %s\n"
                  "Copyright (C) 1997, 2013  Werner Koch\n"
                  "License LGPLv2.1+: GNU LGPL version 2.1 or later "
                  "<http://gnu.org/licenses/old-licenses/lgpl-2.1.html>\n"
                  "This is free software: you are free to change and "
                  "redistribute it.\n"
                  "There is NO WARRANTY, to the extent permitted by law.\n"
                  "\n"
                  "Syntax: mpicalc [options]\n"
                  "Simple interactive big integer RPN calculator\n"
                  "\n"
                  "Options:\n"
                  "  --version           print version information\n"
                  "  --print-config      print the Libgcrypt config\n"
                  "  --disable-hwf NAME  disable feature NAME\n",
                  pgm, gcry_check_version (NULL));
          exit (0);
        }
      else if (!strcmp (*argv, "--print-config"))
        {
          argc--; argv++;
          print_config = 1;
        }
      else if (!strcmp (*argv, "--disable-hwf"))
        {
          argc--; argv++;
          if (argc)
            {
              if (gcry_control (GCRYCTL_DISABLE_HWF, *argv, NULL))
                fprintf (stderr, "%s: unknown hardware feature `%s'"
                         " - option ignored\n", pgm, *argv);
              argc--; argv++;
            }
        }
    }

  if (argc)
    {
      fprintf (stderr, "usage: %s [options]  (--help for help)\n", pgm);
      exit (1);
    }

  if (!gcry_check_version (NEED_LIBGCRYPT_VERSION))
    {
      fprintf (stderr, "%s: Libgcrypt is too old (need %s, have %s)\n",
               pgm, NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
      exit (1);
    }
  gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
  if (print_config)
    {
      gcry_control (GCRYCTL_PRINT_CONFIG, stdout);
      exit (0);
    }

  for (i = 0; i < STACKSIZE; i++)
    stack[i] = NULL;
  stackidx = 0;

  while ((c = my_getc ()) != EOF)
    {
      if (!state) /* waiting */
	{
	  if (isdigit (c))
	    {
	      state = 1;
	      ungetc (c, stdin);
	      strbuf[0] = '0';
	      strbuf[1] = 'x';
	      stridx = 2;
	    }
	  else if (isspace (c))
	    ;
	  else
	    {
	      switch (c)
		{
                case '#':
                  state = 2;
                  break;
		case '+':
		  if ((c = my_getc ()) == '+')
		    do_inc ();
		  else
		    {
		      ungetc (c, stdin);
		      do_add ();
		    }
		  break;
                case '-':
		  if ((c = my_getc ()) == '-')
		    do_dec ();
		  else if (isdigit (c)
                           || (c >= 'A' && c <= 'F')
                           || (c >= 'a' && c <= 'f'))
		    {
		      state = 1;
		      ungetc (c, stdin);
		      strbuf[0] = '-';
		      strbuf[1] = '0';
		      strbuf[2] = 'x';
		      stridx = 3;
		    }
		  else
		    {
		      ungetc (c, stdin);
		      do_sub ();
		    }
		  break;
		case '*':
		  do_mul ();
		  break;
		case 'm':
		  do_mulm ();
		  break;
		case '/':
		  do_div ();
		  break;
		case '%':
		  do_rem ();
		  break;
		case '^':
		  do_powm ();
		  break;
		case '>':
		  do_rshift ();
		  break;
		case 'I':
		  do_inv ();
		  break;
		case 'G':
		  do_gcd ();
		  break;
		case 'i':	/* dummy */
		  if (!stackidx)
		    fputs ("stack underflow\n", stderr);
		  else
		    {
		      mpi_release (stack[stackidx - 1]);
		      stackidx--;
		    }
		  break;
		case 'd':	/* duplicate the tos */
		  if (!stackidx)
		    fputs ("stack underflow\n", stderr);
		  else if (stackidx < STACKSIZE)
		    {
		      mpi_release (stack[stackidx]);
		      stack[stackidx] = mpi_copy (stack[stackidx - 1]);
		      stackidx++;
		    }
		  else
		    fputs ("stack overflow\n", stderr);
		  break;
		case 'r':	/* swap top elements */
		  if (stackidx < 2)
		    fputs ("stack underflow\n", stderr);
		  else if (stackidx < STACKSIZE)
		    {
		      gcry_mpi_t tmp = stack[stackidx-1];
                      stack[stackidx-1] = stack[stackidx - 2];
                      stack[stackidx-2] = tmp;
		    }
		  break;
                case 'b':
                  do_nbits ();
                  break;
                case 'P':
                  do_primecheck ();
                  break;
		case 'c':
		  for (i = 0; i < stackidx; i++)
                    {
                      mpi_release (stack[i]); stack[i] = NULL;
                    }
		  stackidx = 0;
		  break;
		case 'p':	/* print the tos */
		  if (!stackidx)
		    puts ("stack is empty");
		  else
		    {
		      print_mpi (stack[stackidx - 1]);
		      putchar ('\n');
		    }
		  break;
		case 'f':	/* print the stack */
		  for (i = stackidx - 1; i >= 0; i--)
		    {
		      printf ("[%2d]: ", i);
		      print_mpi (stack[i]);
		      putchar ('\n');
		    }
		  break;
                case '?':
                  print_help ();
                  break;
		default:
		  fputs ("invalid operator\n", stderr);
		}
	    }
	}
      else if (state == 1) /* In a number. */
	{
	  if (!isxdigit (c))
	    {
              /* Store the number */
	      state = 0;
	      ungetc (c, stdin);
	      if (stridx < sizeof strbuf)
		strbuf[stridx] = 0;

	      if (stackidx < STACKSIZE)
		{
		  if (!stack[stackidx])
		    stack[stackidx] = mpi_new (0);
		  if (scan_mpi (stack[stackidx], strbuf))
		    fputs ("invalid number\n", stderr);
		  else
		    stackidx++;
		}
	      else
		fputs ("stack overflow\n", stderr);
	    }
	  else
	    { /* Store a digit.  */
	      if (stridx < sizeof strbuf - 1)
		strbuf[stridx++] = c;
	      else if (stridx == sizeof strbuf - 1)
		{
		  strbuf[stridx] = 0;
		  fputs ("input too large - truncated\n", stderr);
		  stridx++;
		}
	    }
	}
      else if (state == 2) /* In a comment. */
        {
          if (c == '\n')
            state = 0;
        }

    }

  for (i = 0; i < stackidx; i++)
    mpi_release (stack[i]);
  return 0;
}