code:
By default 'mutt' embeds configure flags and the output of 'gcc -v',
which contains the store file name of Bash and GCC.  This patch makes
sure we don't embed a reference to these in 'mutt'.

--- mutt-1.5.23/txt2c.sh	2015-06-26 22:56:56.500731643 +0200
+++ mutt-1.5.23/txt2c.sh	2015-06-26 22:57:26.664583900 +0200
@@ -21,6 +21,8 @@ txt2c_fallback () {
 	echo ";"
 }

+echo "unsigned char $1[] = \"value of '$1' not kept\";"
+exit 0
 ./txt2c test </dev/null >/dev/null 2>&1 &&
 ./txt2c "$1" ||
 txt2c_fallback "$1"


code:
http://source.myrepos.branchable.com/?p=source.git;a=patch;h=40a3df21c73f1bb1b6915cc6fa503f50814664c8
This can be removed with the next release. It was modified slightly to apply

From 40a3df21c73f1bb1b6915cc6fa503f50814664c8 Mon Sep 17 00:00:00 2001
From: Paul Wise <pabs3@bonedaddy.net>
Date: Sun, 11 Feb 2018 21:57:49 +0800
Subject: [PATCH] Mitigate vulnerabilities caused by some git remotes being
 able to execute code

Set GIT_PROTOCOL_FROM_USER=0 with git versions newer than 2.12.

Prevent remote websites from causing cloning of local repositories.

Manually whitelist known-safe protocols (http, https, git, ssh)
when using git versions older than 2.12.

Fixes: CVE-2018-7032
Fixes: https://bugs.debian.org/840014
Suggestions-by: Jakub Wilk <jwilk@jwilk.net>
Reported-by: Jakub Wilk <jwilk@jwilk.net>
---
 webcheckout | 22 +++++++++++++++++++++-
 1 file changed, 21 insertions(+), 1 deletion(-)

diff --git a/webcheckout b/webcheckout
index e98da5c..de497ba 100755
--- a/webcheckout
+++ b/webcheckout
@@ -71,6 +71,16 @@ use Getopt::Long;
 use warnings;
 use strict;

+# Mitigate some git remote types being dangerous
+my $git_unsafe = 1;
+my $git_version = `git --version`;
+$git_version =~ s{^git version }{};
+my ($major, $minor) = split(/\./, $git_version);
+if (int($major) >= 2 && int($minor) >= 12) {
+	$ENV{GIT_PROTOCOL_FROM_USER} = 0;
+	$git_unsafe = 0;
+}
+
 # What to download.
 my $url;

@@ -89,7 +99,17 @@ my $destdir;

 # how to perform checkouts
 my %handlers=(
-	git => sub { doit("git", "clone", shift, $destdir) },
-	svn => sub { doit("svn", "checkout", shift, $destdir) },
-	bzr => sub { doit("bzr", "branch", shift, $destdir) },
+	git => sub {
+		my $git_url = shift;
+		# Reject unsafe URLs with older versions of git
+		# that do not already check the URL safety.
+		if ($git_unsafe && $git_url !~ m{^(?:(?:https?|git|ssh):[^:]|(?:[-_.A-Za-z0-9]+@)?[-_.A-Za-z0-9]+:(?!:|//))}) {
+			print STDERR "potentially unsafe git URL, may fail, touch local files or execute arbitrary code\n";
+			return 1;
+		}
+		# Reject cloning local directories too, webcheckout is for remote repos
+		doit(qw(git -c protocol.file.allow=user clone --), $git_url, $destdir)
+	},
+	svn => sub { doit(qw(svn checkout --), shift, $destdir) },
+	bzr => sub { doit(qw(bzr branch --), shift, $destdir) },
 );
--
2.11.0

license: mit


code:
Starting with libc 2.20, this file would fail to build with "NULL undeclared".
Include the fine header to solve that.

--- net-tools-1.60/lib/ec_hw.c	1999-11-20 22:02:53.000000000 +0100
+++ net-tools-1.60/lib/ec_hw.c	2014-10-06 22:48:43.811027768 +0200
@@ -16,6 +16,7 @@

 #if HAVE_HWEC

+#include <stddef.h>
 #include <net/if_arp.h>
 #include "net-support.h"

Avoid "label at end of compound statement" errors.

--- net-tools-1.60/lib/inet_sr.c	2000-02-20 22:46:45.000000000 +0100
+++ net-tools-1.60/lib/inet_sr.c	2014-10-06 22:51:22.575023126 +0200
@@ -104,7 +104,6 @@ static int INET_setroute(int action, int
        isnet = 1; break;
     case 2:
        isnet = 0; break;
-    default:
     }

     /* Fill in the other fields. */

--- net-tools-1.60/hostname.c	2001-04-08 19:04:23.000000000 +0200
+++ net-tools-1.60/hostname.c	2014-10-06 23:01:04.235006119 +0200
@@ -77,7 +77,6 @@ static void setnname(char *nname)
         case EINVAL:
             fprintf(stderr, _("%s: name too long\n"), program_name);
             break;
-        default:
         }
 	exit(1);
     }
@@ -97,7 +96,6 @@ static void sethname(char *hname)
 	case EINVAL:
 	    fprintf(stderr, _("%s: name too long\n"), program_name);
 	    break;
-	default:
 	}
 	exit(1);
     };
@@ -116,7 +114,6 @@ static void setdname(char *dname)
 	case EINVAL:
 	    fprintf(stderr, _("%s: name too long\n"), program_name);
 	    break;
-	default:
 	}
 	exit(1);
     };
@@ -173,7 +170,6 @@ static void showhname(char *hname, int c
 	    *p = '\0';
 	printf("%s\n", hp->h_name);
 	break;
-    default:
     }
 }

Work around the assumption that an 'x25_address' typedef exists.

--- net-tools-1.60/lib/x25_sr.c	2000-05-20 15:38:10.000000000 +0200
+++ net-tools-1.60/lib/x25_sr.c	2014-10-06 22:59:35.787008705 +0200
@@ -77,7 +77,7 @@ static int X25_setroute(int action, int
   rt.sigdigits=sigdigits;

   /* x25_route_struct.address isn't type struct sockaddr_x25, Why? */
-  memcpy(&rt.address, &sx25.sx25_addr, sizeof(x25_address));
+  memcpy(&rt.address, &sx25.sx25_addr, sizeof(struct x25_address));

   while (*args) {
 	if (!strcmp(*args,"device") || !strcmp(*args,"dev")) {

Fix the multi-line string literal syntax.

--- net-tools-1.60/mii-tool.c	2000-05-21 16:31:17.000000000 +0200
+++ net-tools-1.60/mii-tool.c	2014-10-06 23:07:42.002994489 +0200
@@ -379,16 +379,16 @@ static void watch_one_xcvr(int skfd, cha
 /*--------------------------------------------------------------------*/

 const char *usage =
-"usage: %s [-VvRrwl] [-A media,... | -F media] [interface ...]
-       -V, --version               display version information
-       -v, --verbose               more verbose output
-       -R, --reset                 reset MII to poweron state
-       -r, --restart               restart autonegotiation
-       -w, --watch                 monitor for link status changes
-       -l, --log                   with -w, write events to syslog
-       -A, --advertise=media,...   advertise only specified media
-       -F, --force=media           force specified media technology
-media: 100baseT4, 100baseTx-FD, 100baseTx-HD, 10baseT-FD, 10baseT-HD,
+"usage: %s [-VvRrwl] [-A media,... | -F media] [interface ...]\n\
+       -V, --version               display version information\n\
+       -v, --verbose               more verbose output\n\
+       -R, --reset                 reset MII to poweron state\n\
+       -r, --restart               restart autonegotiation\n\
+       -w, --watch                 monitor for link status changes\n\
+       -l, --log                   with -w, write events to syslog\n\
+       -A, --advertise=media,...   advertise only specified media\n\
+       -F, --force=media           force specified media technology\n\
+media: 100baseT4, 100baseTx-FD, 100baseTx-HD, 10baseT-FD, 10baseT-HD,\n\
        (to advertise both HD and FD) 100baseTx, 10baseT\n";

 int main(int argc, char **argv)


code:
--- a/libdispatch/derror.c
+++ b/libdispatch/derror.c
@@ -13,7 +13,7 @@
 #endif

 /* Tell the user the version of netCDF. */
-static const char nc_libvers[] = PACKAGE_VERSION " of "__DATE__" "__TIME__" $";
+static const char nc_libvers[] = PACKAGE_VERSION" $";

 /**
 \defgroup lib_version Library Version


code:
From a83702834938b23cc2e843589aa223e2024a7e6f Mon Sep 17 00:00:00 2001
From: Orion Poplawski <orion@cora.nwra.com>
Date: Tue, 29 Nov 2016 11:48:01 -0700
Subject: [PATCH] Add missing #include "err_macros.h" to tst_h_par.c

---
 h5_test/tst_h_par.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/h5_test/tst_h_par.c b/h5_test/tst_h_par.c
index c3da7f4..a419d55 100644
--- a/h5_test/tst_h_par.c
+++ b/h5_test/tst_h_par.c
@@ -11,6 +11,7 @@
    $Id: tst_h_par.c,v 1.15 2010/05/25 13:53:04 ed Exp $
 */
 #include <nc_tests.h>
+#include "err_macros.h"
 #include <hdf5.h>

 /* Defining USE_MPE causes the MPE trace library to be used (and you


code:
Increase the timeout on dictionary tests to accommodate slower machines.

--- netsurf-3.6/test/hashtable.c
+++ netsurf-3.6/test/hashtable.c
@@ -286,6 +286,7 @@
 	tcase_add_checked_fixture(tc_dict_s,
 				  dicts_hashtable_create,
 				  dict_hashtable_teardown);
+	tcase_set_timeout(tc_dict_s, 30);

 	tcase_add_test(tc_dict_s, hashtable_dict_test);

@@ -297,6 +298,7 @@
 	tcase_add_checked_fixture(tc_dict_l,
 				  dictl_hashtable_create,
 				  dict_hashtable_teardown);
+	tcase_set_timeout(tc_dict_l, 30);

 	tcase_add_test(tc_dict_l, hashtable_dict_test);


code:
Use upstream utf8proc package, as suggested in
http://source.netsurf-browser.org/libutf8proc.git/commit/?id=770e329cceaf0620c7b482589a9b17ed1d19c16d

Work around upstream's lack of a pkg-config file and update API.

--- netsurf-3.6/Makefile
+++ netsurf-3.6/Makefile
@@ -527,10 +527,9 @@
 $(eval $(call pkg_config_find_and_add,libcss,CSS))
 $(eval $(call pkg_config_find_and_add,libdom,DOM))
 $(eval $(call pkg_config_find_and_add,libnsutils,nsutils))
-$(eval $(call pkg_config_find_and_add,libutf8proc,utf8proc))

 # Common libraries without pkg-config support
-LDFLAGS += -lz
+LDFLAGS += -lz -lutf8proc

 # Optional libraries with pkgconfig

--- netsurf-3.8/utils/idna.c
+++ netsurf-3.8/utils/idna.c
@@ -27,7 +27,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <sys/types.h>
-#include <libutf8proc/utf8proc.h>
+#include <utf8proc.h>

 #include "netsurf/inttypes.h"

--- netsurf-3.8/test/Makefile
+++ netsurf-3.8/test/Makefile
@@ -142,14 +142,15 @@
 	-Itest -Iinclude -Icontent/handlers -Ifrontends -I. -I.. \
 	-Dnsgtk \
 	$(SAN_FLAGS) \
-	$(shell pkg-config --cflags libcurl libparserutils libwapcaplet libdom libnsutils libutf8proc) \
+	$(shell pkg-config --cflags libcurl libparserutils libwapcaplet libdom libnsutils) \
 	$(LIB_CFLAGS)
 TESTCFLAGS := $(BASE_TESTCFLAGS) \
 	$(COV_CFLAGS) \
 	$(COV_CPPFLAGS)

 TESTLDFLAGS := -L$(TESTROOT) \
-	$(shell pkg-config --libs libcurl libparserutils libwapcaplet libdom libnsutils libutf8proc) -lz \
+	$(shell pkg-config --libs libcurl libparserutils libwapcaplet libdom libnsutils) \
+	$(LDFLAGS) \
 	$(SAN_FLAGS) \
 	$(LIB_LDFLAGS)\
 	$(COV_LDFLAGS)


code:
Fix compilation failure with glibc 2.26 caused by missing type
declarations:

------
rpc.c: In function ‘nsm_recv_getport’:
rpc.c:469:13: error: ‘UINT16_MAX’ undeclared (first use in this function)
  if (port > UINT16_MAX) {
------

--- a/support/nsm/rpc.c.orig	2016-08-03 20:25:15.000000000 +0200
+++ b/support/nsm/rpc.c	2017-08-26 07:41:11.884000000 +0200
@@ -40,6 +40,7 @@

 #include <time.h>
 #include <stdbool.h>
+#include <stdint.h>
 #include <string.h>
 #include <unistd.h>
 #include <fcntl.h>


code:
The Guile process taking the role of PID 1 during Guix builds does not reap
zombie processes, which makes them continue responding to "kill -0".

--- a/src/testsuite/stop-server.sh	2015-02-05 11:24:00.535908842 +0100
+++ b/src/testsuite/stop-server.sh	2015-02-05 11:25:00.264351349 +0100
@@ -1,6 +1,21 @@
 #!/bin/sh
 # ngIRCd Test Suite

+process_is_alive(){
+    ! process_is_dead "$1" && ! process_is_undead "$1"
+}
+
+process_is_dead(){
+    ! kill -0 "$1"
+}
+
+process_is_undead(){
+    case $(ps -p "$1" -o state=) in
+        (Z*) true ;;
+        (*) false ;;
+    esac
+}
+
 [ -z "$srcdir" ] && srcdir=`dirname $0`

 # read in functions
@@ -24,7 +40,7 @@

 # waiting ...
 for i in 1 2 3 4 5; do
-  kill -0 $pid > /dev/null 2>&1; r=$?
+  process_is_alive $pid > /dev/null 2>&1; r=$?
   if [ $r -ne 0 ]; then
     echo " ok".
     exit 0


code:
We've seen some tests take up to 60s to complete on a busy armhf
machine. Even a busy x86_64 machine can use more than 5s on some tests.

Increase timeouts to increase chances of a successful build.

--- a/nss/gtests/ssl_gtest/tls_connect.cc	2017-03-14 22:47:30.855813629 +0100
+++ b/nss/gtests/ssl_gtest/tls_connect.cc	2017-03-14 22:48:49.042335273 +0100
@@ -245,7 +245,7 @@

   ASSERT_TRUE_WAIT((client_->state() != TlsAgent::STATE_CONNECTING) &&
                        (server_->state() != TlsAgent::STATE_CONNECTING),
-                   5000);
+                   300000);
 }

 void TlsConnectTestBase::EnableExtendedMasterSecret() {
@@ -385,7 +385,7 @@
   if (failing_side == TlsAgent::CLIENT) {
     failing_agent = client_;
   }
-  ASSERT_TRUE_WAIT(failing_agent->state() == TlsAgent::STATE_ERROR, 5000);
+  ASSERT_TRUE_WAIT(failing_agent->state() == TlsAgent::STATE_ERROR, 300000);
 }

 void TlsConnectTestBase::ConfigureVersion(uint16_t version) {


code:
Description: Create nss.pc and nss-config
Author: Lars Wendler <polynomial-c@gentoo.org>
Source: http://sources.gentoo.org/cgi-bin/viewvc.cgi/gentoo-x86/dev-libs/nss/files/nss-3.17.1-gentoo-fixups.patch

Modifications:
  Change libdir from ${prefix}/lib64 to ${prefix}/lib/nss.
  Remove optional patching in nss/Makefile.
  Include -L$libdir in output from "nss-config --libs".

Later adapted to apply cleanly to nss-3.21.

--- nss-3.21/nss/config/Makefile
+++ nss-3.21/nss/config/Makefile
@@ -0,0 +1,40 @@
+CORE_DEPTH = ..
+DEPTH      = ..
+
+include $(CORE_DEPTH)/coreconf/config.mk
+
+NSS_MAJOR_VERSION = `grep "NSS_VMAJOR" ../lib/nss/nss.h | awk '{print $$3}'`
+NSS_MINOR_VERSION = `grep "NSS_VMINOR" ../lib/nss/nss.h | awk '{print $$3}'`
+NSS_PATCH_VERSION = `grep "NSS_VPATCH" ../lib/nss/nss.h | awk '{print $$3}'`
+PREFIX = /usr
+
+all: export libs
+
+export:
+	# Create the nss.pc file
+	mkdir -p $(DIST)/lib/pkgconfig
+	sed -e "s,@prefix@,$(PREFIX)," \
+	    -e "s,@exec_prefix@,\$${prefix}," \
+	    -e "s,@libdir@,\$${prefix}/lib/nss," \
+	    -e "s,@includedir@,\$${prefix}/include/nss," \
+	    -e "s,@NSS_MAJOR_VERSION@,$(NSS_MAJOR_VERSION),g" \
+	    -e "s,@NSS_MINOR_VERSION@,$(NSS_MINOR_VERSION)," \
+	    -e "s,@NSS_PATCH_VERSION@,$(NSS_PATCH_VERSION)," \
+	    nss.pc.in > nss.pc
+	chmod 0644 nss.pc
+	cp nss.pc $(DIST)/lib/pkgconfig
+
+	# Create the nss-config script
+	mkdir -p $(DIST)/bin
+	sed -e "s,@prefix@,$(PREFIX)," \
+	    -e "s,@NSS_MAJOR_VERSION@,$(NSS_MAJOR_VERSION)," \
+	    -e "s,@NSS_MINOR_VERSION@,$(NSS_MINOR_VERSION)," \
+	    -e "s,@NSS_PATCH_VERSION@,$(NSS_PATCH_VERSION)," \
+	    nss-config.in > nss-config
+	chmod 0755 nss-config
+	cp nss-config $(DIST)/bin
+
+libs:
+
+dummy: all export libs
+
--- nss-3.21/nss/config/nss-config.in
+++ nss-3.21/nss/config/nss-config.in
@@ -0,0 +1,145 @@
+#!/bin/sh
+
+prefix=@prefix@
+
+major_version=@NSS_MAJOR_VERSION@
+minor_version=@NSS_MINOR_VERSION@
+patch_version=@NSS_PATCH_VERSION@
+
+usage()
+{
+	cat <<EOF
+Usage: nss-config [OPTIONS] [LIBRARIES]
+Options:
+	[--prefix[=DIR]]
+	[--exec-prefix[=DIR]]
+	[--includedir[=DIR]]
+	[--libdir[=DIR]]
+	[--version]
+	[--libs]
+	[--cflags]
+Dynamic Libraries:
+	nss
+	ssl
+	smime
+	nssutil
+EOF
+	exit $1
+}
+
+if test $# -eq 0; then
+	usage 1 1>&2
+fi
+
+lib_ssl=yes
+lib_smime=yes
+lib_nss=yes
+lib_nssutil=yes
+
+while test $# -gt 0; do
+  case "$1" in
+  -*=*) optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
+  *) optarg= ;;
+  esac
+
+  case $1 in
+    --prefix=*)
+      prefix=$optarg
+      ;;
+    --prefix)
+      echo_prefix=yes
+      ;;
+    --exec-prefix=*)
+      exec_prefix=$optarg
+      ;;
+    --exec-prefix)
+      echo_exec_prefix=yes
+      ;;
+    --includedir=*)
+      includedir=$optarg
+      ;;
+    --includedir)
+      echo_includedir=yes
+      ;;
+    --libdir=*)
+      libdir=$optarg
+      ;;
+    --libdir)
+      echo_libdir=yes
+      ;;
+    --version)
+      echo ${major_version}.${minor_version}.${patch_version}
+      ;;
+    --cflags)
+      echo_cflags=yes
+      ;;
+    --libs)
+      echo_libs=yes
+      ;;
+    ssl)
+      lib_ssl=yes
+      ;;
+    smime)
+      lib_smime=yes
+      ;;
+    nss)
+      lib_nss=yes
+      ;;
+    nssutil)
+      lib_nssutil=yes
+      ;;
+    *)
+      usage 1 1>&2
+      ;;
+  esac
+  shift
+done
+
+# Set variables that may be dependent upon other variables
+if test -z "$exec_prefix"; then
+    exec_prefix=`pkg-config --variable=exec_prefix nss`
+fi
+if test -z "$includedir"; then
+    includedir=`pkg-config --variable=includedir nss`
+fi
+if test -z "$libdir"; then
+    libdir=`pkg-config --variable=libdir nss`
+fi
+
+if test "$echo_prefix" = "yes"; then
+    echo $prefix
+fi
+
+if test "$echo_exec_prefix" = "yes"; then
+    echo $exec_prefix
+fi
+
+if test "$echo_includedir" = "yes"; then
+    echo $includedir
+fi
+
+if test "$echo_libdir" = "yes"; then
+    echo $libdir
+fi
+
+if test "$echo_cflags" = "yes"; then
+    echo -I$includedir
+fi
+
+if test "$echo_libs" = "yes"; then
+      libdirs=-L$libdir
+      if test -n "$lib_ssl"; then
+	libdirs="$libdirs -lssl${major_version}"
+      fi
+      if test -n "$lib_smime"; then
+	libdirs="$libdirs -lsmime${major_version}"
+      fi
+      if test -n "$lib_nss"; then
+	libdirs="$libdirs -lnss${major_version}"
+      fi
+      if test -n "$lib_nssutil"; then
+       libdirs="$libdirs -lnssutil${major_version}"
+      fi
+      echo $libdirs
+fi
+
--- nss-3.21/nss/config/nss.pc.in
+++ nss-3.21/nss/config/nss.pc.in
@@ -0,0 +1,12 @@
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: NSS
+Description: Network Security Services
+Version: @NSS_MAJOR_VERSION@.@NSS_MINOR_VERSION@.@NSS_PATCH_VERSION@
+Requires: nspr >= 4.8
+Libs: -L${libdir} -lssl3 -lsmime3 -lnss3 -lnssutil3
+Cflags: -I${includedir}
+
--- nss-3.21/nss/manifest.mn
+++ nss-3.21/nss/manifest.mn
@@ -10,4 +10,4 @@

 RELEASE = nss

-DIRS = coreconf lib cmd cpputil gtests
+DIRS = coreconf lib cmd cpputil gtests config


code:
Make configure assume nvi can store backups in /var/tmp.

--- a/dist/configure	2014-09-01 14:46:01.075778095 +0200
+++ b/dist/configure	2014-09-01 14:52:08.411790122 +0200
@@ -21319,23 +21319,8 @@
 if test "${vi_cv_path_preserve+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  	dirlist="/var/preserve /var/tmp /usr/tmp"
-	vi_cv_path_preserve=no
-	for i in $dirlist; do
-		if test -d $i/vi.recover; then
-			vi_cv_path_preserve=$i/vi.recover
-			break;
-		fi
-	done
-	if test "$vi_cv_path_preserve" = no; then
-		for i in $dirlist; do
-			if test -d $i -a -w $i; then
-				vi_cv_path_preserve=$i/vi.recover
-				break;
-			fi
-		done
-
-	fi
+#	Assume /var/tmp
+	vi_cv_path_preserve=/var/tmp/vi.recover
 fi

 if test "$vi_cv_path_preserve" = no; then


code:
This patch originates from the Debian project, see https://www.debian.org/

03db4.dpatch  by  <hesso@pool.math.tu-berlin.de>

libdb4 compatibility adjustments.

In particular, this patch adds extra file permission checking and passes the
DB_CREATE flag to the first invocation of db_open on the file's database
structure, which rids us of the following message:

  BDB0635 DB_CREATE must be specified to create databases.

--- nvi-1.81.6.orig/common/msg.c	2009-02-26 14:26:58.350336128 +0100
+++ nvi-1.81.6/common/msg.c	2009-02-26 14:29:05.235335829 +0100
@@ -724,9 +724,18 @@
 		p = buf;
 	} else
 		p = file;
+	if (access(p, F_OK) != 0) {
+		if (first) {
+			first = 0;
+			return (1);
+		}
+		sp->db_error = ENOENT;
+		msgq_str(sp, M_DBERR, p, "%s");
+		return (1);
+	}
 	if ((sp->db_error = db_create(&db, 0, 0)) != 0 ||
 	    (sp->db_error = db->set_re_source(db, p)) != 0 ||
-	    (sp->db_error = db_open(db, NULL, DB_RECNO, 0, 0)) != 0) {
+	    (sp->db_error = db_open(db, NULL, DB_RECNO, DB_CREATE, 0)) != 0) {
 		if (first) {
 			first = 0;
 			return (1);


code:
This patch originates from the Debian project, see https://www.debian.org/

18dbpagesize_binpower.dpatch by  <hesso@pool.math.tu-berlin.de>

Make sure that the pagesize passed to db__set_pagesize() is a power of two.

nvi stores the content of files in BDB database structures. When initiating a
file, it picks a page size for the database to fit the file within 15 pages,
with a minimal page size of 1K and maximal of 10K.

In vanilla nvi, this size is calculated as a multiple of 1024. Modern versions
of BDB, however, require the page size of a database to be a power of two, which
this patch addresses, ridding us of the following message:

  BDB0511 page sizes must be a power-of-2

--- nvi-1.81.6.orig/common/exf.c	2009-03-09 01:48:01.695862889 +0100
+++ nvi-1.81.6/common/exf.c	2009-03-09 10:42:41.147866272 +0100
@@ -249,11 +249,10 @@
 		 * (vi should have good locality) or smaller than 1K.
 		 */
 		psize = ((sb.st_size / 15) + 1023) / 1024;
-		if (psize > 10)
-			psize = 10;
-		if (psize == 0)
-			psize = 1;
-		psize *= 1024;
+		if (psize >= 8) psize=8<<10;
+		else if (psize >= 4) psize=4<<10;
+		else if (psize >= 2) psize=2<<10;
+		else psize=1<<10;

 		F_SET(ep, F_DEVSET);
 		ep->mdev = sb.st_dev;


code:
From 6a08014b77bf435f025ecdac08396580b85f159a Mon Sep 17 00:00:00 2001
From: Jan Nieuwenhuizen <janneke@gnu.org>
Date: Sat, 8 Sep 2018 20:22:45 +0200
Subject: [PATCH] fix binary literals.

---
 module/nyacc/lex.scm | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/module/nyacc/lex.scm b/module/nyacc/lex.scm
index 2ec9895..b205212 100644
--- a/module/nyacc/lex.scm
+++ b/module/nyacc/lex.scm
@@ -345,10 +345,11 @@
 	  ((char-numeric? ch) (iter chl '$fixed ba 1 ch))
 	  ((char=? #\. ch) (iter (cons ch chl) #f ba 15 (read-char)))
 	  (else #f)))
-	((10) ;; allow x after 0
+	((10) ;; allow x, b after 0
 	 (cond
 	  ((eof-object? ch) (iter chl ty ba 5 ch))
 	  ((char=? #\x ch) (iter (cons ch chl) ty 16 1 (read-char)))
+          ((char=? #\b ch) (iter (cons ch chl) ty 2 1 (read-char)))
 	  (else (iter chl ty ba 1 ch))))
 	((15) ;; got `.' only
 	 (cond
--
2.18.0


code:
From: Tobias Geerinckx-Rice <me@tobias.gr>
Date: Fri, 22 Jun 2018 02:56:39 +0200
Subject: nyx: Show header stats.

The following patch was taken verbatim from the upstream repository and
will be included in the next release.
---
commit 3494111cc81ad4985e81d0c1ea5e451d8f7a2bcc
Author: Damian Johnson <atagar@torproject.org>
Date:   Mon Feb 5 20:07:40 2018 -0800

    Header stats missing with python3

    Ick! took me a while to find this. Python3 changed division from providing ints
    to floats. This in turn caused our header panel to call addstr with float x/y
    coordinates, which made that funciton fail silently. End result is that when
    the header panel showed two columns of stats the right column was missing.

    Caught thanks to Stijn.

diff --git a/nyx/panel/header.py b/nyx/panel/header.py
index 09e3838..fb6f2f7 100644
--- a/nyx/panel/header.py
+++ b/nyx/panel/header.py
@@ -155,7 +155,7 @@ class HeaderPanel(nyx.panel.DaemonPanel):
     # space available for content

     interface = nyx_interface()
-    left_width = max(subwindow.width / 2, 77) if is_wide else subwindow.width
+    left_width = max(subwindow.width // 2, 77) if is_wide else subwindow.width
     right_width = subwindow.width - left_width

     _draw_platform_section(subwindow, 0, 0, left_width, vals)
diff --git a/web/changelog/index.html b/web/changelog/index.html
index 333fa84..196d82b 100644
--- a/web/changelog/index.html
+++ b/web/changelog/index.html
@@ -74,6 +74,12 @@

+
Header
+

+
Right column of stats missing when using python 3.x

+

+

+

Connections

Geoip information unavailable for inbound connections

diff --git a/web/changelog/legacy.html b/web/changelog/legacy.html
index a380806..02d405f 100644
--- a/web/changelog/legacy.html
+++ b/web/changelog/legacy.html
@@ -137,13 +137,13 @@

-
Startup
+
Graph

Crash when pausing if we showed accounting stats

-
Startup
+
Logging

Skip reading from malformed tor log files

Unable to log GUARD events


code:
From: Stephane Glondu <steph@glondu.net>
Date: Sun, 16 Aug 2015 20:59:14 +0200
Subject: Add a .file directive to generated .s files

When no .file directive is given, the toolchain records the filename
of the .o file, which is sometimes random, making generated objects
non-deterministic.

We use Location.input_name for adding .file directives to assembly
files. Note: when the file is preprocessed, this reference holds the
name of the temporary file. Hence, files compiled with -pp are still
not deterministic.

Bug-Debian: https://bugs.debian.org/795784
Bug-Debian: https://bugs.debian.org/796336
---
 asmcomp/amd64/emit.mlp | 1 +
 asmcomp/arm/emit.mlp   | 1 +
 asmcomp/arm64/emit.mlp | 1 +
 asmcomp/i386/emit.mlp  | 1 +
 asmcomp/power/emit.mlp | 1 +
 asmcomp/sparc/emit.mlp | 1 +
 6 files changed, 6 insertions(+)

diff --git a/asmcomp/amd64/emit.mlp b/asmcomp/amd64/emit.mlp
index d56d0f5..4d7aa30 100644
--- a/asmcomp/amd64/emit.mlp
+++ b/asmcomp/amd64/emit.mlp
@@ -794,6 +794,7 @@ let data l =
 let begin_assembly() =
   reset_debug_info();                   (* PR#5603 *)
   float_constants := [];
+  `	.file \"{emit_string (String.escaped !Location.input_name)}\"\n`;
   if !Clflags.dlcode then begin
     (* from amd64.S; could emit these constants on demand *)
     if macosx then
diff --git a/asmcomp/arm/emit.mlp b/asmcomp/arm/emit.mlp
index 4948fb2..6f30fba 100644
--- a/asmcomp/arm/emit.mlp
+++ b/asmcomp/arm/emit.mlp
@@ -892,6 +892,7 @@ let data l =

 let begin_assembly() =
   reset_debug_info();
+  `	.file \"{emit_string (String.escaped !Location.input_name)}\"\n`;
   `	.syntax	unified\n`;
   begin match !arch with
   | ARMv4   -> `	.arch	armv4t\n`
diff --git a/asmcomp/arm64/emit.mlp b/asmcomp/arm64/emit.mlp
index 750c2b2..5afbb8a 100644
--- a/asmcomp/arm64/emit.mlp
+++ b/asmcomp/arm64/emit.mlp
@@ -942,6 +942,7 @@ let data l =

 let begin_assembly() =
   reset_debug_info();
+  `	.file \"{emit_string (String.escaped !Location.input_name)}\"\n`;
   let lbl_begin = Compilenv.make_symbol (Some "data_begin") in
   `	.data\n`;
   `	.globl	{emit_symbol lbl_begin}\n`;
diff --git a/asmcomp/i386/emit.mlp b/asmcomp/i386/emit.mlp
index 98df5f9..531150f 100644
--- a/asmcomp/i386/emit.mlp
+++ b/asmcomp/i386/emit.mlp
@@ -986,6 +986,7 @@ let data l =
 let begin_assembly() =
   reset_debug_info();                   (* PR#5603 *)
   float_constants := [];
+  `	.file \"{emit_string (String.escaped !Location.input_name)}\"\n`;
   let lbl_begin = Compilenv.make_symbol (Some "data_begin") in
   `	.data\n`;
   `	.globl	{emit_symbol lbl_begin}\n`;
diff --git a/asmcomp/power/emit.mlp b/asmcomp/power/emit.mlp
index 4344085..343132b 100644
--- a/asmcomp/power/emit.mlp
+++ b/asmcomp/power/emit.mlp
@@ -887,6 +887,7 @@ let data l =
 let begin_assembly() =
   defined_functions := StringSet.empty;
   external_functions := StringSet.empty;
+  `	.file \"{emit_string (String.escaped !Location.input_name)}\"\n`;
   (* Emit the beginning of the segments *)
   let lbl_begin = Compilenv.make_symbol (Some "data_begin") in
   emit_string data_space;
diff --git a/asmcomp/sparc/emit.mlp b/asmcomp/sparc/emit.mlp
index 877a3d5..7b041e9 100644
--- a/asmcomp/sparc/emit.mlp
+++ b/asmcomp/sparc/emit.mlp
@@ -727,6 +727,7 @@ let data l =
 (* Beginning / end of an assembly file *)

 let begin_assembly() =
+  `	.file \"{emit_string (String.escaped !Location.input_name)}\"\n`;
   let lbl_begin = Compilenv.make_symbol (Some "data_begin") in
   `	.data\n`;
   `	.global	{emit_symbol lbl_begin}\n`;


code:
Adapted from upstream commit 659615c7b100a89eafe6253e7a5b9d84d0e8df74,
this patch omits the upstream changes to 'Changes' and 'VERSION'.

http://seclists.org/oss-sec/2016/q2/170
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-8869
https://github.com/ocaml/ocaml/commit/659615c7b100a89eafe6253e7a5b9d84d0e8df74
---
 byterun/alloc.c  | 4 ++--
 byterun/intern.c | 2 +-
 byterun/str.c    | 4 ++--
 3 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/byterun/alloc.c b/byterun/alloc.c
index 96a21bf..0db9947 100644
--- a/byterun/alloc.c
+++ b/byterun/alloc.c
@@ -153,7 +153,7 @@ CAMLexport int caml_convert_flag_list(value list, int *flags)
 /* [size] is a [value] representing number of words (fields) */
 CAMLprim value caml_alloc_dummy(value size)
 {
-  mlsize_t wosize = Int_val(size);
+  mlsize_t wosize = Long_val(size);

   if (wosize == 0) return Atom(0);
   return caml_alloc (wosize, 0);
@@ -169,7 +169,7 @@ CAMLprim value caml_alloc_dummy_function(value size,value arity)
 /* [size] is a [value] representing number of floats. */
 CAMLprim value caml_alloc_dummy_float (value size)
 {
-  mlsize_t wosize = Int_val(size) * Double_wosize;
+  mlsize_t wosize = Long_val(size) * Double_wosize;

   if (wosize == 0) return Atom(0);
   return caml_alloc (wosize, 0);
diff --git a/byterun/intern.c b/byterun/intern.c
index 89d13d1..7b8d049 100644
--- a/byterun/intern.c
+++ b/byterun/intern.c
@@ -291,7 +291,7 @@ static void intern_rec(value *dest)
   case OFreshOID:
     /* Refresh the object ID */
     /* but do not do it for predefined exception slots */
-    if (Int_val(Field((value)dest, 1)) >= 0)
+    if (Long_val(Field((value)dest, 1)) >= 0)
       caml_set_oo_id((value)dest);
     /* Pop item and iterate */
     sp--;
diff --git a/byterun/str.c b/byterun/str.c
index 5ad4e29..885772f 100644
--- a/byterun/str.c
+++ b/byterun/str.c
@@ -266,7 +266,7 @@ CAMLprim value caml_string_greaterequal(value s1, value s2)
 CAMLprim value caml_blit_string(value s1, value ofs1, value s2, value ofs2,
                                 value n)
 {
-  memmove(&Byte(s2, Long_val(ofs2)), &Byte(s1, Long_val(ofs1)), Int_val(n));
+  memmove(&Byte(s2, Long_val(ofs2)), &Byte(s1, Long_val(ofs1)), Long_val(n));
   return Val_unit;
 }

@@ -278,7 +278,7 @@ CAMLprim value caml_fill_string(value s, value offset, value len, value init)

 CAMLprim value caml_bitvect_test(value bv, value n)
 {
-  int pos = Int_val(n);
+  intnat pos = Long_val(n);
   return Val_int(Byte_u(bv, pos >> 3) & (1 << (pos & 7)));
 }

--
2.7.4


code:
From 26cac62fe0154cf65c06faaee10805531e9dade8 Mon Sep 17 00:00:00 2001
From: Julien Lepiller <julien@lepiller.eu>
Date: Wed, 14 Dec 2016 14:14:59 +0100
Subject: [PATCH] fix camlp4 in another directory

---
 Makefile        | 11 ++++++-----
 configure       | 13 ++++++++++++-
 myocamlbuild.ml |  2 +-
 3 files changed, 19 insertions(+), 7 deletions(-)

diff --git a/Makefile b/Makefile
index 4a8ce17..d94a6d5 100644
--- a/Makefile
+++ b/Makefile
@@ -25,7 +25,7 @@ PATH_BUILD=$(PATH_BASE)/_build
 PATH_OCAMLDOC=$(PATH_BASE)/ocamldoc
 PATH_SRC=$(PATH_BASE)/src
 PATH_TESTS=$(PATH_BASE)/tests
-PATH_INSTALL=$(PATH_OCAML_PREFIX)/lib/ocaml/bisect
+PATH_INSTALL=$(PREFIX)/lib/ocaml/bisect

 # DEFINITIONS
@@ -33,7 +33,8 @@ PATH_INSTALL=$(PATH_OCAML_PREFIX)/lib/ocaml/bisect
 PROJECT_NAME=bisect
 OCAMLBUILD=$(PATH_OCAML_PREFIX)/bin/ocamlbuild
 OCAMLBUILD_ENV=WARNINGS=$(WARNINGS) PATH_OCAML_PREFIX=$(PATH_OCAML_PREFIX)
-OCAMLBUILD_FLAGS=-classic-display -no-links
+CAMLP4_INCLUDE=$(shell test -z $(CAMLP4_LIBDIR) || echo "-cflags -I,$(CAMLP4_LIBDIR)")
+OCAMLBUILD_FLAGS=-classic-display -no-links $(CAMLP4_INCLUDE)
 MODULES_ODOCL=$(PROJECT_NAME).odocl
 MODULES_MLPACK=$(PROJECT_NAME).mlpack
 MODULES_MLPACK_PP=$(PROJECT_NAME)_pp.mlpack
@@ -80,11 +81,11 @@ veryclean: clean
	rm -f $(PATH_OCAMLDOC)/*.html $(PATH_OCAMLDOC)/*.css

 install: FORCE
-	cp $(PATH_BUILD)/src/report/report.byte $(PATH_OCAML_PREFIX)/bin/bisect-report; \
+	cp $(PATH_BUILD)/src/report/report.byte $(PREFIX)/bin/bisect-report; \
	if [ "$(PPX)" = "TRUE" ]; then \
-	  cp $(PATH_BUILD)/src/syntax/bisect_ppx.byte $(PATH_OCAML_PREFIX)/bin; \
+	  cp $(PATH_BUILD)/src/syntax/bisect_ppx.byte $(PREFIX)/bin; \
	fi; \
-	(test -x $(PATH_OCAML_PREFIX)/bin/ocamlopt && cp $(PATH_BUILD)/src/report/report.native $(PATH_OCAML_PREFIX)/bin/bisect-report.opt || true); \
+	(test -x $(PATH_OCAML_PREFIX)/bin/ocamlopt && cp $(PATH_BUILD)/src/report/report.native $(PREFIX)/bin/bisect-report.opt || true); \
	if [ -x "$(PATH_OCAMLFIND)" ]; then \
	  $(PATH_OCAMLFIND) query $(PROJECT_NAME) && $(PATH_OCAMLFIND) remove $(PROJECT_NAME) || true; \
	  $(PATH_OCAMLFIND) install $(PROJECT_NAME) META -optional \
diff --git a/configure b/configure
index bb7ebf4..61a3095 100755
--- a/configure
+++ b/configure
@@ -21,7 +21,9 @@
 # default values
 ocamlbuild=`which ocamlbuild || echo '/usr/local/bin/ocamlbuild'`
 bin_path=`dirname $ocamlbuild`
+prefix=''
 ocaml_prefix=`dirname $bin_path`
+camlp4_prefix=`dirname $(dirname $(which camlp4of))`
 ocamlfind=`which ocamlfind 2> /dev/null || echo ''`
 native_dynlink='TRUE'
 devel='FALSE'
@@ -32,8 +34,12 @@ ppx='FALSE'
 while [ $# -gt 0 ]
 do
     case "$1" in
+        -prefix)
+            prefix="$2"; shift;;
         -ocaml-prefix)
             ocaml_prefix="$2"; shift;;
+        -camlp4-prefix)
+            camlp4_prefix="$2"; shift;;
         -ocamlfind)
             ocamlfind="$2"; shift;;
         -no-native-dynlink)
@@ -45,7 +51,7 @@ do
         -ppx)
             ppx='TRUE';;
         *)
-            echo "usage: $0 [-ocaml-prefix <path>] [-ocamlfind <path>] [-no-native-dynlink] [-devel]";
+            echo "usage: $0 [-prefix <path>] [-ocaml-prefix <path>] [-ocamlfind <path>] [-no-native-dynlink] [-devel]";
             exit 1;;
         esac
         shift
@@ -57,6 +63,9 @@ if [ "$no_camlp4" = "TRUE" -a "$ppx" = "FALSE" ]; then
   exit 1
 fi

+# prefix default value
+test -z $prefix && prefix=$ocaml_prefix
+
 # make options
 make_quiet=`make -f - <<EOF
 default: gnumake
@@ -67,11 +76,13 @@ EOF`
 # file creation
 echo "# timestamp: `date`" > Makefile.config
 echo "PATH_OCAML_PREFIX=$ocaml_prefix" >> Makefile.config
+echo "PATH_CAMLP4_PREFIX=$camlp4_prefix" >> Makefile.config
 echo "PATH_OCAMLFIND=$ocamlfind" >> Makefile.config
 echo "NATIVE_DYNLINK=$native_dynlink" >> Makefile.config
 echo "WARNINGS=$devel" >> Makefile.config
 echo "NO_CAMLP4=$no_camlp4" >> Makefile.config
 echo "PPX=$ppx" >> Makefile.config
 echo "MAKE_QUIET=$make_quiet" >> Makefile.config
+echo "PREFIX=$prefix" >> Makefile.config
 echo "" >> Makefile.config
 echo 'Makefile.config successfully created'
diff --git a/myocamlbuild.ml b/myocamlbuild.ml
index 8aa25fd..09a7d48 100644
--- a/myocamlbuild.ml
+++ b/myocamlbuild.ml
@@ -70,7 +70,7 @@ let () =
     | After_rules ->
         let camlp4of =
           try
-            let path_bin = Filename.concat (Sys.getenv "PATH_OCAML_PREFIX") "bin" in
+            let path_bin = Filename.concat (Sys.getenv "PATH_CAMLP4_PREFIX") "bin" in
             Filename.concat path_bin "camlp4of"
           with _ -> "camlp4of" in
         flag ["ocaml"; "compile"; "pp_camlp4of"] (S[A"-pp"; A camlp4of]);
--
2.7.4


code:
From 0aaddfceeea3e89df196ab1846da54d09713a512 Mon Sep 17 00:00:00 2001
From: Julien Lepiller <julien@lepiller.eu>
Date: Thu, 15 Dec 2016 21:17:31 +0100
Subject: [PATCH] fix configure

---
 Makefile.in | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/Makefile.in b/Makefile.in
index d040f4c..85e0b38 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -32,6 +32,7 @@ BISECT_REPORT	= @BISECT_REPORT@
 BYTESWAP_H	= @BYTESWAP_H@

 OCAMLLIB	= @OCAMLLIB@
+BISECTLIB	= $(shell if test -z $${BISECTLIB}; then echo $(OCAMLLIB); else echo $${BISECTLIB}; fi)
 top_srcdir	= @top_srcdir@

 pkg_cil		= @OCAML_PKG_cil@
@@ -47,9 +48,9 @@ OCAMLOPTPACKAGES = $(OCAMLCPACKAGES)
 OCAMLOPTLIBS	= -linkpkg

 ifneq ($(enable_coverage),no)
-OCAMLCFLAGS     += -I +bisect -pp 'camlp4o $(OCAMLLIB)/bisect/instrument.cma'
+OCAMLCFLAGS     += -I +bisect -pp 'camlp4o $(BISECTLIB)/bisect/instrument.cma'
 OCAMLCLIBS	+= -I +bisect bisect.cma
-OCAMLOPTFLAGS   += -I +bisect -pp 'camlp4o $(OCAMLLIB)/bisect/instrument.cma'
+OCAMLOPTFLAGS   += -I +bisect -pp 'camlp4o $(BISECTLIB)/bisect/instrument.cma'
 OCAMLOPTLIBS	+= -I +bisect bisect.cmxa
 endif

@@ -110,7 +111,7 @@ bitstring_persistent.cmi: bitstring_persistent.mli
	  -I +camlp4 -pp camlp4of -c $<

 pa_bitstring.cmo: pa_bitstring.ml bitstring.cma bitstring_persistent.cma
-	$(OCAMLFIND) ocamlc bitstring.cma -I +camlp4 dynlink.cma camlp4lib.cma \
+	$(OCAMLFIND) ocamlc $(OCAMLCFLAGS) bitstring.cma -I +camlp4 dynlink.cma camlp4lib.cma \
	  -pp camlp4of -c $< -o $@

 bitstring-objinfo: bitstring_objinfo.cmo bitstring.cma bitstring_persistent.cma
@@ -133,7 +134,7 @@ byteswap.h: byteswap.in.h
 ifeq ($(enable_coverage),no)
 PP	= -pp 'camlp4o bitstring.cma bitstring_persistent.cma pa_bitstring.cmo'
 else
-PP	= -pp 'camlp4o $(OCAMLLIB)/bisect/bisect.cma bitstring.cma bitstring_persistent.cma pa_bitstring.cmo'
+PP	= -pp 'camlp4o $(BISECTLIB)/bisect/bisect.cma bitstring.cma bitstring_persistent.cma pa_bitstring.cmo'
 endif

 check: test
--
2.11.0


code:
From a87c3f20e846c00e53d695497dba7038edbd12f0 Mon Sep 17 00:00:00 2001
From: Valentin Lorentz <progval@progval.net>
Date: Thu, 13 Aug 2015 11:59:04 +0200
Subject: [PATCH] Enable ocamldoc to build reproducible manpages

Bug-Debian: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=794586
Signed-off-by: Stephane Glondu <steph@glondu.net>
---
 ocamldoc/odoc_man.ml   | 15 +++++----------
 ocamldoc/odoc_misc.ml  | 12 ++++++++++--
 ocamldoc/odoc_misc.mli |  7 ++++++-
 3 files changed, 21 insertions(+), 13 deletions(-)

diff --git a/ocamldoc/odoc_man.ml b/ocamldoc/odoc_man.ml
index 615c5e172..3c85aa32a 100644
--- a/ocamldoc/odoc_man.ml
+++ b/ocamldoc/odoc_man.ml
@@ -864,14 +864,13 @@ class man =
     (** Generate the man page for the given class.*)
     method generate_for_class cl =
       Odoc_info.reset_type_names () ;
-      let date = Unix.time () in
       let file = self#file_name cl.cl_name in
       try
         let chanout = self#open_out file in
         let b = new_buf () in
         bs b (".TH \""^cl.cl_name^"\" ");
         bs b !man_section ;
-        bs b (" "^(Odoc_misc.string_of_date ~hour: false date)^" ");
+        bs b (" source: "^Odoc_misc.current_date^" ");
         bs b "OCamldoc ";
         bs b ("\""^(match !Global.title with Some t -> t | None -> "")^"\"\n");

@@ -923,14 +922,13 @@ class man =
     (** Generate the man page for the given class type.*)
     method generate_for_class_type ct =
       Odoc_info.reset_type_names () ;
-      let date = Unix.time () in
       let file = self#file_name ct.clt_name in
       try
         let chanout = self#open_out file in
         let b = new_buf () in
         bs b (".TH \""^ct.clt_name^"\" ");
         bs b !man_section ;
-        bs b (" "^(Odoc_misc.string_of_date ~hour: false date)^" ");
+        bs b (" source: "^Odoc_misc.current_date^" ");
         bs b "OCamldoc ";
         bs b ("\""^(match !Global.title with Some t -> t | None -> "")^"\"\n");

@@ -1016,14 +1014,13 @@ class man =
     (** Generate the man file for the given module type.
        @raise Failure if an error occurs.*)
     method generate_for_module_type mt =
-      let date = Unix.time () in
       let file = self#file_name mt.mt_name in
       try
         let chanout = self#open_out file in
         let b = new_buf () in
         bs b (".TH \""^mt.mt_name^"\" ");
         bs b !man_section ;
-        bs b (" "^(Odoc_misc.string_of_date ~hour: false date)^" ");
+        bs b (" source: "^Odoc_misc.current_date^" ");
         bs b "OCamldoc ";
         bs b ("\""^(match !Global.title with Some t -> t | None -> "")^"\"\n");

@@ -1099,14 +1096,13 @@ class man =
     (** Generate the man file for the given module.
        @raise Failure if an error occurs.*)
     method generate_for_module m =
-      let date = Unix.time () in
       let file = self#file_name m.m_name in
       try
         let chanout = self#open_out file in
         let b = new_buf () in
         bs b (".TH \""^m.m_name^"\" ");
         bs b !man_section ;
-        bs b (" "^(Odoc_misc.string_of_date ~hour: false date)^" ");
+        bs b (" source: "^Odoc_misc.current_date^" ");
         bs b "OCamldoc ";
         bs b ("\""^(match !Global.title with Some t -> t | None -> "")^"\"\n");

@@ -1206,14 +1202,13 @@ class man =
           | Res_const (_,f) -> f.vc_name
          )
      in
-     let date = Unix.time () in
       let file = self#file_name name in
       try
         let chanout = self#open_out file in
         let b = new_buf () in
         bs b (".TH \""^name^"\" ");
         bs b !man_section ;
-        bs b (" "^(Odoc_misc.string_of_date ~hour: false date)^" ");
+        bs b (" source: "^Odoc_misc.current_date^" ");
         bs b "OCamldoc ";
         bs b ("\""^(match !Global.title with Some t -> t | None -> "")^"\"\n");
         bs b ".SH NAME\n";
diff --git a/ocamldoc/odoc_misc.ml b/ocamldoc/odoc_misc.ml
index 4c74476da..456225f62 100644
--- a/ocamldoc/odoc_misc.ml
+++ b/ocamldoc/odoc_misc.ml
@@ -223,9 +223,9 @@ let apply_opt f v_opt =
     None -> None
   | Some v -> Some (f v)

-let string_of_date ?(hour=true) d =
+let string_of_date ?(absolute=false) ?(hour=true) d =
   let add_0 s = if String.length s < 2 then "0"^s else s in
-  let t = Unix.localtime d in
+  let t = (if absolute then Unix.gmtime else Unix.localtime) d in
   (string_of_int (t.Unix.tm_year + 1900))^"-"^
   (add_0 (string_of_int (t.Unix.tm_mon + 1)))^"-"^
   (add_0 (string_of_int t.Unix.tm_mday))^
@@ -238,6 +238,14 @@ let string_of_date ?(hour=true) d =
      ""
   )

+let current_date =
+  let time =
+    try
+      float_of_string (Sys.getenv "SOURCE_DATE_EPOCH")
+    with
+      Not_found -> Unix.time ()
+  in string_of_date ~absolute: true ~hour: false time
+

 let rec text_list_concat sep l =
   match l with
diff --git a/ocamldoc/odoc_misc.mli b/ocamldoc/odoc_misc.mli
index dd5a7fcb9..38ff0612b 100644
--- a/ocamldoc/odoc_misc.mli
+++ b/ocamldoc/odoc_misc.mli
@@ -62,7 +62,12 @@ val apply_opt : ('a -> 'b) -> 'a option -> 'b option

 (** Return a string representing a date given as a number of seconds
    since 1970. The hour is optionnaly displayed. *)
-val string_of_date : ?hour:bool -> float -> string
+val string_of_date : ?absolute:bool -> ?hour:bool -> float -> string
+
+(* Value returned by string_of_date for current time.
+ * Uses environment variable SOURCE_DATE_EPOCH if set; falls back to
+ * current timestamp otherwise. *)
+val current_date : string

 (** Return the first sentence (until the first dot) of a text.
    Don't stop in the middle of [Code], [Verbatim], [List], [Lnum],
--
2.17.1


code:
Ocaml wants to install its "core" libraries in OCAML_CORE_STDLIB.  That
does not work in a store-based distribution.

A solution was already provided by Nix

    https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/tools/ocaml/findlib/install_topfind.patch

regenerated for Guix.

--- findlib-1.5.3/src/findlib/Makefile	2014-09-16 13:21:46.000000000 +0200
+++ findlib-1.5.3/src/findlib/Makefile.new	2014-10-01 14:30:54.141082521 +0200
@@ -89,7 +89,7 @@
 install: all
 	mkdir -p "$(prefix)$(OCAML_SITELIB)/$(NAME)"
 	mkdir -p "$(prefix)$(OCAMLFIND_BIN)"
-	test $(INSTALL_TOPFIND) -eq 0 || cp topfind "$(prefix)$(OCAML_CORE_STDLIB)"
+	test $(INSTALL_TOPFIND) -eq 0 || cp topfind "$(prefix)$(OCAML_SITELIB)"
 	files=`$(TOP)/tools/collect_files $(TOP)/Makefile.config findlib.cmi findlib.mli findlib.cma topfind.cmi topfind.mli fl_package_base.mli fl_package_base.cmi fl_metascanner.mli fl_metascanner.cmi fl_metatoken.cmi findlib_top.cma findlib.cmxa findlib.a findlib.cmxs findlib_dynload.cma findlib_dynload.cmxa findlib_dynload.a findlib_dynload.cmxs fl_dynload.mli fl_dynload.cmi META` && \
 	cp $$files "$(prefix)$(OCAML_SITELIB)/$(NAME)"
 	f="ocamlfind$(EXEC_SUFFIX)"; { test -f ocamlfind_opt$(EXEC_SUFFIX) && f="ocamlfind_opt$(EXEC_SUFFIX)"; }; \


code:
From 354ef78aac0b887fae3c10b28eb2b0d83f66bdfe Mon Sep 17 00:00:00 2001
From: Julien Lepiller <julien@lepiller.eu>
Date: Mon, 2 Jan 2017 17:05:24 +0100
Subject: [PATCH] Honor SOURCE_DATE_EPOCH

---
 Makefile.in | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/Makefile.in b/Makefile.in
index a32b4b8..ef4c174 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -113,11 +113,16 @@ graph.cmx: $(CMI) $(CMX)
	$(OCAMLOPT) $(INCLUDES) -pack -o $@ $^

 VERSION=1.8.7
+ifdef SOURCE_DATE_EPOCH
+BUILD_DATE=$(shell date -u -d "@$(SOURCE_DATE_EPOCH)" 2>/dev/null || date -u -r "$(SOURCE_DATE_EPOCH)" 2>/dev/null || date)
+else
+BUILD_DATE=$(shell date)
+endif

 src/version.ml: Makefile
	rm -f $@
	echo "let version = \""$(VERSION)"\"" > $@
-	echo "let date = \""`date`"\"" >> $@
+	echo "let date = \""$(BUILD_DATE)"\"" >> $@

 # gtk2 graph editor
 ###################
--
2.11.0


code:
Fix build failure caused by use of the deprecated readdir_r(3) while
building with -Werror=deprecated-declarations

Patch copied from upstream source repository:
https://github.com/daveol/ola/commit/9d8575ff38f76df698ea8889e07a3dee8f21bd68

From 9d8575ff38f76df698ea8889e07a3dee8f21bd68 Mon Sep 17 00:00:00 2001
From: Dave Olsthoorn <dave.olsthoorn@gmail.com>
Date: Wed, 2 Mar 2016 11:22:17 +0100
Subject: [PATCH] Use readdir instead of readdir_r

This replacec the use of readdir_r with readdir since readdir seems to
be both dangarous and deprecated in newer versions of glibc.

This fixes #1055
---
 common/file/Util.cpp | 17 ++++++++---------
 1 file changed, 8 insertions(+), 9 deletions(-)

diff --git a/common/file/Util.cpp b/common/file/Util.cpp
index e2261fd..0ffddd3 100644
--- a/common/file/Util.cpp
+++ b/common/file/Util.cpp
@@ -128,30 +128,29 @@ bool FindMatchingFiles(const string &directory,
   FindClose(h_find);
 #else
   DIR *dp;
-  struct dirent dir_ent;
-  struct dirent *dir_ent_p;
+  struct dirent *dir_ent;
   if ((dp = opendir(directory.data())) == NULL) {
     OLA_WARN << "Could not open " << directory << ":" << strerror(errno);
     return false;
   }

-  if (readdir_r(dp, &dir_ent, &dir_ent_p)) {
-    OLA_WARN << "readdir_r(" << directory << "): " << strerror(errno);
+  if ((dir_ent = readdir(dp)) == NULL) {
+    OLA_WARN << "readdir(" << directory << "): " << strerror(errno);
     closedir(dp);
     return false;
   }

-  while (dir_ent_p != NULL) {
+  while (dir_ent != NULL) {
     vector<string>::const_iterator iter;
     for (iter = prefixes.begin(); iter != prefixes.end(); ++iter) {
-      if (!strncmp(dir_ent_p->d_name, iter->data(), iter->size())) {
+      if (!strncmp(dir_ent->d_name, iter->data(), iter->size())) {
         std::ostringstream str;
-        str << directory << PATH_SEPARATOR << dir_ent_p->d_name;
+        str << directory << PATH_SEPARATOR << dir_ent->d_name;
         files->push_back(str.str());
       }
     }
-    if (readdir_r(dp, &dir_ent, &dir_ent_p)) {
-      OLA_WARN << "readdir_r(" << directory << "): " << strerror(errno);
+    if ((dir_ent = readdir(dp)) == NULL) {
+      OLA_WARN << "readdir(" << directory << "): " << strerror(errno);
       closedir(dp);
       return false;
     }


code:
From 2e7e254160506dc00f1beabf170512a8e932934b Mon Sep 17 00:00:00 2001
From: Julien Lepiller <julien@lepiller.eu>
Date: Sat, 31 Dec 2016 15:43:38 +0100
Subject: [PATCH] fix build date in binary

---
 src/magic/omake_gen_magic.ml | 12 ++----------
 1 file changed, 2 insertions(+), 10 deletions(-)

diff --git a/src/magic/omake_gen_magic.ml b/src/magic/omake_gen_magic.ml
index b2419ba..fad52f5 100644
--- a/src/magic/omake_gen_magic.ml
+++ b/src/magic/omake_gen_magic.ml
@@ -150,7 +150,7 @@ let ir_magic = "%s"
 let obj_magic = "%s"
 let lib_dir = "%s"
 let version = "%s"
-let version_message = "OMake %s:\\n\\tbuild [%s %s %d %02d:%02d:%02d %d]\\n\\ton %s"
+let version_message = "OMake %s"
 |}
        default_save_interval
        digest_len
@@ -160,15 +160,7 @@ let version_message = "OMake %s:\\n\\tbuild [%s %s %d %02d:%02d:%02d %d]\\n\\ton
        (digest_files ".omo.magic" ".omo" omo_files)
        (String.escaped libdir)
        (String.escaped (shorten_version version))
-       (String.escaped version)
-       [|"Sun"; "Mon"; "Tue"; "Wed"; "Thu"; "Fri"; "Sat"|].(tm.tm_wday)
-       [|"Jan"; "Feb"; "Mar"; "Apr"; "May"; "Jun"; "Jul"; "Aug"; "Sep"; "Oct"; "Nov"; "Dec"|].(tm.tm_mon)
-       tm.tm_mday
-       tm.tm_hour
-       tm.tm_min
-       tm.tm_sec
-       (tm.tm_year + 1900)
-       (String.escaped (Unix.gethostname ()));
+       (String.escaped version);
   List.iter
     (fun (name,value) ->
        Printf.fprintf buf "let %s = %S\n" name value
--
2.11.0


code:
From 52cea818bf68f8a2d3c48d55d00c2f8b7da25e4c Mon Sep 17 00:00:00 2001
From: Daniel Hogan <daniel.hogan@usask.ca>
Date: Tue, 28 Mar 2017 22:21:18 -0600
Subject: [PATCH] Remove delete statement.

When from_scratch is true, coordinates is not allocated. A separate if
statement was added to handle the case when from_scratch is true that
does not try to free coordinates.
---
 src/formats/nwchemformat.cpp | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/src/formats/nwchemformat.cpp b/src/formats/nwchemformat.cpp
index 6f625ad5b..79298555f 100644
--- a/src/formats/nwchemformat.cpp
+++ b/src/formats/nwchemformat.cpp
@@ -232,11 +232,14 @@ static const char* OPTIMIZATION_END_PATTERN = "  Optimization converged";
           break;
         tokenize(vs,buffer);
     }
-    if ((from_scratch)||(i != natoms))
-      {
+    if (from_scratch)
+    {
+        return;
+    }
+    if (i != natoms) {
         delete[] coordinates;
         return;
-      }
+    }
     molecule->AddConformer(coordinates);
   }


code:
Fix build with glibc 2.26:

https://github.com/tpaviot/oce/issues/675

Patch copied from upstream source repository:

https://github.com/tpaviot/oce/commit/aa1321e68cc004e3debe38d79ae74581a617c767

From aa1321e68cc004e3debe38d79ae74581a617c767 Mon Sep 17 00:00:00 2001
From: Janus Weil <janus@gcc.gnu.org>
Date: Mon, 18 Dec 2017 11:27:55 +0100
Subject: [PATCH] fix build errors with glibc 2.26+ due to missing xlocale.h
 (issue #675)

* check for the presence of xlocale.h via cmake
* remove related logic from Standard_CLocaleSentry.hxx
---
 CMakeLists.txt                          |  1 +
 src/Standard/Standard_CLocaleSentry.hxx | 15 ---------------
 2 files changed, 1 insertion(+), 15 deletions(-)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index b782b4101..50e9500b2 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -616,6 +616,7 @@ if (NOT WIN32)
 	# compilation anywhere in OCE
 	include(CheckIncludeFile)
 	check_include_file(strings.h HAVE_STRINGS_H)
+	check_include_file(xlocale.h HAVE_XLOCALE_H)
 	include(CheckIncludeFileCXX)
 	check_include_file_cxx(mm_malloc.h HAVE_MM_MALLOC_H)
 	check_include_file_cxx(atomic.h OCE_HAVE_ATOMIC_H)
diff --git a/src/Standard/Standard_CLocaleSentry.hxx b/src/Standard/Standard_CLocaleSentry.hxx
index 2b226e7f3..1a4c1dadc 100644
--- a/src/Standard/Standard_CLocaleSentry.hxx
+++ b/src/Standard/Standard_CLocaleSentry.hxx
@@ -20,21 +20,6 @@

 #include <locale.h>

-#ifndef HAVE_XLOCALE_H
-  //! "xlocale.h" available in Mac OS X and glibc (Linux) for a long time as an extension
-  //! and become part of POSIX since '2008.
-  //! Notice that this is impossible to test (_POSIX_C_SOURCE >= 200809L)
-  //! since POSIX didn't declared such identifier.
-  #if defined(__APPLE__)
-    #define HAVE_XLOCALE_H
-  #endif
-
-  //! We check _GNU_SOURCE for glibc extensions here and it is always defined by g++ compiler.
-  #if defined(_GNU_SOURCE) && !defined(__ANDROID__)
-    #define HAVE_XLOCALE_H
-  #endif
-#endif // ifndef HAVE_LOCALE_H
-
 #ifdef HAVE_XLOCALE_H
   #include <xlocale.h>
 #endif
--
2.15.1


code:
# This patch removes all need for the ThirdParty files of OpenFOAM.

# Derived from EasyBuild patch by Ward Poelmans <wpoely86@gmail.com>.
# Modified for GNU Guix by Paul Garlick <pgarlick@tourbillion-technology.com>.

diff -ur OpenFOAM-4.x-version-4.1.org/applications/utilities/mesh/manipulation/setSet/Allwmake OpenFOAM-4.x-version-4.1/applications/utilities/mesh/manipulation/setSet/Allwmake
--- OpenFOAM-4.x-version-4.1.org/applications/utilities/mesh/manipulation/setSet/Allwmake
+++ OpenFOAM-4.x-version-4.1/applications/utilities/mesh/manipulation/setSet/Allwmake
@@ -9,7 +9,7 @@
 #
 # use readline if available
 #
-if [ -f /usr/include/readline/readline.h ]
+if true
 then
     echo "Found <readline/readline.h>  --  enabling readline support."
     export COMP_FLAGS="-DHAS_READLINE"
diff -ur OpenFOAM-4.x-version-4.1.org/etc/bashrc OpenFOAM-4.x-version-4.1/etc/bashrc
--- OpenFOAM-4.x-version-4.1.org/etc/bashrc
+++ OpenFOAM-4.x-version-4.1/etc/bashrc
@@ -43,8 +43,10 @@
 # Please set to the appropriate path if the default is not correct.
 #
 [ $BASH_SOURCE ] && \
-export FOAM_INST_DIR=$(cd ${BASH_SOURCE%/*/*/*} && pwd -P) || \
+export FOAM_INST_DIR=$(cd $(dirname $BASH_SOURCE)/../.. && pwd -P) || \
 export FOAM_INST_DIR=$HOME/$WM_PROJECT
+# For GNU Guix: set initially for build then re-set at runtime
+#
 # export FOAM_INST_DIR=~$WM_PROJECT
 # export FOAM_INST_DIR=/opt/$WM_PROJECT
 # export FOAM_INST_DIR=/usr/local/$WM_PROJECT
diff -ur OpenFOAM-4.x-version-4.1.org/etc/config.sh/CGAL OpenFOAM-4.x-version-4.1/etc/config.sh/CGAL
--- OpenFOAM-4.x-version-4.1.org/etc/config.sh/CGAL
+++ OpenFOAM-4.x-version-4.1/etc/config.sh/CGAL
@@ -36,37 +36,7 @@
 #
 #------------------------------------------------------------------------------

-boost_version=boost-system
-cgal_version=cgal-system
-#cgal_version=CGAL-4.8
-
-if [ -z "$SOURCE_CGAL_VERSIONS_ONLY" ]
-then
-
-    common_path=$WM_THIRD_PARTY_DIR/platforms/$WM_ARCH$WM_COMPILER
-
-    export BOOST_ARCH_PATH=$common_path/$boost_version
-    export CGAL_ARCH_PATH=$common_path/$cgal_version
-
-    if [ "$FOAM_VERBOSE" -a "$PS1" ]
-    then
-        echo "Using CGAL and boost" 1>&2
-        echo "    $cgal_version at $CGAL_ARCH_PATH" 1>&2
-        echo "    $boost_version at $BOOST_ARCH_PATH" 1>&2
-    fi
-
-    if [ -d "$CGAL_ARCH_PATH" -a "$cgal_version" != "cgal-system" ]
-    then
-        _foamAddLib $CGAL_ARCH_PATH/lib
-    fi
-
-    if [ -d "$BOOST_ARCH_PATH" -a "$boost_version" != "boost-system" ]
-    then
-        _foamAddLib $BOOST_ARCH_PATH/lib
-    fi
-
-    unset boost_version cgal_version common_path
-
-fi
+export CGAL_ARCH_PATH=$CGAL_ROOT
+export BOOST_ARCH_PATH=$BOOST_ROOT

 #------------------------------------------------------------------------------
diff -ur OpenFOAM-4.x-version-4.1.org/etc/config.sh/gperftools OpenFOAM-4.x-version-4.1/etc/config.sh/gperftools
--- OpenFOAM-4.x-version-4.1.org/etc/config.sh/gperftools
+++ OpenFOAM-4.x-version-4.1/etc/config.sh/gperftools
@@ -29,13 +29,5 @@
 #
 #------------------------------------------------------------------------------

-version=svn
-gperftools_install=$WM_THIRD_PARTY_DIR/platforms/$WM_ARCH$WM_COMPILER
-
-GPERFTOOLS_VERSION=gperftools-$version
-GPERFTOOLS_ARCH_PATH=$gperftools_install/$GPERFTOOLS_VERSION
-
-export PATH=$GPERFTOOLS_ARCH_PATH/bin:$PATH
-export LD_LIBRARY_PATH=$GPERFTOOLS_ARCH_PATH/lib:$LD_LIBRARY_PATH

 #------------------------------------------------------------------------------
diff -ur OpenFOAM-4.x-version-4.1.org/etc/config.sh/metis OpenFOAM-4.x-version-4.1/etc/config.sh/metis
--- OpenFOAM-4.x-version-4.1.org/etc/config.sh/metis
+++ OpenFOAM-4.x-version-4.1/etc/config.sh/metis
@@ -34,7 +34,7 @@
 #
 #------------------------------------------------------------------------------

-export METIS_VERSION=metis-5.1.0
-export METIS_ARCH_PATH=$WM_THIRD_PARTY_DIR/platforms/$WM_ARCH$WM_COMPILER$WM_PRECISION_OPTION$WM_LABEL_OPTION/$METIS_VERSION
+export METIS_VERSION=metis-$METISVERSION
+export METIS_ARCH_PATH=$METIS_ROOT

 #------------------------------------------------------------------------------
diff -ur OpenFOAM-4.x-version-4.1.org/etc/config.sh/scotch OpenFOAM-4.x-version-4.1/etc/config.sh/scotch
--- OpenFOAM-4.x-version-4.1.org/etc/config.sh/scotch
+++ OpenFOAM-4.x-version-4.1/etc/config.sh/scotch
@@ -37,7 +37,7 @@
 #
 #------------------------------------------------------------------------------

-export SCOTCH_VERSION=scotch_6.0.3
-export SCOTCH_ARCH_PATH=$WM_THIRD_PARTY_DIR/platforms/$WM_ARCH$WM_COMPILER$WM_PRECISION_OPTION$WM_LABEL_OPTION/$SCOTCH_VERSION
+export SCOTCH_VERSION=scotch_$SCOTCHVERSION
+export SCOTCH_ARCH_PATH=$SCOTCH_ROOT

 #------------------------------------------------------------------------------
diff -ur OpenFOAM-4.x-version-4.1.org/etc/config.sh/settings OpenFOAM-4.x-version-4.1/etc/config.sh/settings
--- OpenFOAM-4.x-version-4.1.org/etc/config.sh/settings
+++ OpenFOAM-4.x-version-4.1/etc/config.sh/settings
@@ -279,6 +279,9 @@
     ;;
 system)
     # Use system compiler
+    # Use system GMP and MPFR packages
+    export GMP_ARCH_PATH=$GMP_ROOT
+    export MPFR_ARCH_PATH=$MPFR_ROOT
     ;;
 *)
     echo "Warn: WM_COMPILER_TYPE='$WM_COMPILER_TYPE' is unsupported" 1>&2
diff -ur OpenFOAM-4.x-version-4.1.org/src/parallel/decompose/ptscotchDecomp/Make/options OpenFOAM-4.x-version-4.1/src/parallel/decompose/ptscotchDecomp/Make/options
--- OpenFOAM-4.x-version-4.1.org/src/parallel/decompose/ptscotchDecomp/Make/options
+++ OpenFOAM-4.x-version-4.1/src/parallel/decompose/ptscotchDecomp/Make/options
@@ -5,8 +5,7 @@
     $(PFLAGS) $(PINC) \
     -I$(SCOTCH_ROOT)/include \
     -I$(SCOTCH_ARCH_PATH)/include/$(FOAM_MPI) \
-    -I/usr/include/scotch \
     -I../decompositionMethods/lnInclude

 LIB_LIBS = \
-    -L$(SCOTCH_ROOT)/lib -L$(FOAM_EXT_LIBBIN)/$(FOAM_MPI) -lptscotch -lptscotcherrexit -lscotch ${LINK_FLAGS} -lrt
+    -L$(SCOTCH_ROOT)/lib -L$(MPI_ARCH_PATH)/lib -lptscotch -lptscotcherrexit -lscotch ${LINK_FLAGS} -lrt
diff -ur OpenFOAM-4.x-version-4.1.org/src/parallel/decompose/scotchDecomp/Make/options OpenFOAM-4.x-version-4.1/src/parallel/decompose/scotchDecomp/Make/options
--- OpenFOAM-4.x-version-4.1.org/src/parallel/decompose/scotchDecomp/Make/options
+++ OpenFOAM-4.x-version-4.1/src/parallel/decompose/scotchDecomp/Make/options
@@ -9,8 +9,7 @@
     $(PFLAGS) $(PINC) \
     -I$(SCOTCH_ROOT)/include \
     -I$(SCOTCH_ARCH_PATH)/include \
-    -I/usr/include/scotch \
     -I../decompositionMethods/lnInclude

 LIB_LIBS = \
-    -L$(SCOTCH_ROOT)/lib -L$(FOAM_EXT_LIBBIN) -lscotch -lscotcherrexit -lrt
+    -L$(SCOTCH_ROOT)/lib -lscotch -lscotcherrexit -lrt
diff -ur OpenFOAM-4.x-version-4.1.org/wmake/makefiles/general OpenFOAM-4.x-version-4.1/wmake/makefiles/general
--- OpenFOAM-4.x-version-4.1.org/wmake/makefiles/general
+++ OpenFOAM-4.x-version-4.1/wmake/makefiles/general
@@ -33,7 +33,6 @@
 # The Makefile uses a POSIX shell
 #------------------------------------------------------------------------------

-SHELL           = /bin/sh

 #------------------------------------------------------------------------------
diff -ur OpenFOAM-4.x-version-4.1.org/wmake/wmake OpenFOAM-4.x-version-4.1/wmake/wmake
--- OpenFOAM-4.x-version-4.1.org/wmake/wmake
+++ OpenFOAM-4.x-version-4.1/wmake/wmake
@@ -163,7 +163,7 @@
 then
     if [ "$WM_NCOMPPROCS" -gt 1 -a ! "$MAKEFLAGS" ]
     then
-        lockDir=$HOME/.$WM_PROJECT/.wmake
+        lockDir=$(cd $(dirname $BASH_SOURCE)/../.. && pwd -P)/.$WM_PROJECT/.wmake

         if [ -d $lockDir ]
         then
diff -ur OpenFOAM-4.x-version-4.1.org/wmake/wmakeScheduler OpenFOAM-4.x-version-4.1/wmake/wmakeScheduler
--- OpenFOAM-4.x-version-4.1.org/wmake/wmakeScheduler
+++ OpenFOAM-4.x-version-4.1/wmake/wmakeScheduler
@@ -53,7 +53,7 @@
 # csh sets HOST, bash sets HOSTNAME
 : ${HOST:=$HOSTNAME}

-lockDir=$HOME/.$WM_PROJECT/.wmake
+lockDir=$(cd $(dirname $BASH_SOURCE)/../.. && pwd -P)/.$WM_PROJECT/.wmake

 # Fallback - 1 core on current host
 : ${WM_HOSTS:=$HOST:1}
diff -ur OpenFOAM-4.x-version-4.1.org/wmake/wmakeSchedulerUptime OpenFOAM-4.x-version-4.1/wmake/wmakeSchedulerUptime
--- OpenFOAM-4.x-version-4.1.org/wmake/wmakeSchedulerUptime
+++ OpenFOAM-4.x-version-4.1/wmake/wmakeSchedulerUptime
@@ -53,7 +53,7 @@
 # csh sets HOST, bash sets HOSTNAME
 : ${HOST:=$HOSTNAME}

-lockDir=$HOME/.$WM_PROJECT/.wmake
+lockDir=$(cd $(dirname $BASH_SOURCE)/../.. && pwd -P)/.$WM_PROJECT/.wmake
 # Fallback - 1 core on current host
 : ${WM_HOSTS:=$HOST:1}

diff -ur OpenFOAM-4.x-version-4.1.org/src/parallel/decompose/metisDecomp/metisDecomp.C OpenFOAM-4.x-version-4.1/src/parallel/decompose/metisDecomp/metisDecomp.C
--- OpenFOAM-4.x-version-4.1.org/src/parallel/decompose/metisDecomp/metisDecomp.C
+++ OpenFOAM-4.x-version-4.1/src/parallel/decompose/metisDecomp/metisDecomp.C
@@ -67,7 +67,7 @@

     // Processor weights initialised with no size, only used if specified in
     // a file
-    Field<scalar> processorWeights;
+    Field<floatScalar> processorWeights;

     // Cell weights (so on the vertices of the dual)
     List<label> cellWeights;
diff -ur OpenFOAM-4.x-version-4.1.org/wmake/rules/General/CGAL OpenFOAM-4.x-version-4.1/wmake/rules/General/CGAL
--- OpenFOAM-4.x-version-4.1.org/wmake/rules/General/CGAL
+++ OpenFOAM-4.x-version-4.1/wmake/rules/General/CGAL
@@ -6,9 +6,10 @@
     -I/usr/include

 CGAL_LIBS = \
-    -L$(MPFR_ARCH_PATH)/lib$(WM_COMPILER_LIB_ARCH) \
-    -L$(GMP_ARCH_PATH)/lib$(WM_COMPILER_LIB_ARCH) \
+    -L$(MPFR_ARCH_PATH)/lib \
+    -L$(GMP_ARCH_PATH)/lib \
     -L$(BOOST_ARCH_PATH)/lib \
     -L$(CGAL_ARCH_PATH)/lib \
     -lCGAL \
+    -lgmp \
     -lmpfr
diff -ur OpenFOAM-4.x-version-4.1.org/wmake/rules/linux64Gcc/c++ OpenFOAM-4.x-version-4.1/wmake/rules/linux64Gcc/c++
--- OpenFOAM-4.x-version-4.1.org/wmake/rules/linux64Gcc/c++
+++ OpenFOAM-4.x-version-4.1/wmake/rules/linux64Gcc/c++
@@ -20,5 +20,5 @@

 LINK_LIBS   = $(c++DBUG)

-LINKLIBSO   = $(CC) $(c++FLAGS) -shared -Xlinker --add-needed -Xlinker --no-as-needed
-LINKEXE     = $(CC) $(c++FLAGS) -Xlinker --add-needed -Xlinker --no-as-needed
+LINKLIBSO   = $(CC) $(c++FLAGS) $(LDFLAGS) -shared -Xlinker --add-needed -Xlinker --no-as-needed
+LINKEXE     = $(CC) $(c++FLAGS) $(LDFLAGS) -Xlinker --add-needed -Xlinker --no-as-needed


code:
Fix CVE-2017-9287:

https://www.openldap.org/its/?findid=8655
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-9287

Patch copied from upstream source repository:

https://www.openldap.org/devel/gitweb.cgi?p=openldap.git;a=commit;h=0cee1ffb6021b1aae3fcc9581699da1c85a6dd6e

From 0cee1ffb6021b1aae3fcc9581699da1c85a6dd6e Mon Sep 17 00:00:00 2001
From: Ryan Tandy <ryan@nardis.ca>
Date: Wed, 17 May 2017 20:07:39 -0700
Subject: [PATCH] ITS#8655 fix double free on paged search with pagesize 0

Fixes a double free when a search includes the Paged Results control
with a page size of 0 and the search base matches the filter.
---
 servers/slapd/back-mdb/search.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/servers/slapd/back-mdb/search.c b/servers/slapd/back-mdb/search.c
index 301d1a498c..43442aa242 100644
--- a/servers/slapd/back-mdb/search.c
+++ b/servers/slapd/back-mdb/search.c
@@ -1066,7 +1066,8 @@ notfound:
 			/* check size limit */
 			if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
 				if ( rs->sr_nentries >= ((PagedResultsState *)op->o_pagedresults_state)->ps_size ) {
-					mdb_entry_return( op, e );
+					if (e != base)
+						mdb_entry_return( op, e );
 					e = NULL;
 					send_paged_response( op, rs, &lastid, tentries );
 					goto done;
--
2.13.0


code:
This patch adds support for nRF52 series devices.  It is patchset 7 from
<http://openocd.zylin.com/#/c/3511/>, which has been tested, but not
merged yet in master.

From: Michael Dietz <mjdietzx@gmail.com>
Date: Mon, 30 May 2016 12:50:44 +0000 (-0700)
Subject: Added support for nRF52 Series Devices.
X-Git-Url: http://openocd.zylin.com/gitweb?p=openocd.git;a=commitdiff_plain;h=9ba15633e221d9d72e320372ba8f49d3f30d4bce

Added support for nRF52 Series Devices.

Both nrf52.c and nrf52.cfg are based off of previous nRF51 files.
- Some possible race conditions with NVMC have been fixed in nRF52.c
- Removed nrf51_get_probed_chip_if_halted() as the core does not have to be halted to perform operations where it is called.
- Only registers that are needed by openOCD are defined, some registers in nRF51 don't exist in nRF52 and are removed.
- Some all around cleanup has been done.
- The protection mechanism is completely different on nRF52 and this has not been implemented yet - just prints a warning and returns for now.

Change-Id: I4dd42c86f33f450709bb981806c2655f04aa6201
Signed-off-by: Michael Dietz <mjdietzx@gmail.com>
---

diff --git a/src/flash/nor/Makefile.am b/src/flash/nor/Makefile.am
index 727e4f2..839667c 100644
--- a/src/flash/nor/Makefile.am
+++ b/src/flash/nor/Makefile.am
@@ -36,6 +36,7 @@ NOR_DRIVERS = \
 	%D%/niietcm4.c \
 	%D%/non_cfi.c \
 	%D%/nrf51.c \
+	%D%/nrf52.c \
 	%D%/numicro.c \
 	%D%/ocl.c \
 	%D%/pic32mx.c \
diff --git a/src/flash/nor/drivers.c b/src/flash/nor/drivers.c
index 56a5cb2..071273e 100644
--- a/src/flash/nor/drivers.c
+++ b/src/flash/nor/drivers.c
@@ -48,6 +48,7 @@ extern struct flash_driver mdr_flash;
 extern struct flash_driver mrvlqspi_flash;
 extern struct flash_driver niietcm4_flash;
 extern struct flash_driver nrf51_flash;
+extern struct flash_driver nrf52_flash;
 extern struct flash_driver numicro_flash;
 extern struct flash_driver ocl_flash;
 extern struct flash_driver pic32mx_flash;
@@ -100,6 +101,7 @@ static struct flash_driver *flash_drivers[] = {
 	&mrvlqspi_flash,
 	&niietcm4_flash,
 	&nrf51_flash,
+       &nrf52_flash,
 	&numicro_flash,
 	&ocl_flash,
 	&pic32mx_flash,
diff --git a/src/flash/nor/nrf52.c b/src/flash/nor/nrf52.c
new file mode 100644
index 0000000..7f2bd35
--- /dev/null
+++ b/src/flash/nor/nrf52.c
@@ -0,0 +1,733 @@
+/***************************************************************************
+ *   Copyright (C) 2013 Synapse Product Development                        *
+ *   Andrey Smirnov <andrew.smironv@gmail.com>                             *
+ *   Angus Gratton <gus@projectgus.com>                                    *
+ *   Erdem U. Altunyurt <spamjunkeater@gmail.com>                          *
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 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 General Public License for more details.                          *
+ *                                                                         *
+ *   You should have received a copy of the GNU General Public License     *
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
+ ***************************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdlib.h>
+
+#include "imp.h"
+#include <target/algorithm.h>
+#include <target/armv7m.h>
+#include <helper/types.h>
+
+/* nRF52 Register addresses used by openOCD. */
+#define NRF52_FLASH_BASE_ADDR        (0x0)
+
+#define NRF52_FICR_BASE_ADDR         (0x10000000)
+#define NRF52_FICR_CODEPAGESIZE_ADDR (NRF52_FICR_BASE_ADDR | 0x010)
+#define NRF52_FICR_CODESIZE_ADDR     (NRF52_FICR_BASE_ADDR | 0x014)
+
+#define NRF52_UICR_BASE_ADDR         (0x10001000)
+
+#define NRF52_NVMC_BASE_ADDR         (0x4001E000)
+#define NRF52_NVMC_READY_ADDR        (NRF52_NVMC_BASE_ADDR | 0x400)
+#define NRF52_NVMC_CONFIG_ADDR       (NRF52_NVMC_BASE_ADDR | 0x504)
+#define NRF52_NVMC_ERASEPAGE_ADDR    (NRF52_NVMC_BASE_ADDR | 0x508)
+#define NRF52_NVMC_ERASEALL_ADDR     (NRF52_NVMC_BASE_ADDR | 0x50C)
+#define NRF52_NVMC_ERASEUICR_ADDR    (NRF52_NVMC_BASE_ADDR | 0x514)
+
+/* nRF52 bit fields. */
+enum nrf52_nvmc_config_bits {
+	NRF52_NVMC_CONFIG_REN = 0x0,
+	NRF52_NVMC_CONFIG_WEN = 0x01,
+	NRF52_NVMC_CONFIG_EEN = 0x02
+};
+
+enum nrf52_nvmc_ready_bits {
+	NRF52_NVMC_BUSY  = 0x0,
+	NRF52_NVMC_READY = 0x01
+};
+
+/* nRF52 state information. */
+struct nrf52_info {
+	uint32_t code_page_size; /* Size of FLASH page in bytes. */
+	uint32_t code_memory_size; /* Size of Code FLASH region in bytes. */
+
+	struct {
+		bool probed;
+		int (*write) (struct flash_bank *bank,
+				struct nrf52_info *chip,
+				const uint8_t *buffer, uint32_t offset, uint32_t count);
+	} bank[2]; /* There are two regions in nRF52 FLASH - Code and UICR. */
+	struct target *target;
+};
+
+static int nrf52_protect_check(struct flash_bank *bank);
+
+static int nrf52_probe(struct flash_bank *bank)
+{
+	int res;
+	struct nrf52_info *chip = bank->driver_priv;
+	assert(chip != NULL);
+
+	res = target_read_u32(chip->target,
+						NRF52_FICR_CODEPAGESIZE_ADDR,
+						&chip->code_page_size);
+	if (res != ERROR_OK) {
+		LOG_ERROR("Couldn't read code page size");
+		return res;
+	}
+
+	res = target_read_u32(chip->target,
+						NRF52_FICR_CODESIZE_ADDR,
+						&chip->code_memory_size);
+	if (res != ERROR_OK) {
+		LOG_ERROR("Couldn't read code memory size");
+		return res;
+	}
+
+	chip->code_memory_size = chip->code_memory_size * chip->code_page_size;
+
+	if (bank->base == NRF52_FLASH_BASE_ADDR) {
+		bank->size = chip->code_memory_size;
+		bank->num_sectors = bank->size / chip->code_page_size;
+		bank->sectors = calloc(bank->num_sectors,
+							sizeof((bank->sectors)[0]));
+		if (!bank->sectors)
+			return ERROR_FLASH_BANK_NOT_PROBED;
+
+		/* Fill out the sector information: All nRF51 sectors are the same size. */
+		for (int i = 0; i < bank->num_sectors; i++) {
+			bank->sectors[i].size = chip->code_page_size;
+			bank->sectors[i].offset	= i * chip->code_page_size;
+
+			/* Mark as unknown. */
+			bank->sectors[i].is_erased = -1;
+			bank->sectors[i].is_protected = -1;
+		}
+
+		nrf52_protect_check(bank);
+
+		chip->bank[0].probed = true;
+	} else { /* This is the UICR bank. */
+		bank->size = chip->code_page_size;
+		bank->num_sectors = 1;
+		bank->sectors = calloc(bank->num_sectors,
+							sizeof((bank->sectors)[0]));
+		if (!bank->sectors)
+			return ERROR_FLASH_BANK_NOT_PROBED;
+
+		bank->sectors[0].size = bank->size;
+		bank->sectors[0].offset	= 0;
+
+		bank->sectors[0].is_erased = -1;
+		bank->sectors[0].is_protected = -1;
+
+		chip->bank[1].probed = true;
+	}
+
+	return ERROR_OK;
+}
+
+static int nrf52_bank_is_probed(struct flash_bank *bank)
+{
+	struct nrf52_info *chip = bank->driver_priv;
+	assert(chip != NULL);
+
+	return chip->bank[bank->bank_number].probed;
+}
+
+static int nrf52_auto_probe(struct flash_bank *bank)
+{
+	if (!nrf52_bank_is_probed(bank))
+		return nrf52_probe(bank);
+	else
+		return ERROR_OK;
+}
+
+static int nrf52_wait_for_nvmc(struct nrf52_info *chip)
+{
+	int res;
+	uint32_t ready;
+	int timeout = 100;
+
+	do {
+		res = target_read_u32(chip->target, NRF52_NVMC_READY_ADDR, &ready);
+		if (res != ERROR_OK) {
+			LOG_ERROR("Couldn't read NVMC_READY register");
+			return res;
+		}
+
+		if (ready == NRF52_NVMC_READY)
+			return ERROR_OK;
+
+		alive_sleep(1);
+	} while (timeout--);
+
+	LOG_DEBUG("Timed out waiting for the NVMC to be ready");
+	return ERROR_FLASH_BUSY;
+}
+
+static int nrf52_nvmc_erase_enable(struct nrf52_info *chip)
+{
+	int res;
+
+	res = nrf52_wait_for_nvmc(chip);
+	if (res != ERROR_OK)
+		return res;
+
+	res = target_write_u32(chip->target,
+						NRF52_NVMC_CONFIG_ADDR,
+						NRF52_NVMC_CONFIG_EEN);
+	if (res != ERROR_OK) {
+		LOG_ERROR("Failed to configure the NVMC for erasing");
+		return res;
+	}
+
+	return res;
+}
+
+static int nrf52_nvmc_write_enable(struct nrf52_info *chip)
+{
+	int res;
+
+	res = nrf52_wait_for_nvmc(chip);
+	if (res != ERROR_OK)
+		return res;
+
+	res = target_write_u32(chip->target,
+						NRF52_NVMC_CONFIG_ADDR,
+						NRF52_NVMC_CONFIG_WEN);
+	if (res != ERROR_OK) {
+		LOG_ERROR("Failed to configure the NVMC for writing");
+		return res;
+	}
+
+	return res;
+}
+
+static int nrf52_nvmc_read_only(struct nrf52_info *chip)
+{
+	int res;
+
+	res = nrf52_wait_for_nvmc(chip);
+	if (res != ERROR_OK)
+		return res;
+
+	res = target_write_u32(chip->target,
+						NRF52_NVMC_CONFIG_ADDR,
+						NRF52_NVMC_CONFIG_REN);
+	if (res != ERROR_OK) {
+		LOG_ERROR("Failed to configure the NVMC for read-only");
+		return res;
+	}
+
+	return res;
+}
+
+static int nrf52_nvmc_generic_erase(struct nrf52_info *chip,
+								uint32_t erase_register,
+								uint32_t erase_value)
+{
+	int res;
+
+	res = nrf52_nvmc_erase_enable(chip);
+	if (res != ERROR_OK)
+		return res;
+
+	res = target_write_u32(chip->target,
+						erase_register,
+						erase_value);
+	if (res != ERROR_OK)
+		LOG_ERROR("Failed to write NVMC erase register");
+
+	return nrf52_nvmc_read_only(chip);
+}
+
+static int nrf52_protect_check(struct flash_bank *bank)
+{
+	LOG_WARNING("nrf52_protect_check() is not implemented for nRF52 series devices yet");
+	return ERROR_OK;
+}
+
+static int nrf52_protect(struct flash_bank *bank, int set, int first, int last)
+{
+	LOG_WARNING("nrf52_protect() is not implemented for nRF52 series devices yet");
+	return ERROR_OK;
+}
+
+static struct flash_sector *nrf52_find_sector_by_address(struct flash_bank *bank, uint32_t address)
+{
+	struct nrf52_info *chip = bank->driver_priv;
+	assert(chip != NULL);
+
+	for (int i = 0; i < bank->num_sectors; i++)
+		if (bank->sectors[i].offset <= address &&
+			address < (bank->sectors[i].offset + chip->code_page_size)) {
+			return &bank->sectors[i];
+		}
+
+	return NULL;
+}
+
+static int nrf52_erase_all(struct nrf52_info *chip)
+{
+	LOG_DEBUG("Erasing all non-volatile memory");
+	return nrf52_nvmc_generic_erase(chip,
+								NRF52_NVMC_ERASEALL_ADDR,
+								0x01);
+}
+
+static int nrf52_erase_page(struct flash_bank *bank,
+							struct nrf52_info *chip,
+							struct flash_sector *sector)
+{
+	int res;
+
+	LOG_DEBUG("Erasing page at 0x%"PRIx32, sector->offset);
+	if (sector->is_protected == 1) {
+		LOG_ERROR("Cannot erase protected sector at 0x%" PRIx32, sector->offset);
+		return ERROR_FAIL;
+	}
+
+	if (bank->base == NRF52_UICR_BASE_ADDR) {
+		res = nrf52_nvmc_generic_erase(chip,
+									NRF52_NVMC_ERASEUICR_ADDR,
+									0x00000001);
+	} else {
+		res = nrf52_nvmc_generic_erase(chip,
+									NRF52_NVMC_ERASEPAGE_ADDR,
+									sector->offset);
+	}
+
+	if (res == ERROR_OK)
+		sector->is_erased = 1;
+	return res;
+}
+
+static const uint8_t nrf52_flash_write_code[] = {
+	/* See contrib/loaders/flash/cortex-m0.S */
+	/* <wait_fifo>: */
+	0x0d, 0x68,		/* ldr	r5,	[r1,	#0] */
+	0x00, 0x2d,		/* cmp	r5,	#0 */
+	0x0b, 0xd0,		/* beq.n	1e <exit> */
+	0x4c, 0x68,		/* ldr	r4,	[r1,	#4] */
+	0xac, 0x42,		/* cmp	r4,	r5 */
+	0xf9, 0xd0,		/* beq.n	0 <wait_fifo> */
+	0x20, 0xcc,		/* ldmia	r4!,	{r5} */
+	0x20, 0xc3,		/* stmia	r3!,	{r5} */
+	0x94, 0x42,		/* cmp	r4,	r2 */
+	0x01, 0xd3,		/* bcc.n	18 <no_wrap> */
+	0x0c, 0x46,		/* mov	r4,	r1 */
+	0x08, 0x34,		/* adds	r4,	#8 */
+	/* <no_wrap>: */
+	0x4c, 0x60,		/* str	r4, [r1,	#4] */
+	0x04, 0x38,		/* subs	r0, #4 */
+	0xf0, 0xd1,		/* bne.n	0 <wait_fifo> */
+	/* <exit>: */
+	0x00, 0xbe		/* bkpt	0x0000 */
+};
+
+
+/* Start a low level flash write for the specified region */
+static int nrf52_ll_flash_write(struct nrf52_info *chip, uint32_t offset, const uint8_t *buffer, uint32_t bytes)
+{
+	struct target *target = chip->target;
+	uint32_t buffer_size = 8192;
+	struct working_area *write_algorithm;
+	struct working_area *source;
+	uint32_t address = NRF52_FLASH_BASE_ADDR + offset;
+	struct reg_param reg_params[4];
+	struct armv7m_algorithm armv7m_info;
+	int retval = ERROR_OK;
+
+	LOG_DEBUG("Writing buffer to flash offset=0x%"PRIx32" bytes=0x%"PRIx32, offset, bytes);
+	assert(bytes % 4 == 0);
+
+	/* allocate working area with flash programming code */
+	if (target_alloc_working_area(target, sizeof(nrf52_flash_write_code),
+			&write_algorithm) != ERROR_OK) {
+		LOG_WARNING("no working area available, falling back to slow memory writes");
+
+		for (; bytes > 0; bytes -= 4) {
+			retval = target_write_memory(chip->target,
+										offset, 4, 1, buffer);
+			if (retval != ERROR_OK)
+				return retval;
+
+			retval = nrf52_wait_for_nvmc(chip);
+			if (retval != ERROR_OK)
+				return retval;
+
+			offset += 4;
+			buffer += 4;
+		}
+
+		return ERROR_OK;
+	}
+
+	LOG_WARNING("using fast async flash loader. This is currently supported");
+	LOG_WARNING("only with ST-Link and CMSIS-DAP. If you have issues, add");
+	LOG_WARNING("\"set WORKAREASIZE 0\" before sourcing nrf52.cfg to disable it");
+
+	retval = target_write_buffer(target, write_algorithm->address,
+				sizeof(nrf52_flash_write_code),
+				nrf52_flash_write_code);
+	if (retval != ERROR_OK)
+		return retval;
+
+	/* memory buffer */
+	while (target_alloc_working_area(target, buffer_size, &source) != ERROR_OK) {
+		buffer_size /= 2;
+		buffer_size &= ~3UL; /* Make sure it's 4 byte aligned */
+		if (buffer_size <= 256) {
+			/* free working area, write algorithm already allocated */
+			target_free_working_area(target, write_algorithm);
+
+			LOG_WARNING("No large enough working area available, can't do block memory writes");
+			return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
+		}
+	}
+
+	armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
+	armv7m_info.core_mode = ARM_MODE_THREAD;
+
+	init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT);	/* byte count */
+	init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);	/* buffer start */
+	init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);	/* buffer end */
+	init_reg_param(&reg_params[3], "r3", 32, PARAM_IN_OUT);	/* target address */
+
+	buf_set_u32(reg_params[0].value, 0, 32, bytes);
+	buf_set_u32(reg_params[1].value, 0, 32, source->address);
+	buf_set_u32(reg_params[2].value, 0, 32, source->address + source->size);
+	buf_set_u32(reg_params[3].value, 0, 32, address);
+
+	retval = target_run_flash_async_algorithm(target, buffer, bytes/4, 4,
+			0, NULL,
+			4, reg_params,
+			source->address, source->size,
+			write_algorithm->address, 0,
+			&armv7m_info);
+
+	target_free_working_area(target, source);
+	target_free_working_area(target, write_algorithm);
+
+	destroy_reg_param(&reg_params[0]);
+	destroy_reg_param(&reg_params[1]);
+	destroy_reg_param(&reg_params[2]);
+	destroy_reg_param(&reg_params[3]);
+
+	return retval;
+}
+
+/* Check and erase flash sectors in specified range, then start a low level page write.
+   start/end must be sector aligned.
+*/
+static int nrf52_write_pages(struct flash_bank *bank, uint32_t start, uint32_t end, const uint8_t *buffer)
+{
+	int res;
+	uint32_t offset;
+	struct flash_sector *sector;
+	struct nrf52_info *chip = bank->driver_priv;
+	assert(chip != NULL);
+
+	assert(start % chip->code_page_size == 0);
+	assert(end % chip->code_page_size == 0);
+
+	/* Erase all sectors */
+	for (offset = start; offset < end; offset += chip->code_page_size) {
+		sector = nrf52_find_sector_by_address(bank, offset);
+
+		if (sector == NULL) {
+			LOG_ERROR("Invalid sector @ 0x%08"PRIx32, offset);
+			return ERROR_FLASH_SECTOR_INVALID;
+		}
+
+		if (sector->is_protected == 1) {
+			LOG_ERROR("Can't erase protected sector @ 0x%08"PRIx32, offset);
+			return ERROR_FAIL;
+		}
+
+		if (sector->is_erased != 1) {	/* 1 = erased, 0= not erased, -1 = unknown */
+			res = nrf52_erase_page(bank, chip, sector);
+			if (res != ERROR_OK) {
+				LOG_ERROR("Failed to erase sector @ 0x%08"PRIx32, sector->offset);
+				return res;
+			}
+		}
+		sector->is_erased = 1;
+	}
+
+	res = nrf52_nvmc_write_enable(chip);
+	if (res != ERROR_OK)
+		return res;
+
+	res = nrf52_ll_flash_write(chip, start, buffer, (end - start));
+	if (res != ERROR_OK) {
+		LOG_ERROR("Failed to write FLASH");
+		nrf52_nvmc_read_only(chip);
+		return res;
+	}
+
+	return nrf52_nvmc_read_only(chip);
+}
+
+static int nrf52_erase(struct flash_bank *bank, int first, int last)
+{
+	int res = ERROR_OK;
+	struct nrf52_info *chip = bank->driver_priv;
+	assert(chip != NULL);
+
+	/* For each sector to be erased */
+	for (int s = first; s <= last && res == ERROR_OK; s++)
+		res = nrf52_erase_page(bank, chip, &bank->sectors[s]);
+
+	return res;
+}
+
+static int nrf52_code_flash_write(struct flash_bank *bank,
+								struct nrf52_info *chip,
+								const uint8_t *buffer, uint32_t offset, uint32_t count)
+{
+	int res;
+	/* Need to perform reads to fill any gaps we need to preserve in the first page,
+	   before the start of buffer, or in the last page, after the end of buffer */
+	uint32_t first_page = offset / chip->code_page_size;
+	uint32_t last_page = DIV_ROUND_UP(offset+count, chip->code_page_size);
+
+	uint32_t first_page_offset = first_page * chip->code_page_size;
+	uint32_t last_page_offset = last_page * chip->code_page_size;
+
+	LOG_DEBUG("Padding write from 0x%08"PRIx32"-0x%08"PRIx32" as 0x%08"PRIx32"-0x%08"PRIx32,
+			offset, offset+count, first_page_offset, last_page_offset);
+
+	uint32_t page_cnt = last_page - first_page;
+	uint8_t buffer_to_flash[page_cnt * chip->code_page_size];
+
+	/* Fill in any space between start of first page and start of buffer */
+	uint32_t pre = offset - first_page_offset;
+	if (pre > 0) {
+		res = target_read_memory(bank->target, first_page_offset, 1, pre, buffer_to_flash);
+		if (res != ERROR_OK)
+			return res;
+	}
+
+	/* Fill in main contents of buffer */
+	memcpy(buffer_to_flash + pre, buffer, count);
+
+	/* Fill in any space between end of buffer and end of last page */
+	uint32_t post = last_page_offset - (offset + count);
+	if (post > 0) {
+		/* Retrieve the full row contents from Flash */
+		res = target_read_memory(bank->target, offset + count, 1, post, buffer_to_flash + pre + count);
+		if (res != ERROR_OK)
+			return res;
+	}
+
+	return nrf52_write_pages(bank, first_page_offset, last_page_offset, buffer_to_flash);
+}
+
+static int nrf52_uicr_flash_write(struct flash_bank *bank,
+								struct nrf52_info *chip,
+								const uint8_t *buffer, uint32_t offset, uint32_t count)
+{
+	int res;
+	uint32_t nrf52_uicr_size = chip->code_page_size;
+	uint8_t uicr[nrf52_uicr_size];
+	struct flash_sector *sector = &bank->sectors[0];
+
+	if ((offset + count) > nrf52_uicr_size)
+		return ERROR_FAIL;
+
+	res = target_read_memory(bank->target, NRF52_UICR_BASE_ADDR, 1, nrf52_uicr_size, uicr);
+
+	if (res != ERROR_OK)
+		return res;
+
+	if (sector->is_erased != 1) {
+		res = nrf52_erase_page(bank, chip, sector);
+		if (res != ERROR_OK)
+			return res;
+	}
+
+	memcpy(&uicr[offset], buffer, count);
+
+	res = nrf52_nvmc_write_enable(chip);
+	if (res != ERROR_OK)
+		return res;
+
+	res = nrf52_ll_flash_write(chip, NRF52_UICR_BASE_ADDR, uicr, nrf52_uicr_size);
+	if (res != ERROR_OK) {
+		nrf52_nvmc_read_only(chip);
+		return res;
+	}
+
+	return nrf52_nvmc_read_only(chip);
+}
+
+
+static int nrf52_write(struct flash_bank *bank, const uint8_t *buffer,
+					uint32_t offset, uint32_t count)
+{
+	struct nrf52_info *chip = bank->driver_priv;
+	assert(chip != NULL);
+
+	return chip->bank[bank->bank_number].write(bank, chip, buffer, offset, count);
+}
+
+
+FLASH_BANK_COMMAND_HANDLER(nrf52_flash_bank_command)
+{
+	static struct nrf52_info *chip;
+
+	assert(bank != NULL);
+
+	switch (bank->base) {
+	case NRF52_FLASH_BASE_ADDR:
+		bank->bank_number = 0;
+		break;
+	case NRF52_UICR_BASE_ADDR:
+		bank->bank_number = 1;
+		break;
+	default:
+		LOG_ERROR("Invalid bank address 0x%08" PRIx32, bank->base);
+		return ERROR_FAIL;
+	}
+
+	if (!chip) {
+		/* Create a new chip */
+		chip = calloc(1, sizeof(*chip));
+		assert(chip != NULL);
+
+		chip->target = bank->target;
+	}
+
+	switch (bank->base) {
+	case NRF52_FLASH_BASE_ADDR:
+		chip->bank[bank->bank_number].write = nrf52_code_flash_write;
+		break;
+	case NRF52_UICR_BASE_ADDR:
+		chip->bank[bank->bank_number].write = nrf52_uicr_flash_write;
+		break;
+	}
+
+	chip->bank[bank->bank_number].probed = false;
+	bank->driver_priv = chip;
+
+	return ERROR_OK;
+}
+
+COMMAND_HANDLER(nrf52_handle_mass_erase_command)
+{
+	int res;
+	struct flash_bank *bank = NULL;
+	struct target *target = get_current_target(CMD_CTX);
+
+	res = get_flash_bank_by_addr(target, NRF52_FLASH_BASE_ADDR, true, &bank);
+	if (res != ERROR_OK)
+		return res;
+
+	assert(bank != NULL);
+
+	struct nrf52_info *chip = bank->driver_priv;
+	assert(chip != NULL);
+
+	res = nrf52_erase_all(chip);
+	if (res != ERROR_OK) {
+		LOG_ERROR("Failed to erase the chip");
+		nrf52_protect_check(bank);
+		return res;
+	}
+
+	for (int i = 0; i < bank->num_sectors; i++)
+		bank->sectors[i].is_erased = 1;
+
+	res = nrf52_protect_check(bank);
+	if (res != ERROR_OK) {
+		LOG_ERROR("Failed to check chip's write protection");
+		return res;
+	}
+
+	res = get_flash_bank_by_addr(target, NRF52_UICR_BASE_ADDR, true, &bank);
+	if (res != ERROR_OK)
+		return res;
+
+	bank->sectors[0].is_erased = 1;
+
+	return ERROR_OK;
+}
+
+static int nrf52_info(struct flash_bank *bank, char *buf, int buf_size)
+{
+	int res;
+	uint32_t ficr[2];
+	struct nrf52_info *chip = bank->driver_priv;
+	assert(chip != NULL);
+
+	res = target_read_u32(chip->target, NRF52_FICR_CODEPAGESIZE_ADDR, &ficr[0]);
+		if (res != ERROR_OK) {
+			LOG_ERROR("Couldn't read NVMC_READY register");
+			return res;
+		}
+
+	res = target_read_u32(chip->target, NRF52_FICR_CODESIZE_ADDR, &ficr[1]);
+		if (res != ERROR_OK) {
+			LOG_ERROR("Couldn't read NVMC_READY register");
+			return res;
+		}
+
+	snprintf(buf, buf_size,
+			"\n--------nRF52 Series Device--------\n\n"
+			"\n[factory information control block]\n"
+			"code page size: %"PRIu32"B\n"
+			"code memory size: %"PRIu32"kB\n",
+			ficr[0],
+			(ficr[1] * ficr[0]) / 1024);
+
+	return ERROR_OK;
+}
+
+static const struct command_registration nrf52_exec_command_handlers[] = {
+	{
+		.name		= "mass_erase",
+		.handler	= nrf52_handle_mass_erase_command,
+		.mode		= COMMAND_EXEC,
+		.help		= "Erase all flash contents of the chip.",
+	},
+	COMMAND_REGISTRATION_DONE
+};
+
+static const struct command_registration nrf52_command_handlers[] = {
+	{
+		.name	= "nrf52",
+		.mode	= COMMAND_ANY,
+		.help	= "nrf52 flash command group",
+		.usage	= "",
+		.chain	= nrf52_exec_command_handlers,
+	},
+	COMMAND_REGISTRATION_DONE
+};
+
+struct flash_driver nrf52_flash = {
+	.name			= "nrf52",
+	.commands		= nrf52_command_handlers,
+	.flash_bank_command	= nrf52_flash_bank_command,
+	.info			= nrf52_info,
+	.erase			= nrf52_erase,
+	.protect		= nrf52_protect,
+	.write			= nrf52_write,
+	.read			= default_flash_read,
+	.probe			= nrf52_probe,
+	.auto_probe		= nrf52_auto_probe,
+	.erase_check	= default_flash_blank_check,
+	.protect_check	= nrf52_protect_check,
+};
diff --git a/tcl/target/nrf52.cfg b/tcl/target/nrf52.cfg
index c1cbf1a..41a22ff 100644
--- a/tcl/target/nrf52.cfg
+++ b/tcl/target/nrf52.cfg
@@ -10,6 +10,13 @@ if { [info exists CHIPNAME] } {
 	set _CHIPNAME nrf52
 }

+# Work-area is a space in RAM used for flash programming, by default use 16kB.
+if { [info exists WORKAREASIZE] } {
+        set _WORKAREASIZE $WORKAREASIZE
+} else {
+        set _WORKAREASIZE 0x4000
+}
+
 if { [info exists CPUTAPID] } {
 	set _CPUTAPID $CPUTAPID
 } else {
@@ -22,7 +29,15 @@ set _TARGETNAME $_CHIPNAME.cpu
 target create $_TARGETNAME cortex_m -chain-position $_TARGETNAME

 adapter_khz 10000
+$_TARGETNAME configure -work-area-phys 0x20000000 -work-area-size $_WORKAREASIZE -work-area-backup 0

 if { ![using_hla] } {
 	cortex_m reset_config sysresetreq
 }
+
+flash bank $_CHIPNAME.flash nrf52 0x00000000 0 1 1 $_TARGETNAME
+flash bank $_CHIPNAME.uicr nrf52 0x10001000 0 1 1 $_TARGETNAME
+
+adapter_khz 1000
+
+$_TARGETNAME configure -event reset-end {}


code:
From 9b5f70b93e038df5446bd37a4adac5a0380748e7 Mon Sep 17 00:00:00 2001
From: johannes <johannes.brechtmann@gmail.com>
Date: Wed, 21 Feb 2018 23:57:11 +0100
Subject: [PATCH] crypt_checkpass: include HAVE_CRYPT_H definition, add NULL
 check

---
 openbsd-compat/crypt_checkpass.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/openbsd-compat/crypt_checkpass.c b/openbsd-compat/crypt_checkpass.c
index dafd2dae..d10b3a57 100644
--- a/openbsd-compat/crypt_checkpass.c
+++ b/openbsd-compat/crypt_checkpass.c
@@ -1,5 +1,6 @@
 /* OPENBSD ORIGINAL: lib/libc/crypt/cryptutil.c */

+#include "includes.h"
 #include <errno.h>
 #ifdef HAVE_CRYPT_H
 #include <crypt.h>
@@ -10,6 +11,8 @@
 int
 crypt_checkpass(const char *pass, const char *goodhash)
 {
+	char *c;
+
 	if (goodhash == NULL)
 		goto fail;

@@ -17,7 +20,11 @@ crypt_checkpass(const char *pass, const char *goodhash)
 	if (strlen(goodhash) == 0 && strlen(pass) == 0)
 		return 0;

-	if (strcmp(crypt(pass, goodhash), goodhash) == 0)
+	c = crypt(pass, goodhash);
+	if (c == NULL)
+		goto fail;
+
+	if (strcmp(c, goodhash) == 0)
 		return 0;

 fail:


code:
Fix CVE-2018-0495:

https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-0495
https://www.nccgroup.trust/us/our-research/technical-advisory-return-of-the-hidden-number-problem/

Patch copied from upstream source repository:

https://github.com/openssl/openssl/commit/949ff36623eafc3523a9f91784992965018ffb05

From 949ff36623eafc3523a9f91784992965018ffb05 Mon Sep 17 00:00:00 2001
From: Matt Caswell <matt@openssl.org>
Date: Fri, 25 May 2018 12:10:13 +0100
Subject: [PATCH] Add blinding to an ECDSA signature

Keegan Ryan (NCC Group) has demonstrated a side channel attack on an
ECDSA signature operation. During signing the signer calculates:

s:= k^-1 * (m + r * priv_key) mod order

The addition operation above provides a sufficient signal for a
flush+reload attack to derive the private key given sufficient signature
operations.

As a mitigation (based on a suggestion from Keegan) we add blinding to
the operation so that:

s := k^-1 * blind^-1 (blind * m + blind * r * priv_key) mod order

Since this attack is a localhost side channel only no CVE is assigned.

Reviewed-by: Rich Salz <rsalz@openssl.org>
---
 CHANGES                  |  4 ++
 crypto/ecdsa/ecdsatest.c |  9 ++++-
 crypto/ecdsa/ecs_ossl.c  | 82 ++++++++++++++++++++++++++++++++--------
 3 files changed, 79 insertions(+), 16 deletions(-)

diff --git a/crypto/ecdsa/ecdsatest.c b/crypto/ecdsa/ecdsatest.c
index 0f301f86d9..a130fc9117 100644
--- a/crypto/ecdsa/ecdsatest.c
+++ b/crypto/ecdsa/ecdsatest.c
@@ -137,7 +137,7 @@ int restore_rand(void)
         return 1;
 }

-static int fbytes_counter = 0;
+static int fbytes_counter = 0, use_fake = 0;
 static const char *numbers[8] = {
     "651056770906015076056810763456358567190100156695615665659",
     "6140507067065001063065065565667405560006161556565665656654",
@@ -158,6 +158,11 @@ int fbytes(unsigned char *buf, int num)
     int ret;
     BIGNUM *tmp = NULL;

+    if (use_fake == 0)
+        return old_rand->bytes(buf, num);
+
+    use_fake = 0;
+
     if (fbytes_counter >= 8)
         return 0;
     tmp = BN_new();
@@ -199,11 +204,13 @@ int x9_62_test_internal(BIO *out, int nid, const char *r_in, const char *s_in)
     /* create the key */
     if ((key = EC_KEY_new_by_curve_name(nid)) == NULL)
         goto x962_int_err;
+    use_fake = 1;
     if (!EC_KEY_generate_key(key))
         goto x962_int_err;
     BIO_printf(out, ".");
     (void)BIO_flush(out);
     /* create the signature */
+    use_fake = 1;
     signature = ECDSA_do_sign(digest, 20, key);
     if (signature == NULL)
         goto x962_int_err;
diff --git a/crypto/ecdsa/ecs_ossl.c b/crypto/ecdsa/ecs_ossl.c
index 16d4f59b9b..1d37551803 100644
--- a/crypto/ecdsa/ecs_ossl.c
+++ b/crypto/ecdsa/ecs_ossl.c
@@ -252,6 +252,7 @@ static ECDSA_SIG *ecdsa_do_sign(const unsigned char *dgst, int dgst_len,
 {
     int ok = 0, i;
     BIGNUM *kinv = NULL, *s, *m = NULL, *tmp = NULL, *order = NULL;
+    BIGNUM *blind = NULL, *blindm = NULL;
     const BIGNUM *ckinv;
     BN_CTX *ctx = NULL;
     const EC_GROUP *group;
@@ -269,14 +270,25 @@ static ECDSA_SIG *ecdsa_do_sign(const unsigned char *dgst, int dgst_len,
     }

     ret = ECDSA_SIG_new();
-    if (!ret) {
+    if (ret == NULL) {
         ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_MALLOC_FAILURE);
         return NULL;
     }
     s = ret->s;

-    if ((ctx = BN_CTX_new()) == NULL || (order = BN_new()) == NULL ||
-        (tmp = BN_new()) == NULL || (m = BN_new()) == NULL) {
+    ctx = BN_CTX_new();
+    if (ctx == NULL) {
+        ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_MALLOC_FAILURE);
+        goto err;
+    }
+
+    BN_CTX_start(ctx);
+    order = BN_CTX_get(ctx);
+    tmp = BN_CTX_get(ctx);
+    m = BN_CTX_get(ctx);
+    blind = BN_CTX_get(ctx);
+    blindm = BN_CTX_get(ctx);
+    if (blindm == NULL) {
         ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_MALLOC_FAILURE);
         goto err;
     }
@@ -315,26 +327,70 @@ static ECDSA_SIG *ecdsa_do_sign(const unsigned char *dgst, int dgst_len,
             }
         }

-        if (!BN_mod_mul(tmp, priv_key, ret->r, order, ctx)) {
+        /*
+         * The normal signature calculation is:
+         *
+         *   s := k^-1 * (m + r * priv_key) mod order
+         *
+         * We will blind this to protect against side channel attacks
+         *
+         *   s := k^-1 * blind^-1 * (blind * m + blind * r * priv_key) mod order
+         */
+
+        /* Generate a blinding value */
+        do {
+            if (!BN_rand(blind, BN_num_bits(order) - 1, -1, 0))
+                goto err;
+        } while (BN_is_zero(blind));
+        BN_set_flags(blind, BN_FLG_CONSTTIME);
+        BN_set_flags(blindm, BN_FLG_CONSTTIME);
+        BN_set_flags(tmp, BN_FLG_CONSTTIME);
+
+        /* tmp := blind * priv_key * r mod order */
+        if (!BN_mod_mul(tmp, blind, priv_key, order, ctx)) {
+            ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
+            goto err;
+        }
+        if (!BN_mod_mul(tmp, tmp, ret->r, order, ctx)) {
+            ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
+            goto err;
+        }
+
+        /* blindm := blind * m mod order */
+        if (!BN_mod_mul(blindm, blind, m, order, ctx)) {
+            ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
+            goto err;
+        }
+
+        /* s : = (blind * priv_key * r) + (blind * m) mod order */
+        if (!BN_mod_add_quick(s, tmp, blindm, order)) {
+            ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
+            goto err;
+        }
+
+        /* s:= s * blind^-1 mod order */
+        if (BN_mod_inverse(blind, blind, order, ctx) == NULL) {
             ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
             goto err;
         }
-        if (!BN_mod_add_quick(s, tmp, m, order)) {
+        if (!BN_mod_mul(s, s, blind, order, ctx)) {
             ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
             goto err;
         }
+
+        /* s := s * k^-1 mod order */
         if (!BN_mod_mul(s, s, ckinv, order, ctx)) {
             ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
             goto err;
         }
+
         if (BN_is_zero(s)) {
             /*
              * if kinv and r have been supplied by the caller don't to
              * generate new kinv and r values
              */
             if (in_kinv != NULL && in_r != NULL) {
-                ECDSAerr(ECDSA_F_ECDSA_DO_SIGN,
-                         ECDSA_R_NEED_NEW_SETUP_VALUES);
+                ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ECDSA_R_NEED_NEW_SETUP_VALUES);
                 goto err;
             }
         } else
@@ -349,15 +405,11 @@ static ECDSA_SIG *ecdsa_do_sign(const unsigned char *dgst, int dgst_len,
         ECDSA_SIG_free(ret);
         ret = NULL;
     }
-    if (ctx)
+    if (ctx != NULL) {
+        BN_CTX_end(ctx);
         BN_CTX_free(ctx);
-    if (m)
-        BN_clear_free(m);
-    if (tmp)
-        BN_clear_free(tmp);
-    if (order)
-        BN_free(order);
-    if (kinv)
+    }
+    if (kinv != NULL)
         BN_clear_free(kinv);
     return ret;
 }
--
2.17.1


code:
Fix CVE-2018-0732:

https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-0732

Patch copied from upstream source repository:

https://github.com/openssl/openssl/commit/3984ef0b72831da8b3ece4745cac4f8575b19098

From 3984ef0b72831da8b3ece4745cac4f8575b19098 Mon Sep 17 00:00:00 2001
From: Guido Vranken <guidovranken@gmail.com>
Date: Mon, 11 Jun 2018 19:38:54 +0200
Subject: [PATCH] Reject excessively large primes in DH key generation.

CVE-2018-0732

Signed-off-by: Guido Vranken <guidovranken@gmail.com>

(cherry picked from commit 91f7361f47b082ae61ffe1a7b17bb2adf213c7fe)

Reviewed-by: Tim Hudson <tjh@openssl.org>
Reviewed-by: Matt Caswell <matt@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/6457)
---
 crypto/dh/dh_key.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/crypto/dh/dh_key.c b/crypto/dh/dh_key.c
index 387558f146..f235e0d682 100644
--- a/crypto/dh/dh_key.c
+++ b/crypto/dh/dh_key.c
@@ -130,10 +130,15 @@ static int generate_key(DH *dh)
     int ok = 0;
     int generate_new_key = 0;
     unsigned l;
-    BN_CTX *ctx;
+    BN_CTX *ctx = NULL;
     BN_MONT_CTX *mont = NULL;
     BIGNUM *pub_key = NULL, *priv_key = NULL;

+    if (BN_num_bits(dh->p) > OPENSSL_DH_MAX_MODULUS_BITS) {
+        DHerr(DH_F_GENERATE_KEY, DH_R_MODULUS_TOO_LARGE);
+        return 0;
+    }
+
     ctx = BN_CTX_new();
     if (ctx == NULL)
         goto err;
--
2.17.1


code:
This patch removes the explicit reference to the 'perl' binary,
such that OpenSSL does not retain a reference to Perl.

The 'c_rehash' program is seldom used, but it is used nonetheless
to create symbolic links to certificates, for instance in the 'nss-certs'
package.

diff --git a/tools/c_rehash.in b/tools/c_rehash.in
index 421fd89208..93aca4e168 100644
--- a/tools/c_rehash.in
+++ b/tools/c_rehash.in
@@ -1,4 +1,6 @@
-#!{- $config{HASHBANGPERL} -}
+eval '(exit $?0)' && eval 'exec perl -wS "$0" ${1+"$@"}'
+  & eval 'exec perl -wS "$0" $argv:q'
+    if 0;

 # {- join("\n# ", @autowarntext) -}
 # Copyright 1999-2018 The OpenSSL Project Authors. All Rights Reserved.


code:
This patch removes the explicit reference to the 'perl' binary,
such that OpenSSL does not retain a reference to Perl.

The 'c_rehash' program is seldom used, but it is used nonetheless
to create symbolic links to certificates, for instance in the 'nss-certs'
package.

--- openssl-1.0.2g/tools/c_rehash.in	2015-09-09 18:36:07.313316482 +0200
+++ openssl-1.0.2g/tools/c_rehash.in	2015-09-09 18:36:28.965458458 +0200
@@ -1,4 +1,6 @@
-#!/usr/local/bin/perl
+eval '(exit $?0)' && eval 'exec perl -wS "$0" ${1+"$@"}'
+  & eval 'exec perl -wS "$0" $argv:q'
+    if 0;

 # Perl c_rehash script, scan all files in a directory
 # and add symbolic links to their hash values.


code:
This patch makes the build system pass -Wl,-rpath=$out/lib even for
libraries (it already does so for executables, thanks to 'DO_GNU_APP'
in 'Makefile.shared'.)

--- openssl-1.0.2a/Makefile.shared	2015-04-05 01:07:35.357602454 +0200
+++ openssl-1.0.2a/Makefile.shared	2015-04-05 01:09:50.474513303 +0200
@@ -106,7 +106,7 @@ LINK_SO=	\
     LIBPATH=`for x in $$LIBDEPS; do echo $$x; done | sed -e 's/^ *-L//;t' -e d | uniq`; \
     LIBPATH=`echo $$LIBPATH | sed -e 's/ /:/g'`; \
     LD_LIBRARY_PATH=$$LIBPATH:$$LD_LIBRARY_PATH \
-    $${SHAREDCMD} $${SHAREDFLAGS} \
+    $${SHAREDCMD} $${SHAREDFLAGS} -Wl,-rpath,$(LIBRPATH) \
 	-o $$SHLIB$$SHLIB_SOVER$$SHLIB_SUFFIX \
 	$$ALLSYMSFLAGS $$SHOBJECTS $$NOALLSYMSFLAGS $$LIBDEPS \
   ) && $(SYMLINK_SO)


code:
The 'intcompare' definition was causing a "cast from 'void*' to 'int' loses
precision [-fpermissive]" error.  It isn't used anywhere, so simply remove it.
Same with 'findint' in texteditor.cc.

Fix other "cast from ‘void*’ to ‘int’ loses precision" errors.

--- a/kkstrtext-0.1/kkstrtext.cc	2005-01-31 18:13:24.000000000 -0600
+++ b/kkstrtext-0.1/kkstrtext.cc	2014-07-24 00:25:07.149305476 -0500
@@ -430,10 +430,6 @@
     }
 }

-int intcompare(void *s1, void *s2) {
-    return (int) s1 != (int) s2;
-}
-
 string i2str(int i) {
     char buf[64];
     sprintf(buf, "%d", i);
@@ -885,7 +881,7 @@
 #ifdef HAVE_ICONV
     iconv_t cd = iconv_open(tocs.c_str(), fromcs.c_str());

-    if(((int) cd) != -1) {
+    if(cd != (iconv_t) -1) {
 	string r, text(atext);
 	size_t inleft, outleft, soutleft;
 	char *inbuf, *outbuf, *sinbuf, *soutbuf;
--- a/kkconsui-0.1/src/texteditor.cc	2003-09-09 16:51:33.000000000 -0500
+++ b/kkconsui-0.1/src/texteditor.cc	2014-07-24 00:33:20.093279060 -0500
@@ -1939,10 +1939,6 @@
     if(ur) delete ur;
 }

-int texteditor::findint(void *p1, void *p2) {
-    return *(int *) p1 != (int) p2;
-}
-
 int texteditor::findhighline(void *p1, void *p2) {
     return *(int *) p1 != ((highline *) p2)->line;
 }
--- a/src/streamtrack.cc	2006-05-11 12:45:20.000000000 -0500
+++ b/src/streamtrack.cc	2014-07-24 00:38:10.797263482 -0500
@@ -34,6 +34,7 @@
 #include <sys/wait.h>
 #include <sys/stat.h>
 #include <signal.h>
+#include <unistd.h>

 #include <algorithm>