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)
28 static int cpu_quota = -1;
29 static int print_quota = -1;
30 static void (*error_hook)(char *msg);
32 // Minsk-2 has 37-bit words in sign-magnitude representation (bit 36 = sign)
33 typedef unsigned long long int word;
35 #define WORD_MASK 01777777777777ULL
36 #define SIGN_MASK 01000000000000ULL
37 #define VAL_MASK 00777777777777ULL
39 static int wsign(word w)
41 return (w & SIGN_MASK) ? -1 : 1;
44 static word wabs(word w)
49 #define WF(w) (wsign(w) < 0 ? '-' : '+'), wabs(w)
51 static long long wtoll(word w)
59 static word wfromll(long long x)
61 word w = ((x < 0) ? -x : x) & VAL_MASK;
67 static double wtofrac(word w)
69 return (double)wtoll(w) / (double)(1ULL << 36);
72 static word wfromfrac(double d)
74 return wfromll((long long)(d * (double)(1ULL << 36)));
77 static int int_in_range(long long x)
79 return (x >= -(long long)VAL_MASK && x <= (long long)VAL_MASK);
82 static int frac_in_range(double d)
84 return (d > -1. && d < 1.);
87 static int wexp(word w)
90 return (w & 0100 ? -exp : exp);
93 static word wputexp(word w, int exp)
95 return ((w & ~(word)0177) | ((exp < 0) ? 0100 | (-exp) : exp));
98 static int wmanti(word w)
100 return ((w >> 8) & ((1 << 28) - 1));
103 static double wtofloat(word w)
105 double x = wmanti(w);
106 return ldexp(x, wexp(w) - 28);
109 static int float_in_range(double x)
112 return (x <= ldexp((1 << 28) - 1, 63 - 28));
115 static word wfromfloat(double x, int normalized)
124 double m = frexp(x, &exp);
125 word mm = (word) ldexp(m, 28);
130 if (normalized || exp < -91)
148 static word mem[4096];
150 static word rd(int addr)
152 word val = addr ? mem[addr] : 0;
154 printf("\tRD %04o = %c%012llo\n", addr, WF(val));
158 static void wr(int addr, word val)
160 assert(!(val & ~(WORD_MASK)));
162 printf("\tWR %04o = %c%012llo\n", addr, WF(val));
168 static void parse_error(char *msg)
171 error_hook("Parse error");
172 printf("Ошибка входа (стр. %d): %s\n", lino, msg);
176 static void parse_in(void)
181 while (fgets(line, sizeof(line), stdin))
184 char *eol = strchr(line, '\n');
186 parse_error("Строка слишком долгая");
190 if (!c[0] || c[0] == ';')
192 if (!strncmp(c, ";daji_zor_i_litva=", 18))
196 error_hook("Secret tracing switch flipped");
208 for (int i=0; i<4; i++)
212 if (*c >= '0' && *c <= '7')
213 addr = 8*addr + *c++ - '0';
215 parse_error("Плохая цифра");
220 parse_error("Адрес слишком долгий");
228 parse_error("Плохой знак");
230 for (int i=0; i<12; i++)
234 if (*c >= '0' && *c <= '7')
235 w = 8*w + *c++ - '0';
237 parse_error("Плохая цифра");
242 parse_error("Номер слишком долгий");
249 static word r1, r2, current_ins;
250 static int ip = 00050; // Standard program start location
253 static void stop(char *reason, char *notice)
257 printf("Машина остановлена -- %s\n", reason);
258 printf("СчАК:%04o См:%c%012llo Р1:%c%012llo Р2:%c%012llo\n", prev_ip, WF(acc), WF(r1), WF(r2));
262 static void over(void)
264 stop("Аварийный останов", "Overflow");
267 static void notimp(void)
270 stop("Устройство разбитое", "Not implemented");
273 static void noins(void)
276 stop("Эту команду не знаю", "Illegal instruction");
279 static uint16_t linebuf[128];
281 static uint16_t russian_chars[64] = {
282 '0', '1', '2', '3', '4', '5', '6', '7', // 0x
283 '8', '9', '+', '-', '/', ',', '.', ' ', // 1x
284 0x2169, '^', '(', ')', 0x00d7, '=', ';', '[', // 2x
285 ']', '*', '`', '\'', 0x2260, '<', '>', ':', // 3x
286 0x410, 0x411, 0x412, 0x413, 0x414, 0x415, 0x416, 0x417, // 4x
287 0x418, 0x419, 0x41a, 0x41b, 0x41c, 0x41d, 0x41e, 0x41f, // 5x
288 0x420, 0x421, 0x422, 0x423, 0x424, 0x425, 0x426, 0x427, // 6x
289 0x428, 0x429, 0x42b, 0x42c, 0x42d, 0x42e, 0x42f, 0x2013 // 7x
292 static uint16_t latin_chars[64] = {
293 '0', '1', '2', '3', '4', '5', '6', '7', // 0x
294 '8', '9', '+', '-', '/', ',', '.', ' ', // 1x
295 0x2169, '^', '(', ')', 0x00d7, '=', ';', '[', // 2x
296 ']', '*', '`', '\'', 0x2260, '<', '>', ':', // 3x
297 'A', 'B', 'W', 'G', 'D', 'E', 'V', 'Z', // 4x
298 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 5x
299 'R', 'S', 'T', 'U', 'F', 'H', 'C', ' ', // 6x
300 ' ', ' ', 'Y', 'X', ' ', ' ', 'Q', 0x2013 // 7x
303 static void print_line(int r)
306 * Meaning of bits of r:
307 * 0 = perform line feed
313 if (print_quota > 0 && !--print_quota)
314 stop("Бумага дошла - нужно ехать в Сибирь про новую", "Out of paper");
315 for (int i=0; i<128; i++)
324 putchar(0xc0 | (ch >> 6));
325 putchar(0x80 | (ch & 0x3f));
329 putchar(0xe0 | (ch >> 12));
330 putchar(0x80 | ((ch >> 6) & 0x3f));
331 putchar(0x80 | (ch & 0x3f));
336 memset(linebuf, 0, sizeof(linebuf));
344 static void print_ins(int x, int y)
348 int r = (x >> 9) & 7;
361 case 0: // Decimal float
362 fmt = "+dddddddx+xbd";
364 case 1: // Octal number
365 fmt = "+oooooooooooo";
367 case 2: // Decimal fixed
370 case 3: // Decimal unsigned
374 case 4: // One Russian symbol
377 case 5: // Russian text
380 case 6: // One Latin symbol
383 default: // Latin text
400 ch = (yy & (1ULL << bit)) ? '-' : '+';
404 ch = '0' + ((yy >> bit) & 1);
408 ch = '0' + ((yy >> bit) & 7);
412 ch = '0' + ((yy >> bit) & 15);
418 ch = russian_chars[(yy >> bit) & 077];
422 ch = latin_chars[(yy >> bit) & 077];
430 if (ch == '0' || ch == ' ')
436 pos = (pos+1) & 0177;
441 static void run(void)
450 int op = (w >> 30) & 0177; // Operation code
451 int ax = (w >> 28) & 3; // Address extensions not supported
452 int ix = (w >> 24) & 15; // Indexing
453 int x = (w >> 12) & 07777; // Operands (original form)
455 int xi=x, yi=y; // (indexed form)
457 printf("@%04o %c%02o %02o %04o %04o\n",
459 (w & SIGN_MASK) ? '-' : '+',
460 (int)((w >> 30) & 077),
461 (int)((w >> 24) & 077),
469 xi = (xi + (int)((i >> 12) & 07777)) & 07777;
470 yi = (yi + (int)(i & 07777)) & 07777;
472 printf("\tIndexing -> %04o %04o\n", xi, yi);
477 if (cpu_quota > 0 && !--cpu_quota)
478 stop("Тайм-аут", "CPU quota exceeded");
480 /* Arithmetic operations */
483 long long aa, bb, cc;
487 auto void afetch(void);
497 auto void astore(word result);
498 void astore(word result)
505 auto void astore_int(long long x);
506 void astore_int(long long x)
508 if (!int_in_range(x))
513 auto void astore_frac(double f);
514 void astore_frac(double f)
516 if (!frac_in_range(f))
518 astore(wfromfrac(f));
521 auto void astore_float(double f);
522 void astore_float(double f)
524 if (!float_in_range(f))
526 astore(wfromfloat(f, 0));
535 case 004 ... 007: // XOR
539 case 010 ... 013: // FIX addition
541 astore_int(wtoll(a) + wtoll(b));
543 case 014 ... 017: // FP addition
545 astore_float(wtofloat(a) + wtofloat(b));
547 case 020 ... 023: // FIX subtraction
549 astore_int(wtoll(a) - wtoll(b));
551 case 024 ... 027: // FP subtraction
553 astore_float(wtofloat(a) - wtofloat(b));
555 case 030 ... 033: // FIX multiplication
557 astore_frac(wtofrac(a) * wtofrac(b));
559 case 034 ... 037: // FP multiplication
561 astore_float(wtofloat(a) * wtofloat(b));
563 case 040 ... 043: // FIX division
569 astore_frac(ad / bd);
571 case 044 ... 047: // FP division
575 if (!bd || wexp(b) < -63)
577 astore_float(ad / bd);
579 case 050 ... 053: // FIX subtraction of abs values
581 astore_int(wabs(a) - wabs(b));
583 case 054 ... 057: // FP subtraction of abs values
585 astore_float(fabs(wtofloat(a)) - fabs(wtofloat(b)));
587 case 060 ... 063: // Shift logical
590 if (i <= -37 || i >= 37)
593 astore((a << i) & WORD_MASK);
597 case 064 ... 067: // Shift arithmetical
601 if (i <= -36 || i >= 36)
604 cc = (aa << i) & VAL_MASK;
607 astore((a & SIGN_MASK) | wfromll(cc));
609 case 070 ... 073: // And
613 case 074 ... 077: // Or
621 stop("Останов машины", "Halted");
622 case 0103: // I/O magtape
624 case 0104: // Disable rounding
626 case 0105: // Enable rounding
628 case 0106: // Interrupt control
630 case 0107: // Reverse tape
633 wr(yi, r1 = acc = rd(xi));
635 case 0111: // Move negative
636 wr(yi, acc = (r1 = rd(xi)) ^ SIGN_MASK);
638 case 0112: // Move absolute value
639 wr(yi, acc = (r1 = rd(xi)) & VAL_MASK);
641 case 0113: // Read from keyboard
643 case 0114: // Copy sign
644 wr(yi, acc = rd(yi) ^ ((r1 = rd(xi)) & SIGN_MASK));
646 case 0115: // Read code from R1 (obscure)
648 case 0116: // Copy exponent
649 wr(yi, acc = wputexp(rd(yi), wexp(r1 = rd(xi))));
651 case 0117: // I/O teletype
657 aa = (a >> 24) & 017777;
660 b = rd(y); // (a mountain range near Prague)
661 acc = ((aa-1) << 24) |
662 (((((a >> 12) & 07777) + (b >> 12) & 07777) & 07777) << 12) |
663 (((a & 07777) + (b & 07777)) & 07777);
671 case 0131: // Jump to subroutine
672 wr(y, acc = ((030ULL << 30) | ((ip & 07777ULL) << 12)));
675 case 0132: // Jump if positive
681 case 0133: // Jump if overflow
682 // Since we always trap on overflow, this instruction always jumps to the 1st address
685 case 0134: // Jump if zero
691 case 0135: // Jump if key pressed
692 // No keys are ever pressed, so always jump to 2nd
695 case 0136: // Interrupt masking
697 case 0137: // Used only when reading from tape
699 case 0140 ... 0147: // I/O
701 case 0150 ... 0154: // I/O
703 case 0160 ... 0161: // I/O
705 case 0162: // Printing
710 case 0170: // FIX multiplication, bottom part
712 if (wtofrac(a) * wtofrac(b) >= .1/(1ULL << 32))
714 acc = wfromll(((unsigned long long)wabs(a) * (unsigned long long)wabs(b)) & VAL_MASK);
715 // XXX: What should be the sign? The book does not define that.
728 case 0172: // Add exponents
731 i = wexp(a) + wexp(b);
732 if (i < -63 || i > 63)
737 case 0173: // Sub exponents
740 i = wexp(b) - wexp(a);
741 if (i < -63 || i > 63)
746 case 0174: // Addition in one's complement
753 // XXX: The effect on the accumulator is undocumented, but likely to be as follows:
756 case 0175: // Normalization
761 wr((yi+1) & 07777, 0);
769 while (!(a & (SIGN_MASK >> 1)))
776 wr((yi+1) & 07777, i);
779 case 0176: // Population count
782 for (int i=0; i<36; i++)
785 // XXX: Guessing that acc gets a copy of the result
794 printf("\tACC:%c%012llo R1:%c%012llo R2:%c%012llo\n", WF(acc), WF(r1), WF(r2));
798 /*** Daemon interface ***/
804 #include <sys/signal.h>
805 #include <sys/wait.h>
806 #include <sys/poll.h>
807 #include <sys/socket.h>
808 #include <netinet/in.h>
809 #include <arpa/inet.h>
812 #define DTRACE(msg, args...) fprintf(stderr, msg "\n", ##args)
813 #define DLOG(msg, args...) fprintf(stderr, msg "\n", ##args)
815 #define DTRACE(msg, args...) do { } while(0)
816 #define DLOG(msg, args...) syslog(LOG_INFO, msg, ##args)
819 #define MAX_CONNECTIONS 50 // Per daemon
820 #define MAX_CONNS_PER_IP 1 // Per IP
821 #define MAX_TRACKERS 200 // IP address trackers
822 #define TBF_MAX 5 // Max number of tokens in the bucket
823 #define TBF_REFILL_PER_SEC 0.2 // Bucket refill rate (buckets/sec)
825 #define PID_FILE "/var/run/pd-minsk.pid"
829 static void die(char *msg)
831 fprintf(stderr, "minsk: ");
832 fprintf(stderr, msg);
837 static char **spt_argv;
838 static char *spt_start, *spt_end;
840 static void setproctitle_init(int argc, char **argv)
843 char **env, **oldenv, *t;
847 /* Create a backup copy of environment */
850 for (i=0; oldenv[i]; i++)
851 len += strlen(oldenv[i]) + 1;
852 __environ = env = malloc(sizeof(char *)*(i+1));
854 if (!__environ || !t)
855 die("malloc failed");
856 for (i=0; oldenv[i]; i++)
859 len = strlen(oldenv[i]) + 1;
860 memcpy(t, oldenv[i], len);
865 /* Scan for consecutive free space */
866 spt_start = spt_end = argv[0];
867 for (i=0; i<argc; i++)
868 if (!i || spt_end+1 == argv[i])
869 spt_end = argv[i] + strlen(argv[i]);
870 for (i=0; oldenv[i]; i++)
871 if (spt_end+1 == oldenv[i])
872 spt_end = oldenv[i] + strlen(oldenv[i]);
876 setproctitle(const char *msg, ...)
883 if (spt_end > spt_start)
885 n = vsnprintf(buf, sizeof(buf), msg, args);
886 if (n >= (int) sizeof(buf) || n < 0)
887 sprintf(buf, "<too-long>");
888 n = spt_end - spt_start;
889 strncpy(spt_start, buf, n);
891 spt_argv[0] = spt_start;
897 static void sigchld_handler(int sig __attribute__((unused)))
901 static void sigalrm_handler(int sig __attribute__((unused)))
903 const char err[] = "--- Timed out. Time machine disconnected. ---\n";
904 write(1, err, sizeof(err));
905 DLOG("Connection timed out");
909 static void child_error_hook(char *err)
911 DLOG("Stopped: %s", err);
914 static void child(int sk2)
920 struct sigaction sact = {
921 .sa_handler = sigalrm_handler,
923 if (sigaction(SIGALRM, &sact, NULL) < 0)
924 die("sigaction: %m");
931 const char welcome[] = "+++ Welcome to our computer museum. +++\n+++ Our time machine will connect you to one of our exhibits. +++\n\n";
932 write(1, welcome, sizeof(welcome));
934 error_hook = child_error_hook;
944 struct tracker *tracker;
947 static struct conn connections[MAX_CONNECTIONS];
949 static struct conn *get_conn(struct in_addr *a)
951 for (int i=0; i<MAX_CONNECTIONS; i++)
953 struct conn *c = &connections[i];
956 memcpy(&c->addr, a, sizeof(struct in_addr));
963 static struct conn *pid_to_conn(pid_t pid)
965 for (int i=0; i<MAX_CONNECTIONS; i++)
967 struct conn *c = &connections[i];
974 static void put_conn(struct conn *c)
987 static struct tracker trackers[MAX_TRACKERS];
989 static int get_tracker(struct conn *c)
992 time_t now = time(NULL);
995 for (i=0; i<MAX_TRACKERS; i++)
998 if (!memcmp(&t->addr, &c->addr, sizeof(struct in_addr)))
1001 if (i < MAX_TRACKERS)
1003 if (now > t->last_access)
1005 t->tokens += (now - t->last_access) * (double) TBF_REFILL_PER_SEC;
1006 t->last_access = now;
1007 if (t->tokens > TBF_MAX)
1008 t->tokens = TBF_MAX;
1010 DTRACE("TBF: Using tracker %d (%.3f tokens)", i, t->tokens);
1015 for (int i=0; i<MAX_TRACKERS; i++)
1018 if (!t->active_conns && (min_i < 0 || t->last_access < trackers[min_i].last_access))
1023 DLOG("TBF: Out of trackers!");
1026 t = &trackers[min_i];
1028 DTRACE("TBF: Recycling tracker %d", min_i);
1030 DTRACE("TBF: Creating tracker %d", min_i);
1031 memset(t, 0, sizeof(*t));
1033 t->last_access = now;
1034 t->tokens = TBF_MAX;
1037 if (t->active_conns >= MAX_CONNS_PER_IP)
1039 DTRACE("TBF: Too many conns per IP");
1043 if (t->tokens >= 0.999)
1048 DTRACE("TBF: Passed (%d conns)", t->active_conns);
1053 DTRACE("TBF: Failed");
1059 static void put_tracker(struct conn *c)
1061 struct tracker *t = c->tracker;
1064 DLOG("put_tracker: no tracker?");
1068 if (t->active_conns <= 0)
1070 DLOG("put_tracker: no counter?");
1075 DTRACE("TBF: Put tracker (%d conns remain)", t->active_conns);
1078 static void run_as_daemon(int do_fork)
1080 int sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1085 if (setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
1086 die("setsockopt: %m");
1088 struct sockaddr_in sa = {
1089 .sin_family = AF_INET,
1090 .sin_port = ntohs(1969),
1091 .sin_addr.s_addr = INADDR_ANY,
1093 if (bind(sk, (struct sockaddr *) &sa, sizeof(sa)) < 0)
1095 if (listen(sk, 128) < 0)
1097 // if (fcntl(sk, F_SETFL, O_NONBLOCK) < 0)
1098 // die("fcntl: %m");
1107 FILE *f = fopen(PID_FILE, "w");
1110 fprintf(f, "%d\n", pid);
1117 setresgid(GID, GID, GID);
1118 setresuid(UID, UID, UID);
1122 struct sigaction sact = {
1123 .sa_handler = sigchld_handler,
1124 .sa_flags = SA_RESTART,
1126 if (sigaction(SIGCHLD, &sact, NULL) < 0)
1127 die("sigaction: %m");
1129 DLOG("Daemon ready");
1130 setproctitle("minsk: Listening");
1131 openlog("minsk", LOG_PID, LOG_LOCAL7);
1135 struct pollfd pfd[1] = {
1136 { .fd = sk, .events = POLLIN },
1139 int nfds = poll(pfd, 1, 60000);
1140 if (nfds < 0 && errno != EINTR)
1149 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1151 if (!WIFEXITED(status) || WEXITSTATUS(status))
1152 DLOG("Process %d exited with strange status %x", pid, status);
1154 struct conn *conn = pid_to_conn(pid);
1157 DTRACE("Connection with PID %d exited", pid);
1162 DTRACE("PID %d exited, matching no connection", pid);
1165 if (!(pfd[0].revents & POLLIN))
1168 socklen_t salen = sizeof(sa);
1169 int sk2 = accept(sk, (struct sockaddr *) &sa, &salen);
1179 DTRACE("Got connection: fd=%d", sk2);
1181 struct conn *conn = get_conn(&sa.sin_addr);
1182 const char *reason = NULL;
1185 if (!get_tracker(conn))
1187 DLOG("Connection from %s dropped: Throttling", inet_ntoa(sa.sin_addr));
1190 reason = "--- Sorry, but you are sending too many requests. Please slow down. ---\n";
1195 DLOG("Connection from %s dropped: Too many connections", inet_ntoa(sa.sin_addr));
1196 reason = "--- Sorry, maximum number of connections exceeded. Please come later. ---\n";
1202 DLOG("fork failed: %m");
1211 DLOG("Accepted connection from %s", inet_ntoa(sa.sin_addr));
1212 setproctitle("minsk: %s", inet_ntoa(sa.sin_addr));
1217 DLOG("Sending error message to %s", inet_ntoa(sa.sin_addr));
1218 setproctitle("minsk: %s ERR", inet_ntoa(sa.sin_addr));
1219 write(sk2, reason, strlen(reason));
1224 DTRACE("Created process %d", pid);
1231 static void init_memory(void)
1233 // For the contest, we fill the whole memory with -00 00 0000 0000 (HALT),
1234 // not +00 00 0000 0000 (NOP). Otherwise, an empty program would reveal
1235 // the location of the password :)
1236 for (int i=0; i<4096; i++)
1237 mem[i] = 01000000000000ULL;
1239 // Store the password
1241 mem[pos++] = 0574060565373;
1242 mem[pos++] = 0371741405340;
1243 mem[pos++] = 0534051524017;
1246 int main(int argc, char **argv)
1252 setproctitle_init(argc, argv);
1253 if (!strcmp(argv[1], "--daemon"))
1255 else if (!strcmp(argv[1], "--net"))
1257 else if (!strncmp(argv[1], "--trace=", 8))
1258 trace = atoi(argv[1] + 8);
1260 die("Usage: minsk [--daemon | --net]");