post-1.16.1 fixes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
diff --git a/archival/cpio.c b/archival/cpio.c
index 858e59b..2698f07 100644
--- a/archival/cpio.c
+++ b/archival/cpio.c
@@ -424,7 +424,7 @@
 	if (archive_handle->cpio__blocks != (off_t)-1
 	 && !(opt & CPIO_OPT_QUIET)
 	) {
-		printf("%"OFF_FMT"u blocks\n", archive_handle->cpio__blocks);
+		fprintf(stderr, "%"OFF_FMT"u blocks\n", archive_handle->cpio__blocks);
 	}
 
 	return EXIT_SUCCESS;
diff --git a/editors/sed.c b/editors/sed.c
index fd9dd1b..4289aa6 100644
--- a/editors/sed.c
+++ b/editors/sed.c
@@ -487,7 +487,7 @@
 static void add_cmd(const char *cmdstr)
 {
 	sed_cmd_t *sed_cmd;
-	int temp;
+	unsigned len, n;
 
 	/* Append this line to any unfinished line from last time. */
 	if (G.add_cmd_line) {
@@ -496,12 +496,14 @@
 		cmdstr = G.add_cmd_line = tp;
 	}
 
-	/* If this line ends with backslash, request next line. */
-	temp = strlen(cmdstr);
-	if (temp && cmdstr[--temp] == '\\') {
+	/* If this line ends with unescaped backslash, request next line. */
+	n = len = strlen(cmdstr);
+	while (n && cmdstr[n-1] == '\\')
+		n--;
+	if ((len - n) & 1) { /* if odd number of trailing backslashes */
 		if (!G.add_cmd_line)
 			G.add_cmd_line = xstrdup(cmdstr);
-		G.add_cmd_line[temp] = '\0';
+		G.add_cmd_line[len-1] = '\0';
 		return;
 	}
 
@@ -936,7 +938,15 @@
 		/* Skip blocks of commands we didn't match */
 		if (sed_cmd->cmd == '{') {
 			if (sed_cmd->invert ? matched : !matched) {
-				while (sed_cmd->cmd != '}') {
+				unsigned nest_cnt = 0;
+				while (1) {
+					if (sed_cmd->cmd == '{')
+						nest_cnt++;
+					if (sed_cmd->cmd == '}') {
+						nest_cnt--;
+						if (nest_cnt == 0)
+							break;
+					}
 					sed_cmd = sed_cmd->next;
 					if (!sed_cmd)
 						bb_error_msg_and_die("unterminated {");
@@ -1031,7 +1041,7 @@
 		case 'c':
 			/* Only triggers on last line of a matching range. */
 			if (!sed_cmd->in_match)
-				sed_puts(sed_cmd->string, NO_EOL_CHAR);
+				sed_puts(sed_cmd->string, '\n');
 			goto discard_line;
 
 		/* Read file, append contents to output */
diff --git a/include/platform.h b/include/platform.h
index a41daa0..804fab4 100644
--- a/include/platform.h
+++ b/include/platform.h
@@ -291,10 +291,12 @@
 #if 1 /* if needed: !defined(arch1) && !defined(arch2) */
 # define ALIGN1 __attribute__((aligned(1)))
 # define ALIGN2 __attribute__((aligned(2)))
+# define ALIGN4 __attribute__((aligned(4)))
 #else
 /* Arches which MUST have 2 or 4 byte alignment for everything are here */
 # define ALIGN1
 # define ALIGN2
+# define ALIGN4
 #endif
 
 
diff --git a/networking/dnsd.c b/networking/dnsd.c
index 56ede3f..1a4ccb9 100644
--- a/networking/dnsd.c
+++ b/networking/dnsd.c
@@ -44,10 +44,15 @@
 	uint16_t nauth;
 	uint16_t nadd;
 };
+/* Structure used to access type and class fields.
+ * They are totally unaligned, but gcc 4.3.4 thinks that pointer of type uint16_t*
+ * is 16-bit aligned and replaces 16-bit memcpy (in move_from_unaligned16 macro)
+ * with aligned halfword access on arm920t!
+ * Oh well. Slapping PACKED everywhere seems to help: */
 struct dns_prop {
-	uint16_t type;
-	uint16_t class;
-};
+	uint16_t type PACKED;
+	uint16_t class PACKED;
+} PACKED;
 /* element of known name, ip address and reversed ip address */
 struct dns_entry {
 	struct dns_entry *next;
@@ -459,7 +464,8 @@
 	unsigned lsa_size;
 	int udps, opts;
 	uint16_t port = 53;
-	uint8_t buf[MAX_PACK_LEN + 1];
+	/* Ensure buf is 32bit aligned (we need 16bit, but 32bit can't hurt) */
+	uint8_t buf[MAX_PACK_LEN + 1] ALIGN4;
 
 	opts = getopt32(argv, "vi:c:t:p:d", &listen_interface, &fileconf, &sttl, &sport);
 	//if (opts & 0x1) // -v
diff --git a/networking/httpd_indexcgi.c b/networking/httpd_indexcgi.c
index 9fa7c74..af43380 100644
--- a/networking/httpd_indexcgi.c
+++ b/networking/httpd_indexcgi.c
@@ -315,7 +315,7 @@
 		if (S_ISREG(cdir->dl_mode))
 			fmt_ull(cdir->dl_size);
 		fmt_str("<td class=dt>");
-		tm = gmtime(&cdir->dl_mtime);
+		ptm = gmtime(&cdir->dl_mtime);
 		fmt_04u(1900 + ptm->tm_year); *dst++ = '-';
 		fmt_02u(ptm->tm_mon + 1); *dst++ = '-';
 		fmt_02u(ptm->tm_mday); *dst++ = ' ';
diff --git a/networking/udhcp/leases.c b/networking/udhcp/leases.c
index 78b0d0a..7b6bb20 100644
--- a/networking/udhcp/leases.c
+++ b/networking/udhcp/leases.c
@@ -64,6 +64,8 @@
 		oldest->hostname[0] = '\0';
 		if (hostname) {
 			char *p;
+
+			hostname_len++; /* include NUL */
 			if (hostname_len > sizeof(oldest->hostname))
 				hostname_len = sizeof(oldest->hostname);
 			p = safe_strncpy(oldest->hostname, hostname, hostname_len);
diff --git a/shell/ash.c b/shell/ash.c
index 34f70ec..e018e87 100644
--- a/shell/ash.c
+++ b/shell/ash.c
@@ -5059,7 +5059,7 @@
 		return 0;
 	pf = g_parsefile;
 	while (pf) {
-		if (fd == pf->fd) {
+		if (pf->fd > 0 && fd == pf->fd) {
 			return 1;
 		}
 		pf = pf->prev;
@@ -5424,7 +5424,11 @@
 		size_t fulllen = len + strlen(p) + 1;
 
 		if (flag & RMESCAPE_GROW) {
+			int strloc = str - (char *)stackblock();
 			r = makestrspace(fulllen, expdest);
+			/* p and str may be invalidated by makestrspace */
+			str = (char *)stackblock() + strloc;
+			p = str + len;
 		} else if (flag & RMESCAPE_HEAP) {
 			r = ckmalloc(fulllen);
 		} else {
diff --git a/shell/hush.c b/shell/hush.c
index 2aeb8e4..78f0f79 100644
--- a/shell/hush.c
+++ b/shell/hush.c
@@ -6944,7 +6944,7 @@
 				/* -c 'script' (no params): prevent empty $0 */
 				G.global_argv--; /* points to argv[i] of 'script' */
 				G.global_argv[0] = argv[0];
-				G.global_argc--;
+				G.global_argc++;
 			} /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
 			init_sigmasks();
 			parse_and_run_string(optarg);
diff --git a/testsuite/cpio.tests b/testsuite/cpio.tests
index e53ade92..325664d 100755
--- a/testsuite/cpio.tests
+++ b/testsuite/cpio.tests
@@ -32,7 +32,7 @@
 # testing "test name" "command" "expected result" "file input" "stdin"
 
 testing "cpio extracts zero-sized hardlinks" \
-"$ECHO -ne '$hexdump' | bzcat | cpio -i; echo \$?;
+"$ECHO -ne '$hexdump' | bzcat | cpio -i 2>&1; echo \$?;
 ls -ln cpio.testdir | $FILTER_LS" \
 "\
 1 blocks
@@ -45,7 +45,7 @@
 
 test x"$SKIP_KNOWN_BUGS" = x"" && {
 # Currently fails. Numerous buglets: "1 blocks" versus "1 block",
-# "1 block" must go to stderr, does not list cpio.testdir/x and cpio.testdir/y
+# does not list cpio.testdir/x and cpio.testdir/y
 testing "cpio lists hardlinks" \
 "$ECHO -ne '$hexdump' | bzcat | cpio -t 2>&1; echo \$?" \
 "\
@@ -70,7 +70,7 @@
 mkdir cpio.testdir2
 
 testing "cpio extracts zero-sized hardlinks 2" \
-"find cpio.testdir | cpio -H newc --create | (cd cpio.testdir2 && cpio -i); echo \$?;
+"find cpio.testdir | cpio -H newc --create | (cd cpio.testdir2 && cpio -i 2>&1); echo \$?;
 ls -ln cpio.testdir2/cpio.testdir | $FILTER_LS" \
 "\
 2 blocks
@@ -87,7 +87,7 @@
 # Was trying to create "/usr/bin", correct is "usr/bin".
 rm -rf cpio.testdir
 testing "cpio -p with absolute paths" \
-"echo /usr/bin | cpio -dp cpio.testdir; echo \$?;
+"echo /usr/bin | cpio -dp cpio.testdir 2>&1; echo \$?;
 ls cpio.testdir" \
 "\
 1 blocks
diff --git a/testsuite/sed.tests b/testsuite/sed.tests
index 875c946..5b0750c 100755
--- a/testsuite/sed.tests
+++ b/testsuite/sed.tests
@@ -248,4 +248,28 @@
 	">/usr</>lib<\n" "" \
 	"/usr/lib\n"
 
+testing "sed c" \
+	"sed 'crepl'" \
+	"repl\nrepl\n" "" \
+	"first\nsecond\n"
+
+testing "sed nested {}s" \
+	"sed '/asd/ { p; /s/ { s/s/c/ }; p; q }'" \
+	"qwe\nasd\nacd\nacd\n" "" \
+	"qwe\nasd\nzxc\n"
+
+testing "sed a cmd ended by double backslash" \
+	"sed -e '/| one /a \\
+	| three \\\\' -e '/| one-/a \\
+	| three-* \\\\'" \
+'	| one \\
+	| three \\
+	| two \\
+' '' \
+'	| one \\
+	| two \\
+'
+
+# testing "description" "arguments" "result" "infile" "stdin"
+
 exit $FAILCOUNT
diff --git a/util-linux/hwclock.c b/util-linux/hwclock.c
index b830057..416271b 100644
--- a/util-linux/hwclock.c
+++ b/util-linux/hwclock.c
@@ -109,10 +109,53 @@
 
 static void from_sys_clock(const char **pp_rtcname, int utc)
 {
-#define TWEAK_USEC 200
+#if 1
+	struct timeval tv;
+	struct tm tm_time;
+	int rtc;
+
+	rtc = rtc_xopen(pp_rtcname, O_WRONLY);
+	gettimeofday(&tv, NULL);
+	/* Prepare tm_time */
+	if (sizeof(time_t) == sizeof(tv.tv_sec)) {
+		if (utc)
+			gmtime_r((time_t*)&tv.tv_sec, &tm_time);
+		else
+			localtime_r((time_t*)&tv.tv_sec, &tm_time);
+	} else {
+		time_t t = tv.tv_sec;
+		if (utc)
+			gmtime_r(&t, &tm_time);
+		else
+			localtime_r(&t, &tm_time);
+	}
+#else
+/* Bloated code which tries to set hw clock with better precision.
+ * On x86, even though code does set hw clock within <1ms of exact
+ * whole seconds, apparently hw clock (at least on some machines)
+ * doesn't reset internal fractional seconds to 0,
+ * making all this a pointless excercise.
+ */
+	/* If we see that we are N usec away from whole second,
+	 * we'll sleep for N-ADJ usecs. ADJ corrects for the fact
+	 * that CPU is not infinitely fast.
+	 * On infinitely fast CPU, next wakeup would be
+	 * on (exactly_next_whole_second - ADJ). On real CPUs,
+	 * this difference between current time and whole second
+	 * is less than ADJ (assuming system isn't heavily loaded).
+	 */
+	/* Small value of 256us gives very precise sync for 2+ GHz CPUs.
+	 * Slower CPUs will fail to sync and will go to bigger
+	 * ADJ values. qemu-emulated armv4tl with ~100 MHz
+	 * performance ends up using ADJ ~= 4*1024 and it takes
+	 * 2+ secs (2 tries with successively larger ADJ)
+	 * to sync. Even straced one on the same qemu (very slow)
+	 * takes only 4 tries.
+	 */
+#define TWEAK_USEC 256
+	unsigned adj = TWEAK_USEC;
 	struct tm tm_time;
 	struct timeval tv;
-	unsigned adj = TWEAK_USEC;
 	int rtc = rtc_xopen(pp_rtcname, O_WRONLY);
 
 	/* Try to catch the moment when whole second is close */
@@ -124,55 +167,64 @@
 
 		t = tv.tv_sec;
 		rem_usec = 1000000 - tv.tv_usec;
-		if (rem_usec < 1024) {
-			/* Less than 1ms to next second. Good enough */
+		if (rem_usec < adj) {
+			/* Close enough */
  small_rem:
 			t++;
 		}
 
-		/* Prepare tm */
+		/* Prepare tm_time from t */
 		if (utc)
 			gmtime_r(&t, &tm_time); /* may read /etc/xxx (it takes time) */
 		else
 			localtime_r(&t, &tm_time); /* same */
-		tm_time.tm_isdst = 0;
+
+		if (adj >= 32*1024) {
+			break; /* 32 ms diff and still no luck?? give up trying to sync */
+		}
 
 		/* gmtime/localtime took some time, re-get cur time */
 		gettimeofday(&tv, NULL);
 
-		if (tv.tv_sec < t /* may happen if rem_usec was < 1024 */
-		 || (tv.tv_sec == t && tv.tv_usec < 1024)
+		if (tv.tv_sec < t /* we are still in old second */
+		 || (tv.tv_sec == t && tv.tv_usec < adj) /* not too far into next second */
 		) {
-			/* We are not too far into next second. Good. */
-			break;
+			break; /* good, we are in sync! */
 		}
-		adj += 32; /* 2^(10-5) = 2^5 = 32 iterations max */
-		if (adj >= 1024) {
-			/* Give up trying to sync */
-			break;
+
+		rem_usec = 1000000 - tv.tv_usec;
+		if (rem_usec < adj) {
+			t = tv.tv_sec;
+			goto small_rem; /* already close to next sec, don't sleep */
 		}
 
 		/* Try to sync up by sleeping */
-		rem_usec = 1000000 - tv.tv_usec;
-		if (rem_usec < 1024) {
-			goto small_rem; /* already close, don't sleep */
-		}
-		/* Need to sleep.
-		 * Note that small adj on slow processors can make us
-		 * to always overshoot tv.tv_usec < 1024 check on next
-		 * iteration. That's why adj is increased on each iteration.
-		 * This also allows it to be reused as a loop limiter.
-		 */
 		usleep(rem_usec - adj);
+
+		/* Jump to 1ms diff, then increase fast (x2): EVERY loop
+		 * takes ~1 sec, people won't like slowly converging code here!
+		 */
+	//bb_error_msg("adj:%d tv.tv_usec:%d", adj, (int)tv.tv_usec);
+		if (adj < 512)
+			adj = 512;
+		/* ... and if last "overshoot" does not look insanely big,
+		 * just use it as adj increment. This makes convergence faster.
+		 */
+		if (tv.tv_usec < adj * 8) {
+			adj += tv.tv_usec;
+			continue;
+		}
+		adj *= 2;
 	}
-
-	xioctl(rtc, RTC_SET_TIME, &tm_time);
-
-	/* Debug aid to find "good" TWEAK_USEC.
+	/* Debug aid to find "optimal" TWEAK_USEC with nearly exact sync.
 	 * Look for a value which makes tv_usec close to 999999 or 0.
-	 * for 2.20GHz Intel Core 2: TWEAK_USEC ~= 200
+	 * For 2.20GHz Intel Core 2: optimal TWEAK_USEC ~= 200
 	 */
-	//bb_error_msg("tv.tv_usec:%d adj:%d", (int)tv.tv_usec, adj);
+	//bb_error_msg("tv.tv_usec:%d", (int)tv.tv_usec);
+#endif
+
+	tm_time.tm_isdst = 0;
+	xioctl(rtc, RTC_SET_TIME, &tm_time);
 
 	if (ENABLE_FEATURE_CLEAN_UP)
 		close(rtc);