Silence warnings about redefining popen on Mingw-w64.

Mingw-w64 headers map popen/pclose to _popen and _pclose, but we want to use
our popen wrapper rather than the Mingw-w64. #undef the Mingw's version.
Misc message style and doc fixes.

Euler Taveira
Fix race condition in preparing a transaction for two-phase commit.

To lock a prepared transaction's shared memory entry, we used to mark it
with the XID of the backend. When the XID was no longer active according
to the proc array, the entry was implicitly considered as not locked
anymore. However, when preparing a transaction, the backend's proc array
entry was cleared before transfering the locks (and some other state) to
the prepared transaction's dummy PGPROC entry, so there was a window where
another backend could finish the transaction before it was in fact fully
prepared.

To fix, rewrite the locking mechanism of global transaction entries. Instead
of an XID, just have simple locked-or-not flag in each entry (we store the
locking backend's backend id rather than a simple boolean, but that's just
for debugging purposes). The backend is responsible for explicitly unlocking
the entry, and to make sure that that happens, install a callback to unlock
it on abort or process exit.

Backpatch to all supported versions.
Handle duplicate XIDs in txid_snapshot.

The proc array can contain duplicate XIDs, when a transaction is just being
prepared for two-phase commit. To cope, remove any duplicates in
txid_current_snapshot(). Also ignore duplicates in the input functions, so
that if e.g. you have an old pg_dump file that already contains duplicates,
it will be accepted.

Report and fix by Jan Wieck. Backpatch to all supported versions.
Fix a couple of bugs in pg_recvlogical output to stdout.

Don't close stdout on SIGHUP. Also, when a SIGHUP is received, close the
file immediately, rather than only after receiving some more data from
the server. Rename a variable, to avoid mentally dealing with double
negatives (not unsynced means synced).
Fix whitespace
Fix unportable setvbuf() usage in initdb.

In yesterday's commit 2dc4f011fd61501cce507be78c39a2677690d44b, I tried
to force buffering of stdout/stderr in initdb to be what it is by
default when the program is run interactively on Unix (since that's how
most manual testing is done).  This tripped over the fact that Windows
doesn't support _IOLBF mode.  We dealt with that a long time ago in
syslogger.c by falling back to unbuffered mode on Windows.  Export that
solution in port.h and use it in initdb.

Back-patch to 8.4, like the previous commit.
Initialize tsId and dbId fields in WAL record of COMMIT PREPARED.

Commit dd428c79 added dbId and tsId to the xl_xact_commit struct but missed
that prepared transaction commits reuse that struct. Fix that.

Because those fields were left unitialized, replaying a commit prepared WAL
record in a hot standby node would fail to remove the relcache init file.
That can lead to "could not open file" errors on the standby. Relcache init
file only needs to be removed when a system table/index is rewritten in the
transaction using two phase commit, so that should be rare in practice. In
HEAD, the incorrect dbId/tsId values are also used for filtering in logical
replication code, causing the transaction to always be filtered out.

Analysis and fix by Andres Freund. Backpatch to 9.0 where hot standby was
introduced.
Open output file before sleeping in pg_recvlogical.

Let's complain about e.g an invalid path or permission problem sooner rather
than later. Before this patch, we would only try to open the output file
after receiving the first decoded message from the server.
Fix thinko in logical decoding of commit-prepared records.

The decoding of prepared transaction commits accidentally used the XID of
the transaction performing the COMMIT PREPARED, not the XID of the prepared
transaction. Before bb38fb0d43c8d that lead to those transactions not being
decoded, afterwards to a assertion failure.
Fix test_decoding test case's check that slot has been dropped.

pg_stat_replication shows connected replication clients. The ddl test case
never has any replication clients connected, so querying pg_stat_replication
is pointless. To check that a slot has been dropped correctly, query
pg_replication_slots instead.

Andres Freund
Add test case for logical decoding of prepared transactions.

Andres Freund
Fix valgrind warning for btree_gist indexes on macaddr.

The macaddr opclass stores two macaddr structs (each of size 6) in an
index column that's declared as being of type gbtreekey16, ie 16 bytes.
In the original coding this led to passing a palloc'd value of size 12
to the index insertion code, so that data would be fetched past the
end of the allocated value during index tuple construction.  This makes
valgrind unhappy.  In principle it could result in a SIGSEGV, though
with the current implementation of palloc there's no risk since
the 12-byte request size would be rounded up to 16 bytes anyway.

To fix, add a field to struct gbtree_ninfo showing the declared size of
the index datums, and use that in the palloc requests; and use palloc0
to be sure that any wasted bytes are cleanly initialized.

Per report from Andres Freund.  No back-patch since there's no current
risk of a real problem.
Fix a second cause of undersized pallocs for btree_gist indexes on macaddr.

gbt_macad_union also allocated 12-byte structs where we really need 16.

Per report from Andres Freund.  No back-patch since there's no current
risk of a real problem.
Suppress some more valgrind whining about btree_gist.

A couple of functions didn't bother to zero out pad bytes in datums that
would ultimately go to disk.  Harmless, but valgrind doesn't know that.
Make sure chr(int) can't create invalid UTF8 sequences.

Several years ago we changed chr(int) so that if the database encoding is
UTF8, it would interpret its argument as a Unicode code point and expand it
into the appropriate multibyte sequence.  However, we weren't sufficiently
careful about checking validity of the input.  According to RFC3629, UTF8
disallows code points above U+10FFFF (note that the predecessor standard
RFC2279 was more liberal).  Also, both versions of the UTF8 spec agree
that Unicode surrogate-pair codes should never appear in UTF8.  Because
our encoding validity checks follow RFC3629, our failure to enforce these
restrictions in chr() means it could be used to produce text strings that
will be rejected when the database is dumped and reloaded.  To ensure
consistency with the input functions, let's actually apply
pg_utf8_islegal() to the proposed output of chr().

Per discussion, this seems like too much of a behavioral change to
back-patch, but it's not too late to squeeze it into 9.4.
Update README, we don't do post-recovery cleanup actions anymore.

transam/README explained how B-tree incomplete splits were tracked and
fixed after recovery, as an example of handling complex actions that need
multiple WAL records, but that's not how it works anymore. Explain the new
paradigm.
Fix unaligned accesses in DecodeUpdate().

The xl_heap_header_len structures in an XLOG_HEAP_UPDATE record aren't
necessarily aligned adequately.  The regular replay function for these
records is aware of that, but decode.c didn't get the memo.  I'm not
sure why the buildfarm failed to catch this; the test_decoding test
certainly blows up real good on my old HPPA box.

Also, I'm pretty sure that the address arithmetic was wrong for the
case of XLOG_HEAP_CONTAINS_OLD and not XLOG_HEAP_CONTAINS_NEW_TUPLE,
though this apparently can't happen when logical decoding is active.
Fix a bunch of functions that were declared static then defined not-static.

Per testing with a compiler that whines about this.
Make fallback implementation of pg_memory_barrier() work.

The fallback implementation involves acquiring and releasing a spinlock
variable that is otherwise unreferenced --- not even to the extent of
initializing it.  This accidentally fails to fail on platforms where
spinlocks should be initialized to zeroes, but elsewhere it results in
a "stuck spinlock" failure during startup.

I griped about this last July, and put in a hack that worked for gcc
on HPPA, but didn't get around to fixing the general case.  Per the
discussion back then, the best thing to do seems to be to initialize
dummy_spinlock in main.c.