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] == ';')
198 if (!strncmp(c, ";daji_zor_i_litva=", 18))
202 error_hook("Secret tracing switch flipped");
214 for (int i=0; i<4; i++)
218 if (*c >= '0' && *c <= '7')
219 addr = 8*addr + *c++ - '0';
221 parse_error("Плохая цифра");
226 parse_error("Адрес слишком долгий");
234 parse_error("Плохой знак");
236 for (int i=0; i<12; i++)
240 if (*c >= '0' && *c <= '7')
241 w = 8*w + *c++ - '0';
243 parse_error("Плохая цифра");
248 parse_error("Номер слишком долгий");
255 static word r1, r2, current_ins;
256 static int ip = 00050; // Standard program start location
259 static void stop(char *reason, char *notice)
263 printf("Машина остановлена -- %s\n", reason);
264 printf("СчАК:%04o См:%c%012llo Р1:%c%012llo Р2:%c%012llo\n", prev_ip, WF(acc), WF(r1), WF(r2));
268 static void over(void)
270 stop("Аварийный останов", "Overflow");
273 static void notimp(void)
276 stop("Устройство разбитое", "Not implemented");
279 static void noins(void)
282 stop("Эту команду не знаю", "Illegal instruction");
285 static uint16_t linebuf[128];
287 static uint16_t russian_chars[64] = {
288 '0', '1', '2', '3', '4', '5', '6', '7', // 0x
289 '8', '9', '+', '-', '/', ',', '.', ' ', // 1x
290 0x2169, '^', '(', ')', 0x00d7, '=', ';', '[', // 2x
291 ']', '*', '`', '\'', 0x2260, '<', '>', ':', // 3x
292 0x410, 0x411, 0x412, 0x413, 0x414, 0x415, 0x416, 0x417, // 4x
293 0x418, 0x419, 0x41a, 0x41b, 0x41c, 0x41d, 0x41e, 0x41f, // 5x
294 0x420, 0x421, 0x422, 0x423, 0x424, 0x425, 0x426, 0x427, // 6x
295 0x428, 0x429, 0x42b, 0x42c, 0x42d, 0x42e, 0x42f, 0x2013 // 7x
298 static uint16_t latin_chars[64] = {
299 '0', '1', '2', '3', '4', '5', '6', '7', // 0x
300 '8', '9', '+', '-', '/', ',', '.', ' ', // 1x
301 0x2169, '^', '(', ')', 0x00d7, '=', ';', '[', // 2x
302 ']', '*', '`', '\'', 0x2260, '<', '>', ':', // 3x
303 'A', 'B', 'W', 'G', 'D', 'E', 'V', 'Z', // 4x
304 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 5x
305 'R', 'S', 'T', 'U', 'F', 'H', 'C', ' ', // 6x
306 ' ', ' ', 'Y', 'X', ' ', ' ', 'Q', 0x2013 // 7x
309 static void print_line(int r)
312 * Meaning of bits of r:
313 * 0 = perform line feed
319 if (print_quota > 0 && !--print_quota)
320 stop("Бумага дошла - нужно ехать в Сибирь про новую", "Out of paper");
321 for (int i=0; i<128; i++)
330 putchar(0xc0 | (ch >> 6));
331 putchar(0x80 | (ch & 0x3f));
335 putchar(0xe0 | (ch >> 12));
336 putchar(0x80 | ((ch >> 6) & 0x3f));
337 putchar(0x80 | (ch & 0x3f));
342 memset(linebuf, 0, sizeof(linebuf));
350 static void print_ins(int x, int y)
354 int r = (x >> 9) & 7;
367 case 0: // Decimal float
368 fmt = "+dddddddx+xbd";
370 case 1: // Octal number
371 fmt = "+oooooooooooo";
373 case 2: // Decimal fixed
376 case 3: // Decimal unsigned
380 case 4: // One Russian symbol
383 case 5: // Russian text
386 case 6: // One Latin symbol
389 default: // Latin text
406 ch = (yy & (1ULL << bit)) ? '-' : '+';
410 ch = '0' + ((yy >> bit) & 1);
414 ch = '0' + ((yy >> bit) & 7);
418 ch = '0' + ((yy >> bit) & 15);
424 ch = russian_chars[(yy >> bit) & 077];
428 ch = latin_chars[(yy >> bit) & 077];
436 if (ch == '0' || ch == ' ')
442 pos = (pos+1) & 0177;
447 static void run(void)
456 int op = (w >> 30) & 0177; // Operation code
457 int ax = (w >> 28) & 3; // Address extensions not supported
458 int ix = (w >> 24) & 15; // Indexing
459 int x = (w >> 12) & 07777; // Operands (original form)
461 int xi=x, yi=y; // (indexed form)
463 printf("@%04o %c%02o %02o %04o %04o\n",
465 (w & SIGN_MASK) ? '-' : '+',
466 (int)((w >> 30) & 077),
467 (int)((w >> 24) & 077),
475 xi = (xi + (int)((i >> 12) & 07777)) & 07777;
476 yi = (yi + (int)(i & 07777)) & 07777;
478 printf("\tIndexing -> %04o %04o\n", xi, yi);
483 if (cpu_quota > 0 && !--cpu_quota)
484 stop("Тайм-аут", "CPU quota exceeded");
486 /* Arithmetic operations */
489 long long aa, bb, cc;
493 auto void afetch(void);
503 auto void astore(word result);
504 void astore(word result)
511 auto void astore_int(long long x);
512 void astore_int(long long x)
514 if (!int_in_range(x))
519 auto void astore_frac(double f);
520 void astore_frac(double f)
522 if (!frac_in_range(f))
524 astore(wfromfrac(f));
527 auto void astore_float(double f);
528 void astore_float(double f)
530 if (!float_in_range(f))
532 astore(wfromfloat(f, 0));
541 case 004 ... 007: // XOR
545 case 010 ... 013: // FIX addition
547 astore_int(wtoll(a) + wtoll(b));
549 case 014 ... 017: // FP addition
551 astore_float(wtofloat(a) + wtofloat(b));
553 case 020 ... 023: // FIX subtraction
555 astore_int(wtoll(a) - wtoll(b));
557 case 024 ... 027: // FP subtraction
559 astore_float(wtofloat(a) - wtofloat(b));
561 case 030 ... 033: // FIX multiplication
563 astore_frac(wtofrac(a) * wtofrac(b));
565 case 034 ... 037: // FP multiplication
567 astore_float(wtofloat(a) * wtofloat(b));
569 case 040 ... 043: // FIX division
575 astore_frac(ad / bd);
577 case 044 ... 047: // FP division
581 if (!bd || wexp(b) < -63)
583 astore_float(ad / bd);
585 case 050 ... 053: // FIX subtraction of abs values
587 astore_int(wabs(a) - wabs(b));
589 case 054 ... 057: // FP subtraction of abs values
591 astore_float(fabs(wtofloat(a)) - fabs(wtofloat(b)));
593 case 060 ... 063: // Shift logical
596 if (i <= -37 || i >= 37)
599 astore((a << i) & WORD_MASK);
603 case 064 ... 067: // Shift arithmetical
607 if (i <= -36 || i >= 36)
610 cc = (aa << i) & VAL_MASK;
613 astore((a & SIGN_MASK) | wfromll(cc));
615 case 070 ... 073: // And
619 case 074 ... 077: // Or
627 stop("Останов машины", "Halted");
628 case 0103: // I/O magtape
630 case 0104: // Disable rounding
632 case 0105: // Enable rounding
634 case 0106: // Interrupt control
636 case 0107: // Reverse tape
639 wr(yi, r1 = acc = rd(xi));
641 case 0111: // Move negative
642 wr(yi, acc = (r1 = rd(xi)) ^ SIGN_MASK);
644 case 0112: // Move absolute value
645 wr(yi, acc = (r1 = rd(xi)) & VAL_MASK);
647 case 0113: // Read from keyboard
649 case 0114: // Copy sign
650 wr(yi, acc = rd(yi) ^ ((r1 = rd(xi)) & SIGN_MASK));
652 case 0115: // Read code from R1 (obscure)
654 case 0116: // Copy exponent
655 wr(yi, acc = wputexp(rd(yi), wexp(r1 = rd(xi))));
657 case 0117: // I/O teletype
663 aa = (a >> 24) & 017777;
666 b = rd(y); // (a mountain range near Prague)
667 acc = ((aa-1) << 24) |
668 (((((a >> 12) & 07777) + (b >> 12) & 07777) & 07777) << 12) |
669 (((a & 07777) + (b & 07777)) & 07777);
677 case 0131: // Jump to subroutine
678 wr(y, acc = ((030ULL << 30) | ((ip & 07777ULL) << 12)));
681 case 0132: // Jump if positive
687 case 0133: // Jump if overflow
688 // Since we always trap on overflow, this instruction always jumps to the 1st address
691 case 0134: // Jump if zero
697 case 0135: // Jump if key pressed
698 // No keys are ever pressed, so always jump to 2nd
701 case 0136: // Interrupt masking
703 case 0137: // Used only when reading from tape
705 case 0140 ... 0147: // I/O
707 case 0150 ... 0154: // I/O
709 case 0160 ... 0161: // I/O
711 case 0162: // Printing
716 case 0170: // FIX multiplication, bottom part
718 if (wtofrac(a) * wtofrac(b) >= .1/(1ULL << 32))
720 acc = wfromll(((unsigned long long)wabs(a) * (unsigned long long)wabs(b)) & VAL_MASK);
721 // XXX: What should be the sign? The book does not define that.
734 case 0172: // Add exponents
737 i = wexp(a) + wexp(b);
738 if (i < -63 || i > 63)
743 case 0173: // Sub exponents
746 i = wexp(b) - wexp(a);
747 if (i < -63 || i > 63)
752 case 0174: // Addition in one's complement
759 // XXX: The effect on the accumulator is undocumented, but likely to be as follows:
762 case 0175: // Normalization
767 wr((yi+1) & 07777, 0);
775 while (!(a & (SIGN_MASK >> 1)))
782 wr((yi+1) & 07777, i);
785 case 0176: // Population count
788 for (int i=0; i<36; i++)
791 // XXX: Guessing that acc gets a copy of the result
800 printf("\tACC:%c%012llo R1:%c%012llo R2:%c%012llo\n", WF(acc), WF(r1), WF(r2));
804 static void die(char *msg)
806 fprintf(stderr, "minsk: ");
807 fprintf(stderr, msg);
812 /*** Daemon interface ***/
814 #ifdef ENABLE_DAEMON_MODE
817 * The daemon mode was a quick hack for the Po drate contest.
818 * Most parameters are hard-wired.
825 #include <sys/signal.h>
826 #include <sys/wait.h>
827 #include <sys/poll.h>
828 #include <sys/socket.h>
829 #include <netinet/in.h>
830 #include <arpa/inet.h>
833 #define DTRACE(msg, args...) fprintf(stderr, msg "\n", ##args)
834 #define DLOG(msg, args...) fprintf(stderr, msg "\n", ##args)
836 #define DTRACE(msg, args...) do { } while(0)
837 #define DLOG(msg, args...) syslog(LOG_INFO, msg, ##args)
840 #define MAX_CONNECTIONS 50 // Per daemon
841 #define MAX_CONNS_PER_IP 1 // Per IP
842 #define MAX_TRACKERS 200 // IP address trackers
843 #define TBF_MAX 5 // Max number of tokens in the bucket
844 #define TBF_REFILL_PER_SEC 0.2 // Bucket refill rate (buckets/sec)
846 #define PID_FILE "/var/run/pd-minsk.pid"
850 static char **spt_argv;
851 static char *spt_start, *spt_end;
853 static void setproctitle_init(int argc, char **argv)
856 char **env, **oldenv, *t;
860 /* Create a backup copy of environment */
863 for (i=0; oldenv[i]; i++)
864 len += strlen(oldenv[i]) + 1;
865 __environ = env = malloc(sizeof(char *)*(i+1));
867 if (!__environ || !t)
868 die("malloc failed");
869 for (i=0; oldenv[i]; i++)
872 len = strlen(oldenv[i]) + 1;
873 memcpy(t, oldenv[i], len);
878 /* Scan for consecutive free space */
879 spt_start = spt_end = argv[0];
880 for (i=0; i<argc; i++)
881 if (!i || spt_end+1 == argv[i])
882 spt_end = argv[i] + strlen(argv[i]);
883 for (i=0; oldenv[i]; i++)
884 if (spt_end+1 == oldenv[i])
885 spt_end = oldenv[i] + strlen(oldenv[i]);
889 setproctitle(const char *msg, ...)
896 if (spt_end > spt_start)
898 n = vsnprintf(buf, sizeof(buf), msg, args);
899 if (n >= (int) sizeof(buf) || n < 0)
900 sprintf(buf, "<too-long>");
901 n = spt_end - spt_start;
902 strncpy(spt_start, buf, n);
904 spt_argv[0] = spt_start;
910 static void sigchld_handler(int sig UNUSED)
914 static void sigalrm_handler(int sig UNUSED)
916 const char err[] = "--- Timed out. Time machine disconnected. ---\n";
917 write(1, err, sizeof(err));
918 DLOG("Connection timed out");
922 static void child_error_hook(char *err)
924 DLOG("Stopped: %s", err);
927 static void child(int sk2)
933 struct sigaction sact = {
934 .sa_handler = sigalrm_handler,
936 if (sigaction(SIGALRM, &sact, NULL) < 0)
937 die("sigaction: %m");
944 const char welcome[] = "+++ Welcome to our computer museum. +++\n+++ Our time machine will connect you to one of our exhibits. +++\n\n";
945 write(1, welcome, sizeof(welcome));
947 error_hook = child_error_hook;
957 struct tracker *tracker;
960 static struct conn connections[MAX_CONNECTIONS];
962 static struct conn *get_conn(struct in_addr *a)
964 for (int i=0; i<MAX_CONNECTIONS; i++)
966 struct conn *c = &connections[i];
969 memcpy(&c->addr, a, sizeof(struct in_addr));
976 static struct conn *pid_to_conn(pid_t pid)
978 for (int i=0; i<MAX_CONNECTIONS; i++)
980 struct conn *c = &connections[i];
987 static void put_conn(struct conn *c)
1000 static struct tracker trackers[MAX_TRACKERS];
1002 static int get_tracker(struct conn *c)
1005 time_t now = time(NULL);
1008 for (i=0; i<MAX_TRACKERS; i++)
1011 if (!memcmp(&t->addr, &c->addr, sizeof(struct in_addr)))
1014 if (i < MAX_TRACKERS)
1016 if (now > t->last_access)
1018 t->tokens += (now - t->last_access) * (double) TBF_REFILL_PER_SEC;
1019 t->last_access = now;
1020 if (t->tokens > TBF_MAX)
1021 t->tokens = TBF_MAX;
1023 DTRACE("TBF: Using tracker %d (%.3f tokens)", i, t->tokens);
1028 for (int i=0; i<MAX_TRACKERS; i++)
1031 if (!t->active_conns && (min_i < 0 || t->last_access < trackers[min_i].last_access))
1036 DLOG("TBF: Out of trackers!");
1039 t = &trackers[min_i];
1041 DTRACE("TBF: Recycling tracker %d", min_i);
1043 DTRACE("TBF: Creating tracker %d", min_i);
1044 memset(t, 0, sizeof(*t));
1046 t->last_access = now;
1047 t->tokens = TBF_MAX;
1050 if (t->active_conns >= MAX_CONNS_PER_IP)
1052 DTRACE("TBF: Too many conns per IP");
1056 if (t->tokens >= 0.999)
1061 DTRACE("TBF: Passed (%d conns)", t->active_conns);
1066 DTRACE("TBF: Failed");
1072 static void put_tracker(struct conn *c)
1074 struct tracker *t = c->tracker;
1077 DLOG("put_tracker: no tracker?");
1081 if (t->active_conns <= 0)
1083 DLOG("put_tracker: no counter?");
1088 DTRACE("TBF: Put tracker (%d conns remain)", t->active_conns);
1091 static void run_as_daemon(int do_fork)
1093 int sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1098 if (setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
1099 die("setsockopt: %m");
1101 struct sockaddr_in sa = {
1102 .sin_family = AF_INET,
1103 .sin_port = ntohs(1969),
1104 .sin_addr.s_addr = INADDR_ANY,
1106 if (bind(sk, (struct sockaddr *) &sa, sizeof(sa)) < 0)
1108 if (listen(sk, 128) < 0)
1110 // if (fcntl(sk, F_SETFL, O_NONBLOCK) < 0)
1111 // die("fcntl: %m");
1120 FILE *f = fopen(PID_FILE, "w");
1123 fprintf(f, "%d\n", pid);
1130 setresgid(GID, GID, GID);
1131 setresuid(UID, UID, UID);
1135 struct sigaction sact = {
1136 .sa_handler = sigchld_handler,
1137 .sa_flags = SA_RESTART,
1139 if (sigaction(SIGCHLD, &sact, NULL) < 0)
1140 die("sigaction: %m");
1142 DLOG("Daemon ready");
1143 setproctitle("minsk: Listening");
1144 openlog("minsk", LOG_PID, LOG_LOCAL7);
1148 struct pollfd pfd[1] = {
1149 { .fd = sk, .events = POLLIN },
1152 int nfds = poll(pfd, 1, 60000);
1153 if (nfds < 0 && errno != EINTR)
1162 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1164 if (!WIFEXITED(status) || WEXITSTATUS(status))
1165 DLOG("Process %d exited with strange status %x", pid, status);
1167 struct conn *conn = pid_to_conn(pid);
1170 DTRACE("Connection with PID %d exited", pid);
1175 DTRACE("PID %d exited, matching no connection", pid);
1178 if (!(pfd[0].revents & POLLIN))
1181 socklen_t salen = sizeof(sa);
1182 int sk2 = accept(sk, (struct sockaddr *) &sa, &salen);
1192 DTRACE("Got connection: fd=%d", sk2);
1194 struct conn *conn = get_conn(&sa.sin_addr);
1195 const char *reason = NULL;
1198 if (!get_tracker(conn))
1200 DLOG("Connection from %s dropped: Throttling", inet_ntoa(sa.sin_addr));
1203 reason = "--- Sorry, but you are sending too many requests. Please slow down. ---\n";
1208 DLOG("Connection from %s dropped: Too many connections", inet_ntoa(sa.sin_addr));
1209 reason = "--- Sorry, maximum number of connections exceeded. Please come later. ---\n";
1215 DLOG("fork failed: %m");
1224 DLOG("Accepted connection from %s", inet_ntoa(sa.sin_addr));
1225 setproctitle("minsk: %s", inet_ntoa(sa.sin_addr));
1230 DLOG("Sending error message to %s", inet_ntoa(sa.sin_addr));
1231 setproctitle("minsk: %s ERR", inet_ntoa(sa.sin_addr));
1232 write(sk2, reason, strlen(reason));
1237 DTRACE("Created process %d", pid);
1246 static void run_as_daemon(int do_fork UNUSED)
1248 die("Daemon mode not supported in this version, need to recompile.");
1251 static void setproctitle_init(int argc UNUSED, char **argv UNUSED)
1257 static void init_memory(void)
1259 // For the contest, we fill the whole memory with -00 00 0000 0000 (HALT),
1260 // not +00 00 0000 0000 (NOP). Otherwise, an empty program would reveal
1261 // the location of the password :)
1262 for (int i=0; i<4096; i++)
1263 mem[i] = 01000000000000ULL;
1265 // Store the password
1267 mem[pos++] = 0574060565373;
1268 mem[pos++] = 0371741405340;
1269 mem[pos++] = 0534051524017;
1272 static const struct option longopts[] = {
1273 { "cpu-quota", 1, NULL, 'q' },
1274 { "daemon", 0, NULL, 'd' },
1275 { "nofork", 0, NULL, 'n' },
1276 { "print-quota", 1, NULL, 'p' },
1277 { "trace", 1, NULL, 't' },
1278 { NULL, 0, NULL, 0 },
1281 static void usage(void)
1285 --daemon Run as daemon and listen for network connections\n\
1286 --nofork When run with --daemon, avoid forking\n\
1287 --trace=<level> Enable tracing of program execution\n\
1288 --cpu-quota=<n> Set CPU quota to <n> instructions\n\
1289 --print-quota=<n> Set printer quota to <n> lines\n\
1294 int main(int argc, char **argv)
1297 int daemon_mode = 0;
1300 while ((opt = getopt_long(argc, argv, "", longopts, NULL)) >= 0)
1310 print_quota = atoi(optarg);
1313 cpu_quota = atoi(optarg);
1316 trace = atoi(optarg);
1324 setproctitle_init(argc, argv);
1328 run_as_daemon(do_fork);