4 * (c) 2010 Martin Mares <mj@ucw.cz>
8 * Things that are not implemented:
11 * - exact behavior of accumulator/R1/R2 (the manual lacks details)
12 * - exact behavior of negative zero
13 * - I/O instructions for devices that are not emulated (paper tape
14 * reader and puncher, card reader and puncher, magnetic tape unit)
18 #define UNUSED __attribute__((unused))
20 #undef ENABLE_DAEMON_MODE
32 static int cpu_quota = -1;
33 static int print_quota = -1;
34 static void (*error_hook)(char *msg);
36 // Minsk-2 has 37-bit words in sign-magnitude representation (bit 36 = sign)
37 typedef unsigned long long int word;
39 #define WORD_MASK 01777777777777ULL
40 #define SIGN_MASK 01000000000000ULL
41 #define VAL_MASK 00777777777777ULL
43 static int wsign(word w)
45 return (w & SIGN_MASK) ? -1 : 1;
48 static word wabs(word w)
53 #define WF(w) (wsign(w) < 0 ? '-' : '+'), wabs(w)
55 static long long wtoll(word w)
63 static word wfromll(long long x)
65 word w = ((x < 0) ? -x : x) & VAL_MASK;
71 static double wtofrac(word w)
73 return (double)wtoll(w) / (double)(1ULL << 36);
76 static word wfromfrac(double d)
78 return wfromll((long long)(d * (double)(1ULL << 36)));
81 static int int_in_range(long long x)
83 return (x >= -(long long)VAL_MASK && x <= (long long)VAL_MASK);
86 static int frac_in_range(double d)
88 return (d > -1. && d < 1.);
91 static int wexp(word w)
94 return (w & 0100 ? -exp : exp);
97 static word wputexp(word w, int exp)
99 return ((w & ~(word)0177) | ((exp < 0) ? 0100 | (-exp) : exp));
102 static int wmanti(word w)
104 return ((w >> 8) & ((1 << 28) - 1));
107 static double wtofloat(word w)
109 double x = wmanti(w);
110 return ldexp(x, wexp(w) - 28);
113 static int float_in_range(double x)
116 return (x <= ldexp((1 << 28) - 1, 63 - 28));
119 static word wfromfloat(double x, int normalized)
128 double m = frexp(x, &exp);
129 word mm = (word) ldexp(m, 28);
134 if (normalized || exp < -91)
152 static word mem[4096];
154 static word rd(int addr)
156 word val = addr ? mem[addr] : 0;
158 printf("\tRD %04o = %c%012llo\n", addr, WF(val));
162 static void wr(int addr, word val)
164 assert(!(val & ~(WORD_MASK)));
166 printf("\tWR %04o = %c%012llo\n", addr, WF(val));
172 static void parse_error(char *msg)
175 error_hook("Parse error");
176 printf("Ошибка входа (стр. %d): %s\n", lino, msg);
180 static void parse_in(void)
185 while (fgets(line, sizeof(line), stdin))
188 char *eol = strchr(line, '\n');
190 parse_error("Строка слишком долгая");
192 if (eol > line && eol[-1] == '\r')
196 if (!c[0] || c[0] == ';')
206 for (int i=0; i<4; i++)
210 if (*c >= '0' && *c <= '7')
211 addr = 8*addr + *c++ - '0';
213 parse_error("Плохая цифра");
218 parse_error("Адрес слишком долгий");
226 parse_error("Плохой знак");
228 for (int i=0; i<12; i++)
232 if (*c >= '0' && *c <= '7')
233 w = 8*w + *c++ - '0';
235 parse_error("Плохая цифра");
240 parse_error("Номер слишком долгий");
247 static word r1, r2, current_ins;
248 static int ip = 00050; // Standard program start location
251 static void stop(char *reason, char *notice)
255 printf("Машина остановлена -- %s\n", reason);
256 printf("СчАК:%04o См:%c%012llo Р1:%c%012llo Р2:%c%012llo\n", prev_ip, WF(acc), WF(r1), WF(r2));
260 static void over(void)
262 stop("Аварийный останов", "Overflow");
265 static void notimp(void)
268 stop("Устройство разбитое", "Not implemented");
271 static void noins(void)
274 stop("Эту команду не знаю", "Illegal instruction");
277 static uint16_t linebuf[128];
279 static uint16_t russian_chars[64] = {
280 '0', '1', '2', '3', '4', '5', '6', '7', // 0x
281 '8', '9', '+', '-', '/', ',', '.', ' ', // 1x
282 0x2169, '^', '(', ')', 0x00d7, '=', ';', '[', // 2x
283 ']', '*', '`', '\'', 0x2260, '<', '>', ':', // 3x
284 0x410, 0x411, 0x412, 0x413, 0x414, 0x415, 0x416, 0x417, // 4x
285 0x418, 0x419, 0x41a, 0x41b, 0x41c, 0x41d, 0x41e, 0x41f, // 5x
286 0x420, 0x421, 0x422, 0x423, 0x424, 0x425, 0x426, 0x427, // 6x
287 0x428, 0x429, 0x42b, 0x42c, 0x42d, 0x42e, 0x42f, 0x2013 // 7x
290 static uint16_t latin_chars[64] = {
291 '0', '1', '2', '3', '4', '5', '6', '7', // 0x
292 '8', '9', '+', '-', '/', ',', '.', ' ', // 1x
293 0x2169, '^', '(', ')', 0x00d7, '=', ';', '[', // 2x
294 ']', '*', '`', '\'', 0x2260, '<', '>', ':', // 3x
295 'A', 'B', 'W', 'G', 'D', 'E', 'V', 'Z', // 4x
296 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 5x
297 'R', 'S', 'T', 'U', 'F', 'H', 'C', ' ', // 6x
298 ' ', ' ', 'Y', 'X', ' ', ' ', 'Q', 0x2013 // 7x
301 static void print_line(int r)
304 * Meaning of bits of r:
305 * 0 = perform line feed
311 if (print_quota > 0 && !--print_quota)
312 stop("Бумага дошла - нужно ехать в Сибирь про новую", "Out of paper");
313 for (int i=0; i<128; i++)
322 putchar(0xc0 | (ch >> 6));
323 putchar(0x80 | (ch & 0x3f));
327 putchar(0xe0 | (ch >> 12));
328 putchar(0x80 | ((ch >> 6) & 0x3f));
329 putchar(0x80 | (ch & 0x3f));
334 memset(linebuf, 0, sizeof(linebuf));
342 static void print_ins(int x, int y)
346 int r = (x >> 9) & 7;
359 case 0: // Decimal float
360 fmt = "+dddddddx+xbd";
362 case 1: // Octal number
363 fmt = "+oooooooooooo";
365 case 2: // Decimal fixed
368 case 3: // Decimal unsigned
372 case 4: // One Russian symbol
375 case 5: // Russian text
378 case 6: // One Latin symbol
381 default: // Latin text
398 ch = (yy & (1ULL << bit)) ? '-' : '+';
402 ch = '0' + ((yy >> bit) & 1);
406 ch = '0' + ((yy >> bit) & 7);
410 ch = '0' + ((yy >> bit) & 15);
416 ch = russian_chars[(yy >> bit) & 077];
420 ch = latin_chars[(yy >> bit) & 077];
428 if (ch == '0' || ch == ' ')
434 pos = (pos+1) & 0177;
439 static void run(void)
448 int op = (w >> 30) & 0177; // Operation code
449 int ax = (w >> 28) & 3; // Address extensions not supported
450 int ix = (w >> 24) & 15; // Indexing
451 int x = (w >> 12) & 07777; // Operands (original form)
453 int xi=x, yi=y; // (indexed form)
455 printf("@%04o %c%02o %02o %04o %04o\n",
457 (w & SIGN_MASK) ? '-' : '+',
458 (int)((w >> 30) & 077),
459 (int)((w >> 24) & 077),
467 xi = (xi + (int)((i >> 12) & 07777)) & 07777;
468 yi = (yi + (int)(i & 07777)) & 07777;
470 printf("\tIndexing -> %04o %04o\n", xi, yi);
475 if (cpu_quota > 0 && !--cpu_quota)
476 stop("Тайм-аут", "CPU quota exceeded");
478 /* Arithmetic operations */
481 long long aa, bb, cc;
485 auto void afetch(void);
495 auto void astore(word result);
496 void astore(word result)
503 auto void astore_int(long long x);
504 void astore_int(long long x)
506 if (!int_in_range(x))
511 auto void astore_frac(double f);
512 void astore_frac(double f)
514 if (!frac_in_range(f))
516 astore(wfromfrac(f));
519 auto void astore_float(double f);
520 void astore_float(double f)
522 if (!float_in_range(f))
524 astore(wfromfloat(f, 0));
533 case 004 ... 007: // XOR
537 case 010 ... 013: // FIX addition
539 astore_int(wtoll(a) + wtoll(b));
541 case 014 ... 017: // FP addition
543 astore_float(wtofloat(a) + wtofloat(b));
545 case 020 ... 023: // FIX subtraction
547 astore_int(wtoll(a) - wtoll(b));
549 case 024 ... 027: // FP subtraction
551 astore_float(wtofloat(a) - wtofloat(b));
553 case 030 ... 033: // FIX multiplication
555 astore_frac(wtofrac(a) * wtofrac(b));
557 case 034 ... 037: // FP multiplication
559 astore_float(wtofloat(a) * wtofloat(b));
561 case 040 ... 043: // FIX division
567 astore_frac(ad / bd);
569 case 044 ... 047: // FP division
573 if (!bd || wexp(b) < -63)
575 astore_float(ad / bd);
577 case 050 ... 053: // FIX subtraction of abs values
579 astore_int(wabs(a) - wabs(b));
581 case 054 ... 057: // FP subtraction of abs values
583 astore_float(fabs(wtofloat(a)) - fabs(wtofloat(b)));
585 case 060 ... 063: // Shift logical
588 if (i <= -37 || i >= 37)
591 astore((a << i) & WORD_MASK);
595 case 064 ... 067: // Shift arithmetical
599 if (i <= -36 || i >= 36)
602 cc = (aa << i) & VAL_MASK;
605 astore((a & SIGN_MASK) | wfromll(cc));
607 case 070 ... 073: // And
611 case 074 ... 077: // Or
619 stop("Останов машины", "Halted");
620 case 0103: // I/O magtape
622 case 0104: // Disable rounding
624 case 0105: // Enable rounding
626 case 0106: // Interrupt control
628 case 0107: // Reverse tape
631 wr(yi, r1 = acc = rd(xi));
633 case 0111: // Move negative
634 wr(yi, acc = (r1 = rd(xi)) ^ SIGN_MASK);
636 case 0112: // Move absolute value
637 wr(yi, acc = (r1 = rd(xi)) & VAL_MASK);
639 case 0113: // Read from keyboard
641 case 0114: // Copy sign
642 wr(yi, acc = rd(yi) ^ ((r1 = rd(xi)) & SIGN_MASK));
644 case 0115: // Read code from R1 (obscure)
646 case 0116: // Copy exponent
647 wr(yi, acc = wputexp(rd(yi), wexp(r1 = rd(xi))));
649 case 0117: // I/O teletype
655 aa = (a >> 24) & 017777;
658 b = rd(y); // (a mountain range near Prague)
659 acc = ((aa-1) << 24) |
660 (((((a >> 12) & 07777) + (b >> 12) & 07777) & 07777) << 12) |
661 (((a & 07777) + (b & 07777)) & 07777);
669 case 0131: // Jump to subroutine
670 wr(y, acc = ((030ULL << 30) | ((ip & 07777ULL) << 12)));
673 case 0132: // Jump if positive
679 case 0133: // Jump if overflow
680 // Since we always trap on overflow, this instruction always jumps to the 1st address
683 case 0134: // Jump if zero
689 case 0135: // Jump if key pressed
690 // No keys are ever pressed, so always jump to 2nd
693 case 0136: // Interrupt masking
695 case 0137: // Used only when reading from tape
697 case 0140 ... 0147: // I/O
699 case 0150 ... 0154: // I/O
701 case 0160 ... 0161: // I/O
703 case 0162: // Printing
708 case 0170: // FIX multiplication, bottom part
710 if (wtofrac(a) * wtofrac(b) >= .1/(1ULL << 32))
712 acc = wfromll(((unsigned long long)wabs(a) * (unsigned long long)wabs(b)) & VAL_MASK);
713 // XXX: What should be the sign? The book does not define that.
726 case 0172: // Add exponents
729 i = wexp(a) + wexp(b);
730 if (i < -63 || i > 63)
735 case 0173: // Sub exponents
738 i = wexp(b) - wexp(a);
739 if (i < -63 || i > 63)
744 case 0174: // Addition in one's complement
751 // XXX: The effect on the accumulator is undocumented, but likely to be as follows:
754 case 0175: // Normalization
759 wr((yi+1) & 07777, 0);
767 while (!(a & (SIGN_MASK >> 1)))
774 wr((yi+1) & 07777, i);
777 case 0176: // Population count
780 for (int i=0; i<36; i++)
783 // XXX: Guessing that acc gets a copy of the result
792 printf("\tACC:%c%012llo R1:%c%012llo R2:%c%012llo\n", WF(acc), WF(r1), WF(r2));
796 static void die(char *msg)
798 fprintf(stderr, "minsk: ");
799 fprintf(stderr, msg);
804 /*** Daemon interface ***/
806 #ifdef ENABLE_DAEMON_MODE
809 * The daemon mode was a quick hack for the Po drate contest.
810 * Most parameters are hard-wired.
817 #include <sys/signal.h>
818 #include <sys/wait.h>
819 #include <sys/poll.h>
820 #include <sys/socket.h>
821 #include <netinet/in.h>
822 #include <arpa/inet.h>
825 #define DTRACE(msg, args...) fprintf(stderr, msg "\n", ##args)
826 #define DLOG(msg, args...) fprintf(stderr, msg "\n", ##args)
828 #define DTRACE(msg, args...) do { } while(0)
829 #define DLOG(msg, args...) syslog(LOG_INFO, msg, ##args)
832 #define MAX_CONNECTIONS 50 // Per daemon
833 #define MAX_CONNS_PER_IP 1 // Per IP
834 #define MAX_TRACKERS 200 // IP address trackers
835 #define TBF_MAX 5 // Max number of tokens in the bucket
836 #define TBF_REFILL_PER_SEC 0.2 // Bucket refill rate (buckets/sec)
838 #define PID_FILE "/var/run/pd-minsk.pid"
842 static char **spt_argv;
843 static char *spt_start, *spt_end;
845 static void setproctitle_init(int argc, char **argv)
848 char **env, **oldenv, *t;
852 /* Create a backup copy of environment */
855 for (i=0; oldenv[i]; i++)
856 len += strlen(oldenv[i]) + 1;
857 __environ = env = malloc(sizeof(char *)*(i+1));
859 if (!__environ || !t)
860 die("malloc failed");
861 for (i=0; oldenv[i]; i++)
864 len = strlen(oldenv[i]) + 1;
865 memcpy(t, oldenv[i], len);
870 /* Scan for consecutive free space */
871 spt_start = spt_end = argv[0];
872 for (i=0; i<argc; i++)
873 if (!i || spt_end+1 == argv[i])
874 spt_end = argv[i] + strlen(argv[i]);
875 for (i=0; oldenv[i]; i++)
876 if (spt_end+1 == oldenv[i])
877 spt_end = oldenv[i] + strlen(oldenv[i]);
881 setproctitle(const char *msg, ...)
888 if (spt_end > spt_start)
890 n = vsnprintf(buf, sizeof(buf), msg, args);
891 if (n >= (int) sizeof(buf) || n < 0)
892 sprintf(buf, "<too-long>");
893 n = spt_end - spt_start;
894 strncpy(spt_start, buf, n);
896 spt_argv[0] = spt_start;
902 static void sigchld_handler(int sig UNUSED)
906 static void sigalrm_handler(int sig UNUSED)
908 const char err[] = "--- Timed out. Time machine disconnected. ---\n";
909 write(1, err, sizeof(err));
910 DLOG("Connection timed out");
914 static void child_error_hook(char *err)
916 DLOG("Stopped: %s", err);
919 static void child(int sk2)
925 struct sigaction sact = {
926 .sa_handler = sigalrm_handler,
928 if (sigaction(SIGALRM, &sact, NULL) < 0)
929 die("sigaction: %m");
936 const char welcome[] = "+++ Welcome to our computer museum. +++\n+++ Our time machine will connect you to one of our exhibits. +++\n\n";
937 write(1, welcome, sizeof(welcome));
939 error_hook = child_error_hook;
949 struct tracker *tracker;
952 static struct conn connections[MAX_CONNECTIONS];
954 static struct conn *get_conn(struct in_addr *a)
956 for (int i=0; i<MAX_CONNECTIONS; i++)
958 struct conn *c = &connections[i];
961 memcpy(&c->addr, a, sizeof(struct in_addr));
968 static struct conn *pid_to_conn(pid_t pid)
970 for (int i=0; i<MAX_CONNECTIONS; i++)
972 struct conn *c = &connections[i];
979 static void put_conn(struct conn *c)
992 static struct tracker trackers[MAX_TRACKERS];
994 static int get_tracker(struct conn *c)
997 time_t now = time(NULL);
1000 for (i=0; i<MAX_TRACKERS; i++)
1003 if (!memcmp(&t->addr, &c->addr, sizeof(struct in_addr)))
1006 if (i < MAX_TRACKERS)
1008 if (now > t->last_access)
1010 t->tokens += (now - t->last_access) * (double) TBF_REFILL_PER_SEC;
1011 t->last_access = now;
1012 if (t->tokens > TBF_MAX)
1013 t->tokens = TBF_MAX;
1015 DTRACE("TBF: Using tracker %d (%.3f tokens)", i, t->tokens);
1020 for (int i=0; i<MAX_TRACKERS; i++)
1023 if (!t->active_conns && (min_i < 0 || t->last_access < trackers[min_i].last_access))
1028 DLOG("TBF: Out of trackers!");
1031 t = &trackers[min_i];
1033 DTRACE("TBF: Recycling tracker %d", min_i);
1035 DTRACE("TBF: Creating tracker %d", min_i);
1036 memset(t, 0, sizeof(*t));
1038 t->last_access = now;
1039 t->tokens = TBF_MAX;
1042 if (t->active_conns >= MAX_CONNS_PER_IP)
1044 DTRACE("TBF: Too many conns per IP");
1048 if (t->tokens >= 0.999)
1053 DTRACE("TBF: Passed (%d conns)", t->active_conns);
1058 DTRACE("TBF: Failed");
1064 static void put_tracker(struct conn *c)
1066 struct tracker *t = c->tracker;
1069 DLOG("put_tracker: no tracker?");
1073 if (t->active_conns <= 0)
1075 DLOG("put_tracker: no counter?");
1080 DTRACE("TBF: Put tracker (%d conns remain)", t->active_conns);
1083 static void run_as_daemon(int do_fork)
1085 int sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1090 if (setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
1091 die("setsockopt: %m");
1093 struct sockaddr_in sa = {
1094 .sin_family = AF_INET,
1095 .sin_port = ntohs(1969),
1096 .sin_addr.s_addr = INADDR_ANY,
1098 if (bind(sk, (struct sockaddr *) &sa, sizeof(sa)) < 0)
1100 if (listen(sk, 128) < 0)
1102 // if (fcntl(sk, F_SETFL, O_NONBLOCK) < 0)
1103 // die("fcntl: %m");
1112 FILE *f = fopen(PID_FILE, "w");
1115 fprintf(f, "%d\n", pid);
1122 setresgid(GID, GID, GID);
1123 setresuid(UID, UID, UID);
1127 struct sigaction sact = {
1128 .sa_handler = sigchld_handler,
1129 .sa_flags = SA_RESTART,
1131 if (sigaction(SIGCHLD, &sact, NULL) < 0)
1132 die("sigaction: %m");
1134 DLOG("Daemon ready");
1135 setproctitle("minsk: Listening");
1136 openlog("minsk", LOG_PID, LOG_LOCAL7);
1140 struct pollfd pfd[1] = {
1141 { .fd = sk, .events = POLLIN },
1144 int nfds = poll(pfd, 1, 60000);
1145 if (nfds < 0 && errno != EINTR)
1154 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1156 if (!WIFEXITED(status) || WEXITSTATUS(status))
1157 DLOG("Process %d exited with strange status %x", pid, status);
1159 struct conn *conn = pid_to_conn(pid);
1162 DTRACE("Connection with PID %d exited", pid);
1167 DTRACE("PID %d exited, matching no connection", pid);
1170 if (!(pfd[0].revents & POLLIN))
1173 socklen_t salen = sizeof(sa);
1174 int sk2 = accept(sk, (struct sockaddr *) &sa, &salen);
1184 DTRACE("Got connection: fd=%d", sk2);
1186 struct conn *conn = get_conn(&sa.sin_addr);
1187 const char *reason = NULL;
1190 if (!get_tracker(conn))
1192 DLOG("Connection from %s dropped: Throttling", inet_ntoa(sa.sin_addr));
1195 reason = "--- Sorry, but you are sending too many requests. Please slow down. ---\n";
1200 DLOG("Connection from %s dropped: Too many connections", inet_ntoa(sa.sin_addr));
1201 reason = "--- Sorry, maximum number of connections exceeded. Please come later. ---\n";
1207 DLOG("fork failed: %m");
1216 DLOG("Accepted connection from %s", inet_ntoa(sa.sin_addr));
1217 setproctitle("minsk: %s", inet_ntoa(sa.sin_addr));
1222 DLOG("Sending error message to %s", inet_ntoa(sa.sin_addr));
1223 setproctitle("minsk: %s ERR", inet_ntoa(sa.sin_addr));
1224 write(sk2, reason, strlen(reason));
1229 DTRACE("Created process %d", pid);
1238 static void run_as_daemon(int do_fork UNUSED)
1240 die("Daemon mode not supported in this version, need to recompile.");
1243 static void setproctitle_init(int argc UNUSED, char **argv UNUSED)
1249 static void init_memory(void)
1251 // For the contest, we fill the whole memory with -00 00 0000 0000 (HALT),
1252 // not +00 00 0000 0000 (NOP). Otherwise, an empty program would reveal
1253 // the location of the password :)
1254 for (int i=0; i<4096; i++)
1255 mem[i] = 01000000000000ULL;
1257 // Store the password
1259 mem[pos++] = 0574060565373;
1260 mem[pos++] = 0371741405340;
1261 mem[pos++] = 0534051524017;
1264 static const struct option longopts[] = {
1265 { "cpu-quota", 1, NULL, 'q' },
1266 { "daemon", 0, NULL, 'd' },
1267 { "nofork", 0, NULL, 'n' },
1268 { "print-quota", 1, NULL, 'p' },
1269 { "trace", 1, NULL, 't' },
1270 { NULL, 0, NULL, 0 },
1273 static void usage(void)
1277 --daemon Run as daemon and listen for network connections\n\
1278 --nofork When run with --daemon, avoid forking\n\
1279 --trace=<level> Enable tracing of program execution\n\
1280 --cpu-quota=<n> Set CPU quota to <n> instructions\n\
1281 --print-quota=<n> Set printer quota to <n> lines\n\
1286 int main(int argc, char **argv)
1289 int daemon_mode = 0;
1292 while ((opt = getopt_long(argc, argv, "", longopts, NULL)) >= 0)
1302 print_quota = atoi(optarg);
1305 cpu_quota = atoi(optarg);
1308 trace = atoi(optarg);
1316 setproctitle_init(argc, argv);
1320 run_as_daemon(do_fork);