aboutsummaryrefslogtreecommitdiffstats
path: root/community/rethinkdb/enable-build-s390x.patch
blob: afc876c86974215323a417d8688d39e24d44de80 (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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
diff --git a/configure b/configure
index eafc63d2e3..7c86c2b9c9 100755
--- a/configure
+++ b/configure
@@ -84,6 +84,8 @@ configure () {
         arm*)
             var_append LDFLAGS -ldl
             final_warning="ARM support is still experimental" ;;
+        s390x)
+            final_warning="s390x support is still experimental" ;;
         *)
             error "unsupported architecture: $MACHINE"
     esac
diff --git a/mk/support/pkg/jemalloc.sh b/mk/support/pkg/jemalloc.sh
index 9c17cf857c..383d4764f0 100644
--- a/mk/support/pkg/jemalloc.sh
+++ b/mk/support/pkg/jemalloc.sh
@@ -1,7 +1,7 @@
 
 version=4.1.0
 
-src_url=http://www.canonware.com/download/jemalloc/jemalloc-$version.tar.bz2
+src_url=https://github.com/jemalloc/jemalloc/releases/download/4.1.0/jemalloc-4.1.0.tar.bz2
 
 pkg_install () {
     configure_flags="--libdir=${install_dir}/lib"
diff --git a/mk/support/pkg/node.sh b/mk/support/pkg/node.sh
index 84634a47a9..6e84f7b240 100644
--- a/mk/support/pkg/node.sh
+++ b/mk/support/pkg/node.sh
@@ -1,4 +1,5 @@
 
-version=0.12.2
+version=6.10.0
 
 src_url=http://nodejs.org/dist/v$version/node-v$version.tar.gz
+src_url_sha1=3bb2629ed623f38b8c3011cf422333862d3653a3
diff --git a/mk/support/pkg/npm-pkg.inc b/mk/support/pkg/npm-pkg.inc
index a149265f9e..3ce901453f 100644
--- a/mk/support/pkg/npm-pkg.inc
+++ b/mk/support/pkg/npm-pkg.inc
@@ -49,7 +49,7 @@ pkg_install () {
     mkdir -p "$install_dir/node_modules"
     local pkg
     pkg=$(niceabspath "$src_dir")
-    in_dir "$install_dir" npm install "$pkg"
+    in_dir "$install_dir" npm --registry http://no-npm-registry.rethinkdb.com install "$pkg"
 
     local bin_dir="$install_dir/node_modules/$full_npm_package/node_modules/.bin/"
     mkdir -p "$install_dir/bin"
diff --git a/mk/support/pkg/v8.sh b/mk/support/pkg/v8.sh
index 5454e76fb4..f01be00a5d 100644
--- a/mk/support/pkg/v8.sh
+++ b/mk/support/pkg/v8.sh
@@ -1,30 +1,61 @@
+if [[ "$(uname -m)" = s390x ]]; then
+    # V8 3.30.33 does not support s390x.
+    # This s390x-specific code can be removed once V8 is updated to 5.1+.
+    version=3.28-s390
 
-version=3.30.33.16-patched2
-# See http://omahaproxy.appspot.com/ for the current stable/beta/dev versions of v8
-
-src_url=http://commondatastorage.googleapis.com/chromium-browser-official/v8-${version/-patched2/}.tar.bz2
+    pkg_fetch () {
+        pkg_make_tmp_fetch_dir
+        git clone --depth 1 https://chromium.googlesource.com/chromium/tools/depot_tools.git "$tmp_dir/depot_tools"
+        PATH="$tmp_dir/depot_tools:$PATH"
+        in_dir "$tmp_dir" gclient config --unmanaged https://github.com/ibmruntimes/v8z.git
+        in_dir "$tmp_dir" git clone https://github.com/ibmruntimes/v8z.git
+        cd "$tmp_dir/v8z"
+        git checkout 3.28-s390
+        rm -rf "$src_dir"
+        mv "$tmp_dir/v8z" "$src_dir"
+        mv "$tmp_dir/depot_tools" "$src_dir"
+        pkg_remove_tmp_fetch_dir
+    }
+else
+    version=3.30.33.16-patched2
+    # See http://omahaproxy.appspot.com/ for the current stable/beta/dev versions of v8
+    src_url=http://commondatastorage.googleapis.com/chromium-browser-official/v8-${version/-patched2/}.tar.bz2
+fi
 
 pkg_install-include () {
     pkg_copy_src_to_build
+# See http://omahaproxy.appspot.com/ for the current stable/beta/dev versions of v8
+# See http://omahaproxy.appspot.com/ for the current stable/beta/dev versions of v8
     in_dir "$build_dir" patch -fp1 < "$pkg_dir"/patch/v8_2-HandleScope-protected.patch
     
     rm -rf "$install_dir/include"
     mkdir -p "$install_dir/include"
-    cp -RL "$build_dir/include/." "$install_dir/include"
-    sed -i.bak 's/include\///' "$install_dir/include/libplatform/libplatform.h"
-    
-    # -- assemble the icu headers
-    if [[ "$CROSS_COMPILING" = 1 ]]; then
-        ( cross_build_env; in_dir "$build_dir/third_party/icu" ./configure --prefix="$(niceabspath "$install_dir")" --enable-static "$@" )
+    if [[ "$(uname -m)" = s390x ]]; then
+        # for s390x we need to generate correct header files
+       cd $build_dir
+       export PATH=$(pwd)/depot_tools:$PATH
+       #cd v8z
+       make dependencies || true
+       make s390x -j4 library=static werror=no snapshot=off
+
+       #s390x cp -RL "$src_dir/include/." "$install_dir/include"
+       cp -RL "$build_dir/include/." "$install_dir/include"
+       cp -RL "$build_dir/third_party/icu/source/common/." "$install_dir/include"
+       sed -i.bak 's/include\///' "$install_dir/include/libplatform/libplatform.h"
     else
-        in_dir "$build_dir/third_party/icu/source" ./configure --prefix="$(niceabspath "$install_dir")" --enable-static --disable-layout "$@"
+       cp -RL "$src_dir/include/." "$install_dir/include"
+       sed -i.bak 's/include\///' "$install_dir/include/libplatform/libplatform.h"
+
+       # -- assemble the icu headers
+       if [[ "$CROSS_COMPILING" = 1 ]]; then
+           ( cross_build_env; in_dir "$build_dir/third_party/icu" ./configure --prefix="$(niceabspath "$install_dir")" --enable-static "$@" )
+       else
+           in_dir "$build_dir/third_party/icu/source" ./configure --prefix="$(niceabspath "$install_dir")" --enable-static --disable-layout "$@"
+       fi
+
+       in_dir "$build_dir/third_party/icu/source" make install-headers-recursive
+
     fi
-    # The install-headers-recursive target is missing. Let's patch it.
-    sed -i.bak $'s/distclean-recursive/install-headers-recursive/g;$a\\\ninstall-headers-local:' "$build_dir/third_party/icu/source/Makefile"
-    for file in "$build_dir"/third_party/icu/source/*/Makefile; do
-        sed -i.bak $'$a\\\ninstall-headers:' "$file"
-    done
-    in_dir "$build_dir/third_party/icu/source" make install-headers-recursive
 }
 
 pkg_install () {
@@ -43,22 +74,31 @@ pkg_install () {
     case ${host%%-*} in
         i?86)   arch=ia32 ;;
         x86_64) arch=x64 ;;
+        s390x)  arch=s390x ;;
         arm*)   arch=arm; arch_gypflags=$raspberry_pi_gypflags ;;
         *)      arch=native ;;
     esac
     mode=release
-    pkg_make $arch.$mode CXX=$CXX LINK=$CXX LINK.target=$CXX GYPFLAGS="-Dwerror= $arch_gypflags" V=1
-    for lib in `find "$build_dir/out/$arch.$mode" -maxdepth 1 -name \*.a` `find "$build_dir/out/$arch.$mode/obj.target" -name \*.a`; do
-        name=`basename $lib`
-        cp $lib "$install_dir/lib/${name/.$arch/}"
-    done
-    touch "$install_dir/lib/libv8.a" # Create a dummy libv8.a because the makefile looks for it
+    if [[ "$arch" = "s390x" ]]; then
+       for lib in `find "$build_dir/out/$arch.$mode" -maxdepth 1 -name \*.a` `find "$build_dir/out/$arch.$mode/obj.target" -name \*.a` `find "$build_dir/out/$arch.$mode/obj.target/third_party/icu" -name \*.a` `find "$build_dir/out/$arch.$mode/obj.target/tools/gyp" -name \*.a` ; do
+           name=`basename $lib`
+           cp $lib "$install_dir/lib/${name/.$arch/}"
+       done
+    else
+       pkg_make $arch.$mode CXX=$CXX LINK=$CXX LINK.target=$CXX GYPFLAGS="-Dwerror= $arch_gypflags" V=1
+       for lib in `find "$build_dir/out/$arch.$mode" -maxdepth 1 -name \*.a` `find "$build_dir/out/$arch.$mode/obj.target" -name \*.a`; do
+           name=`basename $lib`
+           cp $lib "$install_dir/lib/${name/.$arch/}"
+       done
+       touch "$install_dir/lib/libv8.a" # Create a dummy libv8.a because the makefile looks for it
+    fi
+
 }
 
 pkg_link-flags () {
     # These are the necessary libraries recommended by the docs:
     # https://developers.google.com/v8/get_started#hello
-    for lib in libv8_{base,libbase,snapshot,libplatform}; do
+    for lib in libv8_{base,libbase,nosnapshot,libplatform}; do
         echo "$install_dir/lib/$lib.a"
     done
     for lib in libicu{i18n,uc,data}; do
diff --git a/src/arch/runtime/context_switching.cc b/src/arch/runtime/context_switching.cc
index d7295751e6..63bb43ccfa 100644
--- a/src/arch/runtime/context_switching.cc
+++ b/src/arch/runtime/context_switching.cc
@@ -60,54 +60,77 @@ artificial_stack_t::artificial_stack_t(void (*initial_fun)(void), size_t _stack_
     valgrind_stack_id = VALGRIND_STACK_REGISTER(stack.get(), (intptr_t)stack.get() + stack_size);
 #endif
 
-    /* Set up the stack... */
-
-    uintptr_t *sp; /* A pointer into the stack. Note that uintptr_t is ideal since it points to something of the same size as the native word or pointer. */
-
-    /* Start at the beginning. */
+    // Setup the new stack (grows downwards).
+    //
+    // +---------------+ <- (1) initial sp.
+    // |               |
+    // +---------------+ <- (2) sp aligned as needed.
+    // |               |
+    // +---------------+ <- (3) sp after allocating (fake) caller stack frame;
+    // |  initial_fun  |    will be the stack pointer at entry to initial_fun.
+    // +---------------+ <- (4) sp after pushing the return address, initial_fun.
+    // |               |
+    // |  callee-save  |
+    // |   registers   |
+    // |               |
+    // +---------------+ <- (5) sp after allocating space for callee-save registers.
+    //
+    // When swapcontext is called it will pop the callee-save registers off of the
+    // stack (may be junk), pop initial_fun off the stack and then jump to initial_fun.
+    uintptr_t *sp;
+
+    // (1) initialize sp to point at the top of the stack.
     sp = reinterpret_cast<uintptr_t *>(uintptr_t(stack.get()) + stack_size);
-
-    /* Align stack. The x86-64 ABI requires the stack pointer to always be
-    16-byte-aligned at function calls. That is, "(%rsp - 8) is always a multiple
-    of 16 when control is transferred to the function entry point". */
+    // (2) align sp to meet platform ABI requirements.
+    // Note: not all platforms require 16-byte alignment, but it is easier to do it
+    // everywhere.
     sp = reinterpret_cast<uintptr_t *>(uintptr_t(sp) & static_cast<uintptr_t>(-16L));
 
-    // Currently sp is 16-byte aligned.
-
-    /* Set up the instruction pointer; this will be popped off the stack by ret (or popped
-    explicitly, for ARM) in swapcontext once all the other registers have been "restored". */
-    sp--;
-
-    /* This seems to prevent Valgrind from complaining about uninitialized value
-    errors when throwing an uncaught exception. My assembly-fu isn't strong
-    enough to explain why, though. */
-    /* Also, on ARM, this gets popped into `r12` */
-    *sp = 0;
+    // (3) allocate caller stack frame.
+#if defined(__i386__) || defined(__x86_64__)
+    // The x86-64 ABI requires the stack pointer to always be 16-byte-aligned at
+    // function calls. That is, "(%rsp - 8) is always a multiple of 16 when control
+    // is transferred to the function entry point".
+    const size_t min_frame = 1;
+#elif defined(__s390x__)
+    // The s390x ABI requires a 160-byte caller allocated register save area.
+    const size_t min_frame = 20;
+#elif defined(__arm__)
+    // This slot is used to store r12.
+    const size_t min_frame = 1;
+#endif
+    // Zero the caller stack frame. Prevents Valgrind complaining about uninitialized
+    // value errors when throwing an uncaught exception.
+    for (size_t i = 0; i < min_frame; i++) {
+        sp--;
+        *sp = 0;
+    }
 
+    // (4) write the return address to the stack.
     sp--;
 
-    // Subtracted 2*sizeof(uintptr_t), so sp is still double-word-size (16-byte for amd64) aligned.
-
     *sp = reinterpret_cast<uintptr_t>(initial_fun);
 
+    // (5) allocate space for callee-save registers. These will be popped off the
+    // stack by swapcontext but initial_fun should ignore their contents so we
+    // don't initialize them to anything.
+    // See swapcontext for more information about the way registers are restored.
 #if defined(__i386__)
     /* For i386, we are obligated (by the A.B.I. specification) to preserve esi, edi, ebx, ebp, and esp. We do not push esp onto the stack, though, since we will have needed to retrieve it anyway in order to get to the point on the stack from which we would pop. */
-    sp -= 4;
+    sp -= 4; // esi, edi, ebx and ebp.
 #elif defined(__x86_64__)
-    /* These registers (r12, r13, r14, r15, rbx, rbp) are going to be popped off
-    the stack by swapcontext; they're callee-saved, so whatever happens to be in
-    them will be ignored. */
-    sp -= 6;
+    sp -= 6; // r12-r15, rbx and rbp.
 #elif defined(__arm__)
-    /* We must preserve r4, r5, r6, r7, r8, r9, r10, and r11. Because we have to store the LR (r14) in swapcontext as well, we also store r12 in swapcontext to keep the stack double-word-aligned. However, we already accounted for both of those by decrementing sp twice above (once for r14 and once for r12, say). */
-    sp -= 8;
+    // Note: r12 is also stored, in the 'caller frame' slot above the return
+    // address.
+    sp -= 8; // r4-r11.
+#elif defined(__s390x__)
+    sp -= 16; // r6-r13 and f8-f15.
 #else
 #error "Unsupported architecture."
 #endif
 
-    // Subtracted (multiple of 2)*sizeof(uintptr_t), so sp is still double-word-size (16-byte for amd64, 8-byte for i386 and ARM) aligned.
-
-    /* Set up stack pointer. */
+    // Save stack pointer.
     context.pointer = sp;
 
     /* Our coroutines never return, so we don't put anything else on the stack.
@@ -262,8 +285,8 @@ void context_switch(artificial_stack_context_ref_t *current_context_out, artific
 }
 
 asm(
-#if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
-// We keep the i386, x86_64, and ARM stuff interleaved in order to enforce commonality.
+#if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined (__s390x__)
+// We keep architecture-specific code interleaved in order to enforce commonality.
 #if defined(__x86_64__)
 #if defined(__LP64__) || defined(__LLP64__)
 // Pointers are of the right size
@@ -281,16 +304,19 @@ asm(
     /* `current_pointer_out` is in `%rdi`. `dest_pointer` is in `%rsi`. */
 #elif defined(__arm__)
     /* `current_pointer_out` is in `r0`. `dest_pointer` is in `r1` */
+#elif defined(__s390x_)
+    /* `current_pointer_out` is in `%r2`. `dest_pointer` is in `%r3`. */
 #endif
 
-    /* Save preserved registers (the return address is already on the stack). */
+    /* Save preserved registers. */
 #if defined(__i386__)
-    /* For i386, we must preserve esi, edi, ebx, ebp, and esp. */
+    /* Preserve esi, edi, ebx, and ebp. The return address is already on the stack. */
     "push %esi\n"
     "push %edi\n"
     "push %ebx\n"
     "push %ebp\n"
 #elif defined(__x86_64__)
+    // Preserve r12-r15, rbx, and rbp. The return address is already on the stack.
     "pushq %r12\n"
     "pushq %r13\n"
     "pushq %r14\n"
@@ -298,10 +324,23 @@ asm(
     "pushq %rbx\n"
     "pushq %rbp\n"
 #elif defined(__arm__)
-    /* Note that we push `LR` (`r14`) since that's not implicitly done at a call on ARM. We include `r12` just to keep the stack double-word-aligned. The order here is really important, as it must match the way we set up the stack in artificial_stack_t::artificial_stack_t. For consistency with the other architectures, we push `r12` first, then `r14`, then the rest. */
+    // Preserve r4-r12 and the return address (r14). For consistency with x86 r12 is
+    // pushed first, followed by r14 and then r4-r11.
     "push {r12}\n"
     "push {r14}\n"
     "push {r4-r11}\n"
+#elif defined(__s390x__)
+    // Preserve r6-r13, the return address (r14), and f8-f15.
+    "aghi %r15, -136\n"
+    "stmg %r6, %r14, 64(%r15)\n"
+    "std %f8, 0(%r15)\n"
+    "std %f9, 8(%r15)\n"
+    "std %f10, 16(%r15)\n"
+    "std %f11, 24(%r15)\n"
+    "std %f12, 32(%r15)\n"
+    "std %f13, 40(%r15)\n"
+    "std %f14, 48(%r15)\n"
+    "std %f15, 56(%r15)\n"
 #endif
 
     /* Save old stack pointer. */
@@ -316,6 +355,9 @@ asm(
 #elif defined(__arm__)
     /* On ARM, the first argument is in `r0`. `r13` is the stack pointer. */
     "str r13, [r0]\n"
+#elif defined(__s390x__)
+    /* On s390x, the first argument is in r2. r15 is the stack pointer. */
+    "stg %r15, 0(%r2)\n"
 #endif
 
     /* Load the new stack pointer and the preserved registers. */
@@ -330,6 +372,9 @@ asm(
 #elif defined(__arm__)
     /* On ARM, the second argument is in `r1` */
     "mov r13, r1\n"
+#elif defined(__s390x__)
+    /* On s390x, the second argument is in r3 */
+    "lgr %r15, %r3\n"
 #endif
 
 #if defined(__i386__)
@@ -348,6 +393,17 @@ asm(
     "pop {r4-r11}\n"
     "pop {r14}\n"
     "pop {r12}\n"
+#elif defined(__s390x__)
+    "lmg %r6, %r14, 64(%r15)\n"
+    "ld %f8, 0(%r15)\n"
+    "ld %f9, 8(%r15)\n"
+    "ld %f10, 16(%r15)\n"
+    "ld %f11, 24(%r15)\n"
+    "ld %f12, 32(%r15)\n"
+    "ld %f13, 40(%r15)\n"
+    "ld %f14, 48(%r15)\n"
+    "ld %f15, 56(%r15)\n"
+    "aghi %r15, 136\n"
 #endif
 
 #if defined(__i386__) || defined(__x86_64__)
@@ -360,6 +416,9 @@ asm(
     /* Above, we popped `LR` (`r14`) off the stack, so the bx instruction will
     jump to the correct return address. */
     "bx r14\n"
+#elif defined(__s390x__)
+    /* Above, we popped the return address (r14) off the stack. */
+    "br %r14\n"
 #endif
 
 #else
diff --git a/src/arch/runtime/coroutines.hpp b/src/arch/runtime/coroutines.hpp
index c34a6630f7..67eac07e25 100644
--- a/src/arch/runtime/coroutines.hpp
+++ b/src/arch/runtime/coroutines.hpp
@@ -17,7 +17,7 @@
 // Enable cross-coroutine backtraces in debug mode, or when coro profiling is enabled.
 // We don't enable it on ARM, because taking backtraces currently isn't working
 // reliably and sometimes causes crashes.
-#if (!defined(NDEBUG) && !defined(__MACH__) && !defined(__arm__)) \
+#if (!defined(NDEBUG) && !defined(__MACH__) && !defined(__arm__)) && !defined(__s390x__) \
     || defined(ENABLE_CORO_PROFILER)
 #define CROSS_CORO_BACKTRACES            1
 #endif
diff --git a/src/client_protocol/json.cc b/src/client_protocol/json.cc
index 07080ad927..72551bd74b 100644
--- a/src/client_protocol/json.cc
+++ b/src/client_protocol/json.cc
@@ -55,6 +55,11 @@ scoped_ptr_t<ql::query_params_t> json_protocol_t::parse_query(
     conn->read_buffered(&size, sizeof(size), interruptor);
     ql::response_t error;
 
+#ifdef __s390x__
+    token = __builtin_bswap64(token);
+    size = __builtin_bswap32(size);
+#endif
+
     if (size >= wire_protocol_t::TOO_LARGE_QUERY_SIZE) {
         error.fill_error(Response::CLIENT_ERROR,
                          Response::RESOURCE_LIMIT,
@@ -226,11 +231,17 @@ void json_protocol_t::send_response(ql::response_t *response,
 
     // Fill in the token and size
     char *mutable_buffer = buffer.GetMutableBuffer();
+#ifdef __s390x__
+    token = __builtin_bswap64(token);
+#endif
     for (size_t i = 0; i < sizeof(token); ++i) {
         mutable_buffer[i] = reinterpret_cast<const char *>(&token)[i];
     }
 
     data_size = static_cast<uint32_t>(payload_size);
+#ifdef __s390x__
+    data_size = __builtin_bswap32(data_size);
+#endif
     for (size_t i = 0; i < sizeof(data_size); ++i) {
         mutable_buffer[i + sizeof(token)] =
             reinterpret_cast<const char *>(&data_size)[i];
diff --git a/src/client_protocol/server.cc b/src/client_protocol/server.cc
index 188e11f3ac..265eddcd21 100644
--- a/src/client_protocol/server.cc
+++ b/src/client_protocol/server.cc
@@ -280,7 +280,9 @@ void query_server_t::handle_conn(const scoped_ptr_t<tcp_conn_descriptor_t> &ncon
         int32_t client_magic_number;
         conn->read_buffered(
             &client_magic_number, sizeof(client_magic_number), &ct_keepalive);
-
+#ifdef __s390x__
+        client_magic_number = __builtin_bswap32(client_magic_number);
+#endif
         switch (client_magic_number) {
             case VersionDummy::V0_1:
                 version = 1;
@@ -315,6 +317,9 @@ void query_server_t::handle_conn(const scoped_ptr_t<tcp_conn_descriptor_t> &ncon
 
             uint32_t auth_key_size;
             conn->read_buffered(&auth_key_size, sizeof(uint32_t), &ct_keepalive);
+#ifdef __s390x__
+            auth_key_size = __builtin_bswap32(auth_key_size);
+#endif
             if (auth_key_size > 2048) {
                 throw client_protocol::client_server_error_t(
                     -1, "Client provided an authorization key that is too long.");
@@ -334,6 +339,9 @@ void query_server_t::handle_conn(const scoped_ptr_t<tcp_conn_descriptor_t> &ncon
 
             int32_t wire_protocol;
             conn->read_buffered(&wire_protocol, sizeof(wire_protocol), &ct_keepalive);
+#ifdef __s390x__
+            wire_protocol = __builtin_bswap32(wire_protocol);
+#endif
             switch (wire_protocol) {
                 case VersionDummy::JSON:
                     break;
@@ -664,6 +672,9 @@ void query_server_t::handle(const http_req_t &req,
     // Parse the token out from the start of the request
     char *data = body_buf.data();
     token = *reinterpret_cast<const int64_t *>(data);
+#ifdef __s390x__
+    token = __builtin_bswap64(token);
+#endif
     data += sizeof(token);
 
     ql::response_t response;
@@ -740,6 +751,10 @@ void query_server_t::handle(const http_req_t &req,
     json_protocol_t::write_response_to_buffer(&response, &buffer);
 
     uint32_t size = static_cast<uint32_t>(buffer.GetSize());
+#ifdef __s390x__
+    size = __builtin_bswap32(size);
+    token = __builtin_bswap64(token);
+#endif
     char header_buffer[sizeof(token) + sizeof(size)];
     memcpy(&header_buffer[0], &token, sizeof(token));
     memcpy(&header_buffer[sizeof(token)], &size, sizeof(size));
diff --git a/src/rdb_protocol/datum.cc b/src/rdb_protocol/datum.cc
index 7fbd7aa04e..a218402397 100644
--- a/src/rdb_protocol/datum.cc
+++ b/src/rdb_protocol/datum.cc
@@ -1118,7 +1118,9 @@ std::string datum_t::mangle_secondary(
 std::string datum_t::encode_tag_num(uint64_t tag_num) {
     static_assert(sizeof(tag_num) == tag_size,
             "tag_size constant is assumed to be the size of a uint64_t.");
-#ifndef BOOST_LITTLE_ENDIAN
+#if defined(__s390x__)
+    tag_num = __builtin_bswap64(tag_num);
+#elif !defined(BOOST_LITTLE_ENDIAN)
     static_assert(false, "This piece of code will break on big-endian systems.");
 #endif
     return std::string(reinterpret_cast<const char *>(&tag_num), tag_size);
@@ -1244,10 +1246,13 @@ components_t parse_secondary(const std::string &key) THROWS_NOTHING {
     std::string tag_str = key.substr(start_of_tag, key.size() - (start_of_tag + 2));
     boost::optional<uint64_t> tag_num;
     if (tag_str.size() != 0) {
-#ifndef BOOST_LITTLE_ENDIAN
+        uint64_t t = *reinterpret_cast<const uint64_t *>(tag_str.data());
+#if defined(__s390x__)
+        t = __builtin_bswap64(t);
+#elif !defined(BOOST_LITTLE_ENDIAN)
         static_assert(false, "This piece of code will break on little endian systems.");
 #endif
-        tag_num = *reinterpret_cast<const uint64_t *>(tag_str.data());
+        tag_num = t;
     }
     return components_t{
         skey_version,
diff --git a/src/rpc/connectivity/cluster.cc b/src/rpc/connectivity/cluster.cc
index b43f7abcc7..f90780630c 100644
--- a/src/rpc/connectivity/cluster.cc
+++ b/src/rpc/connectivity/cluster.cc
@@ -103,7 +103,7 @@ static bool resolve_protocol_version(const std::string &remote_version_string,
     return false;
 }
 
-#if defined (__x86_64__) || defined (_WIN64)
+#if defined (__x86_64__) || defined (_WIN64) || defined (__s390x__)
 const std::string connectivity_cluster_t::cluster_arch_bitsize("64bit");
 #elif defined (__i386__) || defined(__arm__)
 const std::string connectivity_cluster_t::cluster_arch_bitsize("32bit");
diff --git a/src/unittest/print_secondary.cc b/src/unittest/print_secondary.cc
index 9557aa0ecf..d1f2fed876 100644
--- a/src/unittest/print_secondary.cc
+++ b/src/unittest/print_secondary.cc
@@ -1,13 +1,14 @@
 // Copyright 2010-2013 RethinkDB, all rights reserved.
 #include "unittest/gtest.hpp"
+#include "unittest/unittest_utils.hpp"
 #include "rdb_protocol/datum.hpp"
 
 namespace unittest {
 void test_mangle(const std::string &pkey, const std::string &skey, boost::optional<uint64_t> tag = boost::optional<uint64_t>()) {
     std::string tag_string;
     if (tag) {
-        tag_string = std::string(reinterpret_cast<const char *>(&*tag),
-                                 sizeof(uint64_t));
+        // Encode tag in little endian.
+        tag_string = encode_le64(*tag);
     }
     auto versions = {
         reql_version_t::v1_16,
diff --git a/src/unittest/rdb_interruptor.cc b/src/unittest/rdb_interruptor.cc
index fba8a6c659..8dda5adf87 100644
--- a/src/unittest/rdb_interruptor.cc
+++ b/src/unittest/rdb_interruptor.cc
@@ -309,9 +309,19 @@ const std::string stop_json(strprintf("[%" PRIi32 "]",
                                       Query::STOP));
 const std::string invalid_json("]");
 
-template <class T>
-void append_to_message(const T& item, std::string *message) {
-    message->append(reinterpret_cast<const char *>(&item), sizeof(item));
+template <class Integral>
+void append_to_message(Integral item, std::string *message) {
+    const size_t size = sizeof(Integral);
+    static_assert(std::is_integral<Integral>::value, "item must be an integral");
+    static_assert(size == 4 || size == 8, "item size must be 4 or 8 bytes");
+    switch (size) {
+    case 4:
+        message->append(encode_le32(item));
+        break;
+    case 8:
+        message->append(encode_le64(item));
+        break;
+    }
 }
 
 void append_to_message(const std::string &item, std::string *message) {
@@ -392,15 +402,18 @@ std::string get_query_response(tcp_conn_stream_t *conn) {
     int64_t res;
     int64_t token;
     uint32_t response_size;
-    res = conn->read(&token, sizeof(token));
+    char buf[8];
+    res = conn->read(buf, sizeof(token));
     if (res == 0) {
         return std::string();
     }
     guarantee(res == sizeof(token));
+    token = decode_le64(std::string(buf, 8));
     guarantee(token == unparsable_query_token || token == test_token);
 
-    res = conn->read(&response_size, sizeof(response_size));
+    res = conn->read(buf, sizeof(response_size));
     guarantee(res == sizeof(response_size));
+    response_size = decode_le32(std::string(buf, 4));
 
     scoped_array_t<char> response_data(response_size + 1);
     res = conn->read(response_data.data(), response_size);
@@ -515,10 +528,10 @@ std::string parse_http_result(const http_res_t &http_res, int32_t expected_type)
     guarantee(http_res.body.size() > sizeof(int64_t) + sizeof(uint32_t));
     const char *data = http_res.body.data();
 
-    int64_t token = *reinterpret_cast<const int64_t *>(data);
+    int64_t token = decode_le64(std::string(data, 8));
     data += sizeof(token);
 
-    uint32_t data_size = *reinterpret_cast<const uint32_t *>(data);
+    uint32_t data_size = decode_le32(std::string(data, 4));
     data += sizeof(data_size);
 
     return parse_json_error_message(data, expected_type);
diff --git a/src/unittest/unittest_utils.cc b/src/unittest/unittest_utils.cc
index c6fa90b35b..ef30c575f8 100644
--- a/src/unittest/unittest_utils.cc
+++ b/src/unittest/unittest_utils.cc
@@ -205,4 +205,50 @@ std::string random_letter_string(rng_t *rng, int min_length, int max_length) {
     return ret;
 }
 
+// Zero extend the given byte to 64-bits.
+uint64_t zero_extend(char x) {
+	return static_cast<uint64_t>(static_cast<uint8_t>(x));
+}
+
+uint64_t decode_le64(const std::string& buf) {
+	return zero_extend(buf[0]) |
+		zero_extend(buf[1]) << 8 |
+		zero_extend(buf[2]) << 16 |
+		zero_extend(buf[3]) << 24 |
+		zero_extend(buf[4]) << 32 |
+		zero_extend(buf[5]) << 40 |
+		zero_extend(buf[6]) << 48 |
+		zero_extend(buf[7]) << 56;
+}
+
+uint32_t decode_le32(const std::string& buf) {
+	return static_cast<uint32_t>(
+		zero_extend(buf[0]) |
+		zero_extend(buf[1]) << 8 |
+		zero_extend(buf[2]) << 16 |
+		zero_extend(buf[3]) << 32);
+}
+
+std::string encode_le64(uint64_t x) {
+	char buf[8];
+	buf[0] = x;
+	buf[1] = x >> 8;
+	buf[2] = x >> 16;
+	buf[3] = x >> 24;
+	buf[4] = x >> 32;
+	buf[5] = x >> 40;
+	buf[6] = x >> 48;
+	buf[7] = x >> 56;
+	return std::string(&buf[0], 8);
+}
+
+std::string encode_le32(uint32_t x) {
+	char buf[4];
+	buf[0] = x;
+	buf[1] = x >> 8;
+	buf[2] = x >> 16;
+	buf[3] = x >> 24;
+	return std::string(&buf[0], 4);
+}
+
 }  // namespace unittest
diff --git a/src/unittest/unittest_utils.hpp b/src/unittest/unittest_utils.hpp
index 5a3d11145a..fad683fdae 100644
--- a/src/unittest/unittest_utils.hpp
+++ b/src/unittest/unittest_utils.hpp
@@ -64,6 +64,18 @@ state_timestamp_t make_state_timestamp(int n);
 
 std::string random_letter_string(rng_t *rng, int min_length, int max_length);
 
+// Read an 8-byte little-endian encoded integer from the given string.
+uint64_t decode_le64(const std::string& buf);
+
+// Read a 4-byte little-endian encoded integer from the given string.
+uint32_t decode_le32(const std::string& buf);
+
+// Write an 8-byte integer to a string in little-endian byte order.
+std::string encode_le64(uint64_t x);
+
+// Write a 4-byte integer to a string in little-endian byte order.
+std::string encode_le32(uint32_t x);
+
 }  // namespace unittest
 
 
diff --git a/src/unittest/utils_test.cc b/src/unittest/utils_test.cc
index bfed8d33d4..654d8feb45 100644
--- a/src/unittest/utils_test.cc
+++ b/src/unittest/utils_test.cc
@@ -68,7 +68,7 @@ TEST(UtilsTest, TimeLocal) {
     _putenv("TZ=UTC+7"); // TODO WINDOWS: this seems wrong, but causes the test to pass
     _tzset();
 #else
-    setenv("TZ", "America/Los_Angeles", 1);
+    setenv("TZ", "PST8PDT", 1);
     tzset();
 #endif