]> granicus.if.org Git - postgresql/log
postgresql
8 years agoStamp 9.0.23. REL9_0_STABLE github/REL9_0_STABLE REL9_0_23
Tom Lane [Mon, 5 Oct 2015 19:19:44 +0000 (15:19 -0400)]
Stamp 9.0.23.

8 years agodoc: Update URLs of external projects
Peter Eisentraut [Sat, 3 Oct 2015 01:50:59 +0000 (21:50 -0400)]
doc: Update URLs of external projects

8 years agoTranslation updates
Peter Eisentraut [Mon, 5 Oct 2015 14:42:12 +0000 (10:42 -0400)]
Translation updates

Source-Git-URL: git://git.postgresql.org/git/pgtranslation/messages.git
Source-Git-Hash: e0981ce6d26309e48891d9192c69fcccd40fe7cd

8 years agoLast-minute updates for release notes.
Tom Lane [Mon, 5 Oct 2015 14:57:15 +0000 (10:57 -0400)]
Last-minute updates for release notes.

Add entries for security and not-quite-security issues.

Security: CVE-2015-5288, CVE-2015-5289

8 years agoRemove outdated comment about relation level autovacuum freeze limits.
Andres Freund [Mon, 5 Oct 2015 14:09:13 +0000 (16:09 +0200)]
Remove outdated comment about relation level autovacuum freeze limits.

The documentation for the autovacuum_multixact_freeze_max_age and
autovacuum_freeze_max_age relation level parameters contained:
"Note that while you can set autovacuum_multixact_freeze_max_age very
small, or even zero, this is usually unwise since it will force frequent
vacuuming."
which hasn't been true since these options were made relation options,
instead of residing in the pg_autovacuum table (834a6da4f7).

Remove the outdated sentence. Even the lowered limits from 2596d70 are
high enough that this doesn't warrant calling out the risk in the CREATE
TABLE docs.

Per discussion with Tom Lane and Alvaro Herrera

Discussion: 26377.1443105453@sss.pgh.pa.us
Backpatch: 9.0- (in parts)

8 years agoPrevent stack overflow in query-type functions.
Noah Misch [Mon, 5 Oct 2015 14:06:30 +0000 (10:06 -0400)]
Prevent stack overflow in query-type functions.

The tsquery, ltxtquery and query_int data types have a common ancestor.
Having acquired check_stack_depth() calls independently, each was
missing at least one call.  Back-patch to 9.0 (all supported versions).

8 years agoPrevent stack overflow in container-type functions.
Noah Misch [Mon, 5 Oct 2015 14:06:29 +0000 (10:06 -0400)]
Prevent stack overflow in container-type functions.

A range type can name another range type as its subtype, and a record
type can bear a column of another record type.  Consequently, functions
like range_cmp() and record_recv() are recursive.  Functions at risk
include operator family members and referents of pg_type regproc
columns.  Treat as recursive any such function that looks up and calls
the same-purpose function for a record column type or the range subtype.
Back-patch to 9.0 (all supported versions).

An array type's element type is never itself an array type, so array
functions are unaffected.  Recursion depth proportional to array
dimensionality, found in array_dim_to_jsonb(), is fine thanks to MAXDIM.

8 years agopgcrypto: Detect and report too-short crypt() salts.
Noah Misch [Mon, 5 Oct 2015 14:06:29 +0000 (10:06 -0400)]
pgcrypto: Detect and report too-short crypt() salts.

Certain short salts crashed the backend or disclosed a few bytes of
backend memory.  For existing salt-induced error conditions, emit a
message saying as much.  Back-patch to 9.0 (all supported versions).

Josh Kupershmidt

Security: CVE-2015-5288

8 years agoRe-Align *_freeze_max_age reloption limits with corresponding GUC limits.
Andres Freund [Mon, 5 Oct 2015 09:53:43 +0000 (11:53 +0200)]
Re-Align *_freeze_max_age reloption limits with corresponding GUC limits.

In 020235a5754 I lowered the autovacuum_*freeze_max_age minimums to
allow for easier testing of wraparounds. I did not touch the
corresponding per-table limits. While those don't matter for the purpose
of wraparound, it seems more consistent to lower them as well.

It's noteworthy that the previous reloption lower limit for
autovacuum_multixact_freeze_max_age was too high by one magnitude, even
before 020235a5754.

Discussion: 26377.1443105453@sss.pgh.pa.us
Backpatch: back to 9.0 (in parts), like the prior patch

8 years agoRelease notes for 9.5beta1, 9.4.5, 9.3.10, 9.2.14, 9.1.19, 9.0.23.
Tom Lane [Sun, 4 Oct 2015 23:38:01 +0000 (19:38 -0400)]
Release notes for 9.5beta1, 9.4.5, 9.3.10, 9.2.14, 9.1.19, 9.0.23.

8 years agoFurther twiddling of nodeHash.c hashtable sizing calculation.
Tom Lane [Sun, 4 Oct 2015 19:55:07 +0000 (15:55 -0400)]
Further twiddling of nodeHash.c hashtable sizing calculation.

On reflection, the submitted patch didn't really work to prevent the
request size from exceeding MaxAllocSize, because of the fact that we'd
happily round nbuckets up to the next power of 2 after we'd limited it to
max_pointers.  The simplest way to enforce the limit correctly is to
round max_pointers down to a power of 2 when it isn't one already.

(Note that the constraint to INT_MAX / 2, if it were doing anything useful
at all, is properly applied after that.)

8 years agoFix possible "invalid memory alloc request size" failure in nodeHash.c.
Tom Lane [Sun, 4 Oct 2015 18:16:59 +0000 (14:16 -0400)]
Fix possible "invalid memory alloc request size" failure in nodeHash.c.

Limit the size of the hashtable pointer array to not more than
MaxAllocSize.  We've seen reports of failures due to this in HEAD/9.5,
and it seems possible in older branches as well.  The change in
NTUP_PER_BUCKET in 9.5 may have made the problem more likely, but
surely it didn't introduce it.

Tomas Vondra, slightly modified by me

8 years agoUpdate time zone data files to tzdata release 2015g.
Tom Lane [Fri, 2 Oct 2015 23:15:39 +0000 (19:15 -0400)]
Update time zone data files to tzdata release 2015g.

DST law changes in Cayman Islands, Fiji, Moldova, Morocco, Norfolk Island,
North Korea, Turkey, Uruguay.  New zone America/Fort_Nelson for Canadian
Northern Rockies.

8 years agoAdd recursion depth protection to LIKE matching.
Tom Lane [Fri, 2 Oct 2015 19:00:52 +0000 (15:00 -0400)]
Add recursion depth protection to LIKE matching.

Since MatchText() recurses, it could in principle be driven to stack
overflow, although quite a long pattern would be needed.

8 years agoAdd recursion depth protections to regular expression matching.
Tom Lane [Fri, 2 Oct 2015 18:51:59 +0000 (14:51 -0400)]
Add recursion depth protections to regular expression matching.

Some of the functions in regex compilation and execution recurse, and
therefore could in principle be driven to stack overflow.  The Tcl crew
has seen this happen in practice in duptraverse(), though their fix was
to put in a hard-wired limit on the number of recursive levels, which is
not too appetizing --- fortunately, we have enough infrastructure to check
the actually available stack.  Greg Stark has also seen it in other places
while fuzz testing on a machine with limited stack space.  Let's put guards
in to prevent crashes in all these places.

Since the regex code would leak memory if we simply threw elog(ERROR),
we have to introduce an API that checks for stack depth without throwing
such an error.  Fortunately that's not difficult.

8 years agoFix potential infinite loop in regular expression execution.
Tom Lane [Fri, 2 Oct 2015 18:26:36 +0000 (14:26 -0400)]
Fix potential infinite loop in regular expression execution.

In cfindloop(), if the initial call to shortest() reports that a
zero-length match is possible at the current search start point, but then
it is unable to construct any actual match to that, it'll just loop around
with the same start point, and thus make no progress.  We need to force the
start point to be advanced.  This is safe because the loop over "begin"
points has already tried and failed to match starting at "close", so there
is surely no need to try that again.

This bug was introduced in commit e2bd904955e2221eddf01110b1f25002de2aaa83,
wherein we allowed continued searching after we'd run out of match
possibilities, but evidently failed to think hard enough about exactly
where we needed to search next.

Because of the way this code works, such a match failure is only possible
in the presence of backrefs --- otherwise, shortest()'s judgment that a
match is possible should always be correct.  That probably explains how
come the bug has escaped detection for several years.

The actual fix is a one-liner, but I took the trouble to add/improve some
comments related to the loop logic.

After fixing that, the submitted test case "()*\1" didn't loop anymore.
But it reported failure, though it seems like it ought to match a
zero-length string; both Tcl and Perl think it does.  That seems to be from
overenthusiastic optimization on my part when I rewrote the iteration match
logic in commit 173e29aa5deefd9e71c183583ba37805c8102a72: we can't just
"declare victory" for a zero-length match without bothering to set match
data for capturing parens inside the iterator node.

Per fuzz testing by Greg Stark.  The first part of this is a bug in all
supported branches, and the second part is a bug since 9.2 where the
iteration rewrite happened.

8 years agoAdd some more query-cancel checks to regular expression matching.
Tom Lane [Fri, 2 Oct 2015 17:45:39 +0000 (13:45 -0400)]
Add some more query-cancel checks to regular expression matching.

Commit 9662143f0c35d64d7042fbeaf879df8f0b54be32 added infrastructure to
allow regular-expression operations to be terminated early in the event
of SIGINT etc.  However, fuzz testing by Greg Stark disclosed that there
are still cases where regex compilation could run for a long time without
noticing a cancel request.  Specifically, the fixempties() phase never
adds new states, only new arcs, so it doesn't hit the cancel check I'd put
in newstate().  Add one to newarc() as well to cover that.

Some experimentation of my own found that regex execution could also run
for a long time despite a pending cancel.  We'd put a high-level cancel
check into cdissect(), but there was none inside the core text-matching
routines longest() and shortest().  Ordinarily those inner loops are very
very fast ... but in the presence of lookahead constraints, not so much.
As a compromise, stick a cancel check into the stateset cache-miss
function, which is enough to guarantee a cancel check at least once per
lookahead constraint test.

Making this work required more attention to error handling throughout the
regex executor.  Henry Spencer had apparently originally intended longest()
and shortest() to be incapable of incurring errors while running, so
neither they nor their subroutines had well-defined error reporting
behaviors.  However, that was already broken by the lookahead constraint
feature, since lacon() can surely suffer an out-of-memory failure ---
which, in the code as it stood, might never be reported to the user at all,
but just silently be treated as a non-match of the lookahead constraint.
Normalize all that by inserting explicit error tests as needed.  I took the
opportunity to add some more comments to the code, too.

Back-patch to all supported branches, like the previous patch.

8 years agoDocs: add disclaimer about hazards of using regexps from untrusted sources.
Tom Lane [Fri, 2 Oct 2015 17:30:43 +0000 (13:30 -0400)]
Docs: add disclaimer about hazards of using regexps from untrusted sources.

It's not terribly hard to devise regular expressions that take large
amounts of time and/or memory to process.  Recent testing by Greg Stark has
also shown that machines with small stack limits can be driven to stack
overflow by suitably crafted regexps.  While we intend to fix these things
as much as possible, it's probably impossible to eliminate slow-execution
cases altogether.  In any case we don't want to treat such things as
security issues.  The history of that code should already discourage
prudent DBAs from allowing execution of regexp patterns coming from
possibly-hostile sources, but it seems like a good idea to warn about the
hazard explicitly.

Currently, similar_escape() allows access to enough of the underlying
regexp behavior that the warning has to apply to SIMILAR TO as well.
We might be able to make it safer if we tightened things up to allow only
SQL-mandated capabilities in SIMILAR TO; but that would be a subtly
non-backwards-compatible change, so it requires discussion and probably
could not be back-patched.

Per discussion among pgsql-security list.

8 years agoFix documentation error in commit 8703059c6b55c427100e00a09f66534b6ccbfaa1.
Tom Lane [Thu, 1 Oct 2015 14:31:22 +0000 (10:31 -0400)]
Fix documentation error in commit 8703059c6b55c427100e00a09f66534b6ccbfaa1.

Etsuro Fujita spotted a thinko in the README commentary.

8 years agoImprove LISTEN startup time when there are many unread notifications.
Tom Lane [Thu, 1 Oct 2015 03:32:23 +0000 (23:32 -0400)]
Improve LISTEN startup time when there are many unread notifications.

If some existing listener is far behind, incoming new listener sessions
would start from that session's read pointer and then need to advance over
many already-committed notification messages, which they have no interest
in.  This was expensive in itself and also thrashed the pg_notify SLRU
buffers a lot more than necessary.  We can improve matters considerably
in typical scenarios, without much added cost, by starting from the
furthest-ahead read pointer, not the furthest-behind one.  We do have to
consider only sessions in our own database when doing this, which requires
an extra field in the data structure, but that's a pretty small cost.

Back-patch to 9.0 where the current LISTEN/NOTIFY logic was introduced.

Matt Newell, slightly adjusted by me

8 years agoFix compiler warning about unused function in non-readline case.
Andrew Dunstan [Mon, 28 Sep 2015 22:29:20 +0000 (18:29 -0400)]
Fix compiler warning about unused function in non-readline case.

Backpatch to all live branches to keep the code in sync.

8 years agoFurther fix for psql's code for locale-aware formatting of numeric output.
Tom Lane [Fri, 25 Sep 2015 16:20:46 +0000 (12:20 -0400)]
Further fix for psql's code for locale-aware formatting of numeric output.

(Third time's the charm, I hope.)

Additional testing disclosed that this code could mangle already-localized
output from the "money" datatype.  We can't very easily skip applying it
to "money" values, because the logic is tied to column right-justification
and people expect "money" output to be right-justified.  Short of
decoupling that, we can fix it in what should be a safe enough way by
testing to make sure the string doesn't contain any characters that would
not be expected in plain numeric output.

8 years agoFurther fix for psql's code for locale-aware formatting of numeric output.
Tom Lane [Fri, 25 Sep 2015 04:00:33 +0000 (00:00 -0400)]
Further fix for psql's code for locale-aware formatting of numeric output.

On closer inspection, those seemingly redundant atoi() calls were not so
much inefficient as just plain wrong: the author of this code either had
not read, or had not understood, the POSIX specification for localeconv().
The grouping field is *not* a textual digit string but separate integers
encoded as chars.

We'll follow the existing code as well as the backend's cash.c in only
honoring the first group width, but let's at least honor it correctly.

This doesn't actually result in any behavioral change in any of the
locales I have installed on my Linux box, which may explain why nobody's
complained; grouping width 3 is close enough to universal that it's barely
worth considering other cases.  Still, wrong is wrong, so back-patch.

8 years agoFix psql's code for locale-aware formatting of numeric output.
Tom Lane [Fri, 25 Sep 2015 03:01:04 +0000 (23:01 -0400)]
Fix psql's code for locale-aware formatting of numeric output.

This code did the wrong thing entirely for numbers with an exponent
but no decimal point (e.g., '1e6'), as reported by Jeff Janes in
bug #13636.  More generally, it made lots of unverified assumptions
about what the input string could possibly look like.  Rearrange so
that it only fools with leading digits that it's directly verified
are there, and an immediately adjacent decimal point.  While at it,
get rid of some useless inefficiencies, like converting the grouping
count string to integer over and over (and over).

This has been broken for a long time, so back-patch to all supported
branches.

8 years agoLower *_freeze_max_age minimum values.
Andres Freund [Thu, 24 Sep 2015 12:53:33 +0000 (14:53 +0200)]
Lower *_freeze_max_age minimum values.

The old minimum values are rather large, making it time consuming to
test related behaviour. Additionally the current limits, especially for
multixacts, can be problematic in space-constrained systems. 10000000
multixacts can contain a lot of members.

Since there's no good reason for the current limits, lower them a good
bit. Setting them to 0 would be a bad idea, triggering endless vacuums,
so still retain a limit.

While at it fix autovacuum_multixact_freeze_max_age to refer to
multixact.c instead of varsup.c.

Reviewed-By: Robert Haas
Discussion: CA+TgmoYmQPHcrc3GSs7vwvrbTkbcGD9Gik=OztbDGGrovkkEzQ@mail.gmail.com
Backpatch: 9.0 (in parts)

8 years agoSkip recently-added umask() call on Windows.
Noah Misch [Wed, 23 Sep 2015 03:37:26 +0000 (23:37 -0400)]
Skip recently-added umask() call on Windows.

Symbols S_IRWXG and S_IRWXO became available to Windows builds in commit
1319002e2ee166c06b38cdbc5e8508c7205fa115, so PostgreSQL 9.0 cannot use
them in platform-independent code.  Rewrite commit
24aed2124a5273e4cb543b06d4b7bb2c2ad5bf3c to not change Windows builds.
The new umask() call had no effect on Windows, anyway.  Per buildfarm.

8 years agoDocs: fix typo in to_char() example.
Tom Lane [Tue, 22 Sep 2015 14:40:25 +0000 (10:40 -0400)]
Docs: fix typo in to_char() example.

Per bug #13631 from KOIZUMI Satoru.

8 years agoFix possible internal overflow in numeric multiplication.
Tom Lane [Mon, 21 Sep 2015 16:11:32 +0000 (12:11 -0400)]
Fix possible internal overflow in numeric multiplication.

mul_var() postpones propagating carries until it risks overflow in its
internal digit array.  However, the logic failed to account for the
possibility of overflow in the carry propagation step, allowing wrong
results to be generated in corner cases.  We must slightly reduce the
when-to-propagate-carries threshold to avoid that.

Discovered and fixed by Dean Rasheed, with small adjustments by me.

This has been wrong since commit d72f6c75038d8d37e64a29a04b911f728044d83b,
so back-patch to all supported branches.

8 years agoRestrict file mode creation mask during tmpfile().
Noah Misch [Mon, 21 Sep 2015 00:42:27 +0000 (20:42 -0400)]
Restrict file mode creation mask during tmpfile().

Per Coverity.  Back-patch to 9.0 (all supported versions).

Michael Paquier, reviewed (in earlier versions) by Heikki Linnakangas.

8 years agoBe more wary about partially-valid LOCALLOCK data in RemoveLocalLock().
Tom Lane [Sun, 20 Sep 2015 20:48:44 +0000 (16:48 -0400)]
Be more wary about partially-valid LOCALLOCK data in RemoveLocalLock().

RemoveLocalLock() must consider the possibility that LockAcquireExtended()
failed to palloc the initial space for a locallock's lockOwners array.
I had evidently meant to cope with this hazard when the code was originally
written (commit 1785acebf2ed14fd66955e2d9a55d77a025f418d), but missed that
the pfree needed to be protected with an if-test.  Just to make sure things
are left in a clean state, reset numLockOwners as well.

Per low-memory testing by Andreas Seltenreich.  Back-patch to all supported
branches.

8 years agoLet compiler handle size calculation of bool types.
Michael Meskes [Thu, 17 Sep 2015 13:41:04 +0000 (15:41 +0200)]
Let compiler handle size calculation of bool types.

Back in the day this did not work, but modern compilers should handle it themselves.

8 years agoFix low-probability memory leak in regex execution.
Tom Lane [Fri, 18 Sep 2015 17:55:17 +0000 (13:55 -0400)]
Fix low-probability memory leak in regex execution.

After an internal failure in shortest() or longest() while pinning down the
exact location of a match, find() forgot to free the DFA structure before
returning.  This is pretty unlikely to occur, since we just successfully
ran the "search" variant of the DFA; but it could happen, and it would
result in a session-lifespan memory leak since this code uses malloc()
directly.  Problem seems to have been aboriginal in Spencer's library,
so back-patch all the way.

In passing, correct a thinko in a comment I added awhile back about the
meaning of the "ntree" field.

I happened across these issues while comparing our code to Tcl's version
of the library.

8 years agoFix documentation of regular expression character-entry escapes.
Tom Lane [Wed, 16 Sep 2015 18:50:12 +0000 (14:50 -0400)]
Fix documentation of regular expression character-entry escapes.

The docs claimed that \uhhhh would be interpreted as a Unicode value
regardless of the database encoding, but it's never been implemented
that way: \uhhhh and \xhhhh actually mean exactly the same thing, namely
the character that pg_mb2wchar translates to 0xhhhh.  Moreover we were
falsely dismissive of the usefulness of Unicode code points above FFFF.
Fix that.

It's been like this for ages, so back-patch to all supported branches.

8 years agoRemove set-but-not-used variable.
Tom Lane [Sat, 12 Sep 2015 15:11:08 +0000 (11:11 -0400)]
Remove set-but-not-used variable.

In branches before 9.3, commit 8703059c6 caused join_is_legal()'s
unique_ified variable to become unused, since its only remaining
use is for LATERAL-related tests which don't exist pre-9.3.
My compiler didn't complain about that, but Peter's does.

8 years agopg_dump, pg_upgrade: allow postgres/template1 tablespace moves
Bruce Momjian [Fri, 11 Sep 2015 19:51:10 +0000 (15:51 -0400)]
pg_dump, pg_upgrade:  allow postgres/template1 tablespace moves

Modify pg_dump to restore postgres/template1 databases to non-default
tablespaces by switching out of the database to be moved, then switching
back.

Also, to fix potentially cases where the old/new tablespaces might not
match, fix pg_upgrade to process new/old tablespaces separately in all
cases.

Report by Marti Raudsepp

Patch by Marti Raudsepp, me

Backpatch through 9.0

8 years agoRevert "Fix typo in setrefs.c"
Tom Lane [Thu, 10 Sep 2015 14:26:58 +0000 (10:26 -0400)]
Revert "Fix typo in setrefs.c"

This reverts commit 0473e047877ab9e51d5130bc14276b2308ed77a8.

8 years agoFix typo in setrefs.c
Stephen Frost [Thu, 10 Sep 2015 13:22:44 +0000 (09:22 -0400)]
Fix typo in setrefs.c

We're adding OIDs, not TIDs, to invalItems.

Pointed out by Etsuro Fujita.

Back-patch to all supported branches.

8 years agoFix minor bug in regexp makesearch() function.
Tom Lane [Thu, 10 Sep 2015 00:14:58 +0000 (20:14 -0400)]
Fix minor bug in regexp makesearch() function.

The list-wrangling here was done wrong, allowing the same state to get
put into the list twice.  The following loop then would clone it twice.
The second clone would wind up with no inarcs, so that there was no
observable misbehavior AFAICT, but a useless state in the finished NFA
isn't an especially good thing.

8 years agoAdd gin_fuzzy_search_limit to postgresql.conf.sample.
Fujii Masao [Tue, 8 Sep 2015 17:25:50 +0000 (02:25 +0900)]
Add gin_fuzzy_search_limit to postgresql.conf.sample.

This was forgotten in 8a3631f (commit that originally added the parameter)
and 0ca9907 (commit that added the documentation later that year).

Back-patch to all supported versions.

8 years agoFix error message wording in previous sslinfo commit
Alvaro Herrera [Tue, 8 Sep 2015 14:10:20 +0000 (11:10 -0300)]
Fix error message wording in previous sslinfo commit

8 years agoAdd more sanity checks in contrib/sslinfo
Alvaro Herrera [Mon, 7 Sep 2015 22:18:29 +0000 (19:18 -0300)]
Add more sanity checks in contrib/sslinfo

We were missing a few return checks on OpenSSL calls.  Should be pretty
harmless, since we haven't seen any user reports about problems, and
this is not a high-traffic module anyway; still, a bug is a bug, so
backpatch this all the way back to 9.0.

Author: Michael Paquier, while reviewing another sslinfo patch

8 years agoChange type of DOW/DOY to UNITS
Greg Stark [Mon, 7 Sep 2015 12:35:09 +0000 (13:35 +0100)]
Change type of DOW/DOY to UNITS

8 years agoMake GIN's cleanup pending list process interruptable
Teodor Sigaev [Mon, 7 Sep 2015 14:20:44 +0000 (17:20 +0300)]
Make GIN's cleanup pending list process interruptable

Cleanup process could be called by ordinary insert/update and could take a lot
of time. Add vacuum_delay_point() to make this process interruptable. Under
vacuum this call will also throttle a vacuum process to decrease system load,
called from insert/update it will not throttle, and that reduces a latency.

Backpatch for all supported branches.

Jeff Janes <jeff.janes@gmail.com>

8 years agoUpdate site address of Snowball project
Teodor Sigaev [Mon, 7 Sep 2015 12:22:29 +0000 (15:22 +0300)]
Update site address of Snowball project

8 years ago Move DTK_ISODOW DTK_DOW and DTK_DOY to be type UNITS rather than
Greg Stark [Sun, 6 Sep 2015 03:02:57 +0000 (04:02 +0100)]
Move DTK_ISODOW DTK_DOW and DTK_DOY to be type UNITS rather than
    RESERV. RESERV is meant for tokens like "now" and having them in that
    category throws errors like these when used as an input date:

    stark=# SELECT 'doy'::timestamptz;
    ERROR:  unexpected dtype 33 while parsing timestamptz "doy"
    LINE 1: SELECT 'doy'::timestamptz;
                   ^
    stark=# SELECT 'dow'::timestamptz;
    ERROR:  unexpected dtype 32 while parsing timestamptz "dow"
    LINE 1: SELECT 'dow'::timestamptz;
                   ^

    Found by LLVM's Libfuzzer

8 years agoFix misc typos.
Heikki Linnakangas [Sat, 5 Sep 2015 08:35:49 +0000 (11:35 +0300)]
Fix misc typos.

Oskari Saarenmaa. Backpatch to stable branches where applicable.

8 years agoFix subtransaction cleanup after an outer-subtransaction portal fails.
Tom Lane [Fri, 4 Sep 2015 17:36:50 +0000 (13:36 -0400)]
Fix subtransaction cleanup after an outer-subtransaction portal fails.

Formerly, we treated only portals created in the current subtransaction as
having failed during subtransaction abort.  However, if the error occurred
while running a portal created in an outer subtransaction (ie, a cursor
declared before the last savepoint), that has to be considered broken too.

To allow reliable detection of which ones those are, add a bookkeeping
field to struct Portal that tracks the innermost subtransaction in which
each portal has actually been executed.  (Without this, we'd end up
failing portals containing functions that had called the subtransaction,
thereby breaking plpgsql exception blocks completely.)

In addition, when we fail an outer-subtransaction Portal, transfer its
resources into the subtransaction's resource owner, so that they're
released early in cleanup of the subxact.  This fixes a problem reported by
Jim Nasby in which a function executed in an outer-subtransaction cursor
could cause an Assert failure or crash by referencing a relation created
within the inner subtransaction.

The proximate cause of the Assert failure is that AtEOSubXact_RelationCache
assumed it could blow away a relcache entry without first checking that the
entry had zero refcount.  That was a bad idea on its own terms, so add such
a check there, and to the similar coding in AtEOXact_RelationCache.  This
provides an independent safety measure in case there are still ways to
provoke the situation despite the Portal-level changes.

This has been broken since subtransactions were invented, so back-patch
to all supported branches.

Tom Lane and Michael Paquier

8 years agoFix s_lock.h PPC assembly code to be compatible with native AIX assembler.
Tom Lane [Sat, 29 Aug 2015 20:09:25 +0000 (16:09 -0400)]
Fix s_lock.h PPC assembly code to be compatible with native AIX assembler.

On recent AIX it's necessary to configure gcc to use the native assembler
(because the GNU assembler hasn't been updated to handle AIX 6+).  This
caused PG builds to fail with assembler syntax errors, because we'd try
to compile s_lock.h's gcc asm fragment for PPC, and that assembly code
relied on GNU-style local labels.  We can't substitute normal labels
because it would fail in any file containing more than one inlined use of
tas().  Fortunately, that code is stable enough, and the PPC ISA is simple
enough, that it doesn't seem like too much of a maintenance burden to just
hand-code the branch offsets, removing the need for any labels.

Note that the AIX assembler only accepts "$" for the location counter
pseudo-symbol.  The usual GNU convention is "."; but it appears that all
versions of gas for PPC also accept "$", so in theory this patch will not
break any other PPC platforms.

This has been reported by a few people, but Steve Underwood gets the credit
for being the first to pursue the problem far enough to understand why it
was failing.  Thanks also to Noah Misch for additional testing.

8 years agodblink docs: fix typo to use "connname" (3 n's), not "conname"
Bruce Momjian [Thu, 27 Aug 2015 17:43:10 +0000 (13:43 -0400)]
dblink docs:  fix typo to use "connname" (3 n's), not "conname"

This makes the parameter names match the documented prototype names.

Report by Erwin Brandstetter

Backpatch through 9.0

8 years agoDocs: be explicit about datatype matching for lead/lag functions.
Tom Lane [Tue, 25 Aug 2015 23:12:57 +0000 (19:12 -0400)]
Docs: be explicit about datatype matching for lead/lag functions.

The default argument, if given, has to be of exactly the same datatype
as the first argument; but this was not stated in so many words, and
the error message you get about it might not lead your thought in the
right direction.  Per bug #13587 from Robert McGehee.

A quick scan says that these are the only two built-in functions with two
anyelement arguments and no other polymorphic arguments.  There are plenty
of cases of, eg, anyarray and anyelement, but those seem less likely to
confuse.  For instance this doesn't seem terribly hard to figure out:
"function array_remove(integer[], numeric) does not exist".  So I've
contented myself with fixing these two cases.

8 years agoAvoid O(N^2) behavior when enlarging SPI tuple table in spi_printtup().
Tom Lane [Sat, 22 Aug 2015 00:32:11 +0000 (20:32 -0400)]
Avoid O(N^2) behavior when enlarging SPI tuple table in spi_printtup().

For no obvious reason, spi_printtup() was coded to enlarge the tuple
pointer table by just 256 slots at a time, rather than doubling the size at
each reallocation, as is our usual habit.  For very large SPI results, this
makes for O(N^2) time spent in repalloc(), which of course soon comes to
dominate the runtime.  Use the standard doubling approach instead.

This is a longstanding performance bug, so back-patch to all active
branches.

Neil Conway

8 years agoFix a few bogus statement type names in plpgsql error messages.
Tom Lane [Tue, 18 Aug 2015 23:22:38 +0000 (19:22 -0400)]
Fix a few bogus statement type names in plpgsql error messages.

plpgsql's error location context messages ("PL/pgSQL function fn-name line
line-no at stmt-type") would misreport a CONTINUE statement as being an
EXIT, and misreport a MOVE statement as being a FETCH.  These are clear
bugs that have been there a long time, so back-patch to all supported
branches.

In addition, in 9.5 and HEAD, change the description of EXECUTE from
"EXECUTE statement" to just plain EXECUTE; there seems no good reason why
this statement type should be described differently from others that have
a well-defined head keyword.  And distinguish GET STACKED DIAGNOSTICS from
plain GET DIAGNOSTICS.  These are a bit more of a judgment call, and also
affect existing regression-test outputs, so I did not back-patch into
stable branches.

Pavel Stehule and Tom Lane

8 years agoImprove documentation about MVCC-unsafe utility commands.
Tom Lane [Sat, 15 Aug 2015 17:30:16 +0000 (13:30 -0400)]
Improve documentation about MVCC-unsafe utility commands.

The table-rewriting forms of ALTER TABLE are MVCC-unsafe, in much the same
way as TRUNCATE, because they replace all rows of the table with newly-made
rows with a new xmin.  (Ideally, concurrent transactions with old snapshots
would continue to see the old table contents, but the data is not there
anymore --- and if it were there, it would be inconsistent with the table's
updated rowtype, so there would be serious implementation problems to fix.)
This was nowhere documented though, and the problem was only documented for
TRUNCATE in a note in the TRUNCATE reference page.  Create a new "Caveats"
section in the MVCC chapter that can be home to this and other limitations
on serializable consistency.

In passing, fix a mistaken statement that VACUUM and CLUSTER would reclaim
space occupied by a dropped column.  They don't reconstruct existing tuples
so they couldn't do that.

Back-patch to all supported branches.

8 years agoUse fuzzy path cost tiebreaking rule in our oldest supported branches.
Tom Lane [Sat, 15 Aug 2015 15:02:17 +0000 (11:02 -0400)]
Use fuzzy path cost tiebreaking rule in our oldest supported branches.

We've been doing it that way since 9.2, cf commit 33e99153e93b9acc,
but some recently-added regression test cases are making a few buildfarm
members fail (ie choose the "wrong" plan) in 9.0 and 9.1 due to
platform-specific roundoff differences in cost calculations.  To fix,
back-port the patch that made add_path treat cost difference ratios of
less than 1e-10 as equal.

8 years agoDon't use 'bool' as a struct member name in help_config.c.
Andres Freund [Wed, 12 Aug 2015 14:02:20 +0000 (16:02 +0200)]
Don't use 'bool' as a struct member name in help_config.c.

Doing so doesn't work if bool is a macro rather than a typedef.

Although c.h spends some effort to support configurations where bool is
a preexisting macro, help_config.c has existed this way since
2003 (b700a6), and there have not been any reports of
problems. Backpatch anyway since this is as riskless as it gets.

Discussion: 20150812084351.GD8470@awork2.anarazel.de
Backpatch: 9.0-master

8 years agoFix declaration of isarray variable.
Michael Meskes [Thu, 13 Aug 2015 11:22:29 +0000 (13:22 +0200)]
Fix declaration of isarray variable.

Found and fixed by Andres Freund.

8 years agoUndo mistaken tightening in join_is_legal().
Tom Lane [Thu, 13 Aug 2015 01:18:45 +0000 (21:18 -0400)]
Undo mistaken tightening in join_is_legal().

One of the changes I made in commit 8703059c6b55c427 turns out not to have
been such a good idea: we still need the exception in join_is_legal() that
allows a join if both inputs already overlap the RHS of the special join
we're checking.  Otherwise we can miss valid plans, and might indeed fail
to find a plan at all, as in recent report from Andreas Seltenreich.

That code was added way back in commit c17117649b9ae23d, but I failed to
include a regression test case then; my bad.  Put it back with a better
explanation, and a test this time.  The logic does end up a bit different
than before though: I now believe it's appropriate to make this check
first, thereby allowing such a case whether or not we'd consider the
previous SJ(s) to commute with this one.  (Presumably, we already decided
they did; but it was confusing to have this consideration in the middle
of the code that was handling the other case.)

Back-patch to all active branches, like the previous patch.

8 years agoThis routine was calling ecpg_alloc to allocate to memory but did not
Michael Meskes [Thu, 5 Feb 2015 14:12:34 +0000 (15:12 +0100)]
This routine was calling ecpg_alloc to allocate to memory but did not
actually check the returned pointer allocated, potentially NULL which
could be the result of a malloc call.

Issue noted by Coverity, fixed by Michael Paquier <michael@otacoo.com>

8 years agoFix some possible low-memory failures in regexp compilation.
Tom Lane [Wed, 12 Aug 2015 04:48:11 +0000 (00:48 -0400)]
Fix some possible low-memory failures in regexp compilation.

newnfa() failed to set the regex error state when malloc() fails.
Several places in regcomp.c failed to check for an error after calling
subre().  Each of these mistakes could lead to null-pointer-dereference
crashes in memory-starved backends.

Report and patch by Andreas Seltenreich.  Back-patch to all branches.

8 years agoFix privilege dumping from servers too old to have that type of privilege.
Tom Lane [Tue, 11 Aug 2015 00:10:16 +0000 (20:10 -0400)]
Fix privilege dumping from servers too old to have that type of privilege.

pg_dump produced fairly silly GRANT/REVOKE commands when dumping types from
pre-9.2 servers, and when dumping functions or procedural languages from
pre-7.3 servers.  Those server versions lack the typacl, proacl, and/or
lanacl columns respectively, and pg_dump substituted default values that
were in fact incorrect.  We ended up revoking all the owner's own
privileges for the object while granting all privileges to PUBLIC.
Of course the owner would then have those privileges again via PUBLIC, so
long as she did not try to revoke PUBLIC's privileges; which may explain
the lack of field reports.  Nonetheless this is pretty silly behavior.

The stakes were raised by my recent patch to make pg_dump dump shell types,
because 9.2 and up pg_dump would proceed to emit bogus GRANT/REVOKE
commands for a shell type if dumping from a pre-9.2 server; and the server
will not accept GRANT/REVOKE commands for a shell type.  (Perhaps it
should, but that's a topic for another day.)  So the resulting dump script
wouldn't load without errors.

The right thing to do is to act as though these objects have default
privileges (null ACL entries), which causes pg_dump to print no
GRANT/REVOKE commands at all for them.  That fixes the silly results
and also dodges the problem with shell types.

In passing, modify getProcLangs() to be less creatively different about
how to handle missing columns when dumping from older server versions.
Every other data-acquisition function in pg_dump does that by substituting
appropriate default values in the version-specific SQL commands, and I see
no reason why this one should march to its own drummer.  Its use of
"SELECT *" was likewise not conformant with anyplace else, not to mention
it's not considered good SQL style for production queries.

Back-patch to all supported versions.  Although 9.0 and 9.1 pg_dump don't
have the issue with typacl, they are more likely than newer versions to be
used to dump from ancient servers, so we ought to fix the proacl/lanacl
issues all the way back.

8 years agoAccept alternate spellings of __sparcv7 and __sparcv8.
Tom Lane [Mon, 10 Aug 2015 21:34:51 +0000 (17:34 -0400)]
Accept alternate spellings of __sparcv7 and __sparcv8.

Apparently some versions of gcc prefer __sparc_v7__ and __sparc_v8__.
Per report from Waldemar Brodkorb.

8 years agoFurther fixes for degenerate outer join clauses.
Tom Lane [Thu, 6 Aug 2015 19:35:28 +0000 (15:35 -0400)]
Further fixes for degenerate outer join clauses.

Further testing revealed that commit f69b4b9495269cc4 was still a few
bricks shy of a load: minor tweaking of the previous test cases resulted
in the same wrong-outer-join-order problem coming back.  After study
I concluded that my previous changes in make_outerjoininfo() were just
accidentally masking the problem, and should be reverted in favor of
forcing syntactic join order whenever an upper outer join's predicate
doesn't mention a lower outer join's LHS.  This still allows the
chained-outer-joins style that is the normally optimizable case.

I also tightened things up some more in join_is_legal().  It seems to me
on review that what's really happening in the exception case where we
ignore a mismatched special join is that we're allowing the proposed join
to associate into the RHS of the outer join we're comparing it to.  As
such, we should *always* insist that the proposed join be a left join,
which eliminates a bunch of rather dubious argumentation.  The case where
we weren't enforcing that was the one that was already known buggy anyway
(it had a violatable Assert before the aforesaid commit) so it hardly
deserves a lot of deference.

Back-patch to all active branches, like the previous patch.  The added
regression test case failed in all branches back to 9.1, and I think it's
only an unrelated change in costing calculations that kept 9.0 from
choosing a broken plan.

8 years agoMake real sure we don't reassociate joins into or out of SEMI/ANTI joins.
Tom Lane [Wed, 5 Aug 2015 18:39:07 +0000 (14:39 -0400)]
Make real sure we don't reassociate joins into or out of SEMI/ANTI joins.

Per the discussion in optimizer/README, it's unsafe to reassociate anything
into or out of the RHS of a SEMI or ANTI join.  An example from Piotr
Stefaniak showed that join_is_legal() wasn't sufficiently enforcing this
rule, so lock it down a little harder.

I couldn't find a reasonably simple example of the optimizer trying to
do this, so no new regression test.  (Piotr's example involved the random
search in GEQO accidentally trying an invalid case and triggering a sanity
check way downstream in clause selectivity estimation, which did not seem
like a sequence of events that would be useful to memorialize in a
regression test as-is.)

Back-patch to all active branches.

8 years agoDocs: add an explicit example about controlling overall greediness of REs.
Tom Lane [Wed, 5 Aug 2015 01:09:12 +0000 (21:09 -0400)]
Docs: add an explicit example about controlling overall greediness of REs.

Per discussion of bug #13538.

8 years agoFix pg_dump to dump shell types.
Tom Lane [Tue, 4 Aug 2015 23:34:12 +0000 (19:34 -0400)]
Fix pg_dump to dump shell types.

Per discussion, it really ought to do this.  The original choice to
exclude shell types was probably made in the dark ages before we made
it harder to accidentally create shell types; but that was in 7.3.

Also, cause the standard regression tests to leave a shell type behind,
for convenience in testing the case in pg_dump and pg_upgrade.

Back-patch to all supported branches.

8 years agoFix bogus "out of memory" reports in tuplestore.c.
Tom Lane [Tue, 4 Aug 2015 22:18:47 +0000 (18:18 -0400)]
Fix bogus "out of memory" reports in tuplestore.c.

The tuplesort/tuplestore memory management logic assumed that the chunk
allocation overhead for its memtuples array could not increase when
increasing the array size.  This is and always was true for tuplesort,
but we (I, I think) blindly copied that logic into tuplestore.c without
noticing that the assumption failed to hold for the much smaller array
elements used by tuplestore.  Given rather small work_mem, this could
result in an improper complaint about "unexpected out-of-memory situation",
as reported by Brent DeSpain in bug #13530.

The easiest way to fix this is just to increase tuplestore's initial
array size so that the assumption holds.  Rather than relying on magic
constants, though, let's export a #define from aset.c that represents
the safe allocation threshold, and make tuplestore's calculation depend
on that.

Do the same in tuplesort.c to keep the logic looking parallel, even though
tuplesort.c isn't actually at risk at present.  This will keep us from
breaking it if we ever muck with the allocation parameters in aset.c.

Back-patch to all supported versions.  The error message doesn't occur
pre-9.3, not so much because the problem can't happen as because the
pre-9.3 tuplestore code neglected to check for it.  (The chance of
trouble is a great deal larger as of 9.3, though, due to changes in the
array-size-increasing strategy.)  However, allowing LACKMEM() to become
true unexpectedly could still result in less-than-desirable behavior,
so let's patch it all the way back.

8 years agoCap wal_buffers to avoid a server crash when it's set very large.
Robert Haas [Tue, 4 Aug 2015 16:58:54 +0000 (12:58 -0400)]
Cap wal_buffers to avoid a server crash when it's set very large.

It must be possible to multiply wal_buffers by XLOG_BLCKSZ without
overflowing int, or calculations in StartupXLOG will go badly wrong
and crash the server.  Avoid that by imposing a maximum value on
wal_buffers.  This will be just under 2GB, assuming the usual value
for XLOG_BLCKSZ.

Josh Berkus, per an analysis by Andrew Gierth.

8 years agoFix incorrect order of lock file removal and failure to close() sockets.
Tom Lane [Sun, 2 Aug 2015 18:54:44 +0000 (14:54 -0400)]
Fix incorrect order of lock file removal and failure to close() sockets.

Commit c9b0cbe98bd783e24a8c4d8d8ac472a494b81292 accidentally broke the
order of operations during postmaster shutdown: it resulted in removing
the per-socket lockfiles after, not before, postmaster.pid.  This creates
a race-condition hazard for a new postmaster that's started immediately
after observing that postmaster.pid has disappeared; if it sees the
socket lockfile still present, it will quite properly refuse to start.
This error appears to be the explanation for at least some of the
intermittent buildfarm failures we've seen in the pg_upgrade test.

Another problem, which has been there all along, is that the postmaster
has never bothered to close() its listen sockets, but has just allowed them
to close at process death.  This creates a different race condition for an
incoming postmaster: it might be unable to bind to the desired listen
address because the old postmaster is still incumbent.  This might explain
some odd failures we've seen in the past, too.  (Note: this is not related
to the fact that individual backends don't close their client communication
sockets.  That behavior is intentional and is not changed by this patch.)

Fix by adding an on_proc_exit function that closes the postmaster's ports
explicitly, and (in 9.3 and up) reshuffling the responsibility for where
to unlink the Unix socket files.  Lock file unlinking can stay where it
is, but teach it to unlink the lock files in reverse order of creation.

8 years agoFix some planner issues with degenerate outer join clauses.
Tom Lane [Sun, 2 Aug 2015 00:57:41 +0000 (20:57 -0400)]
Fix some planner issues with degenerate outer join clauses.

An outer join clause that didn't actually reference the RHS (perhaps only
after constant-folding) could confuse the join order enforcement logic,
leading to wrong query results.  Also, nested occurrences of such things
could trigger an Assertion that on reflection seems incorrect.

Per fuzz testing by Andreas Seltenreich.  The practical use of such cases
seems thin enough that it's not too surprising we've not heard field
reports about it.

This has been broken for a long time, so back-patch to all active branches.

8 years agoAvoid some zero-divide hazards in the planner.
Tom Lane [Thu, 30 Jul 2015 16:11:23 +0000 (12:11 -0400)]
Avoid some zero-divide hazards in the planner.

Although I think on all modern machines floating division by zero
results in Infinity not SIGFPE, we still don't want infinities
running around in the planner's costing estimates; too much risk
of that leading to insane behavior.

grouping_planner() failed to consider the possibility that final_rel
might be known dummy and hence have zero rowcount.  (I wonder if it
would be better to set a rows estimate of 1 for dummy relations?
But at least in the back branches, changing this convention seems
like a bad idea, so I'll leave that for another day.)

Make certain that get_variable_numdistinct() produces a nonzero result.
The case that can be shown to be broken is with stadistinct < 0.0 and
small ntuples; we did not prevent the result from rounding to zero.
For good luck I applied clamp_row_est() to all the nonconstant return
values.

In ExecChooseHashTableSize(), Assert that we compute positive nbuckets
and nbatch.  I know of no reason to think this isn't the case, but it
seems like a good safety check.

Per reports from Piotr Stefaniak.  Back-patch to all active branches.

8 years agoBlacklist xlc 32-bit inlining.
Noah Misch [Thu, 30 Jul 2015 02:49:48 +0000 (22:49 -0400)]
Blacklist xlc 32-bit inlining.

Per a suggestion from Tom Lane.  Back-patch to 9.0 (all supported
versions).  While only 9.4 and up have code known to elicit this
compiler bug, we were disabling inlining by accident until commit
43d89a23d59c487bc9258fad7a6187864cb8c0c0.

8 years agoUpdate our documentation concerning where to create data directories.
Tom Lane [Tue, 28 Jul 2015 22:42:59 +0000 (18:42 -0400)]
Update our documentation concerning where to create data directories.

Although initdb has long discouraged use of a filesystem mount-point
directory as a PG data directory, this point was covered nowhere in the
user-facing documentation.  Also, with the popularity of pg_upgrade,
we really need to recommend that the PG user own not only the data
directory but its parent directory too.  (Without a writable parent
directory, operations such as "mv data data.old" fail immediately.
pg_upgrade itself doesn't do that, but wrapper scripts for it often do.)

Hence, adjust the "Creating a Database Cluster" section to address
these points.  I also took the liberty of wordsmithing the discussion
of NFS a bit.

These considerations aren't by any means new, so back-patch to all
supported branches.

8 years agoReduce chatter from signaling of autovacuum workers.
Tom Lane [Tue, 28 Jul 2015 21:34:00 +0000 (17:34 -0400)]
Reduce chatter from signaling of autovacuum workers.

Don't print a WARNING if we get ESRCH from a kill() that's attempting
to cancel an autovacuum worker.  It's possible (and has been seen in the
buildfarm) that the worker is already gone by the time we are able to
execute the kill, in which case the failure is harmless.  About the only
plausible reason for reporting such cases would be to help debug corrupted
lock table contents, but this is hardly likely to be the most important
symptom if that happens.  Moreover issuing a WARNING might scare users
more than is warranted.

Also, since sending a signal to an autovacuum worker is now entirely a
routine thing, and the worker will log the query cancel on its end anyway,
reduce the message saying we're doing that from LOG to DEBUG1 level.

Very minor cosmetic cleanup as well.

Since the main practical reason for doing this is to avoid unnecessary
buildfarm failures, back-patch to all active branches.

8 years agoDisable ssl renegotiation by default.
Andres Freund [Tue, 28 Jul 2015 19:39:40 +0000 (21:39 +0200)]
Disable ssl renegotiation by default.

While postgres' use of SSL renegotiation is a good idea in theory, it
turned out to not work well in practice. The specification and openssl's
implementation of it have lead to several security issues. Postgres' use
of renegotiation also had its share of bugs.

Additionally OpenSSL has a bunch of bugs around renegotiation, reported
and open for years, that regularly lead to connections breaking with
obscure error messages. We tried increasingly complex workarounds to get
around these bugs, but we didn't find anything complete.

Since these connection breakages often lead to hard to debug problems,
e.g. spuriously failing base backups and significant latency spikes when
synchronous replication is used, we have decided to change the default
setting for ssl renegotiation to 0 (disabled) in the released
backbranches and remove it entirely in 9.5 and master..

Author: Michael Paquier, with changes by me
Discussion: 20150624144148.GQ4797@alap3.anarazel.de
Backpatch: 9.0-9.4; 9.5 and master get a different patch

8 years agoReuse all-zero pages in GIN.
Heikki Linnakangas [Mon, 27 Jul 2015 09:30:26 +0000 (12:30 +0300)]
Reuse all-zero pages in GIN.

In GIN, an all-zeros page would be leaked forever, and never reused. Just
add them to the FSM in vacuum, and they will be reinitialized when grabbed
from the FSM. On master and 9.5, attempting to access the page's opaque
struct also caused an assertion failure, although that was otherwise
harmless.

Reported by Jeff Janes. Backpatch to all supported versions.

8 years agoFix off-by-one error in calculating subtrans/multixact truncation point.
Heikki Linnakangas [Wed, 22 Jul 2015 22:30:19 +0000 (01:30 +0300)]
Fix off-by-one error in calculating subtrans/multixact truncation point.

If there were no subtransactions (or multixacts) active, we would calculate
the oldestxid == next xid. That's correct, but if next XID happens to be
on the next pg_subtrans (pg_multixact) page, the page does not exist yet,
and SimpleLruTruncate will produce an "apparent wraparound" warning. The
warning is harmless in this case, but looks very alarming to users.

Backpatch to all supported versions. Patch and analysis by Thomas Munro.

8 years agoFix (some of) pltcl memory usage
Alvaro Herrera [Mon, 20 Jul 2015 12:18:08 +0000 (14:18 +0200)]
Fix (some of) pltcl memory usage

As reported by Bill Parker, PL/Tcl did not validate some malloc() calls
against NULL return.  Fix by using palloc() in a new long-lived memory
context instead.  This allows us to simplify error handling too, by
simply deleting the memory context instead of doing retail frees.

There's still a lot that could be done to improve PL/Tcl's memory
handling ...

This is pretty ancient, so backpatch all the way back.

Author: Michael Paquier and Álvaro Herrera
Discussion: https://www.postgresql.org/message-id/CAFrbyQwyLDYXfBOhPfoBGqnvuZO_Y90YgqFM11T2jvnxjLFmqw@mail.gmail.com

8 years agoAIX: Test the -qlonglong option before use.
Noah Misch [Fri, 17 Jul 2015 07:01:14 +0000 (03:01 -0400)]
AIX: Test the -qlonglong option before use.

xlc provides "long long" unconditionally at C99-compatible language
levels, and this option provokes a warning.  The warning interferes with
"configure" tests that fail in response to any warning.  Notably, before
commit 85a2a8903f7e9151793308d0638621003aded5ae, it interfered with the
test for -qnoansialias.  Back-patch to 9.0 (all supported versions).

8 years agoFix a low-probability crash in our qsort implementation.
Tom Lane [Fri, 17 Jul 2015 02:57:46 +0000 (22:57 -0400)]
Fix a low-probability crash in our qsort implementation.

It's standard for quicksort implementations, after having partitioned the
input into two subgroups, to recurse to process the smaller partition and
then handle the larger partition by iterating.  This method guarantees
that no more than log2(N) levels of recursion can be needed.  However,
Bentley and McIlroy argued that checking to see which partition is smaller
isn't worth the cycles, and so their code doesn't do that but just always
recurses on the left partition.  In most cases that's fine; but with
worst-case input we might need O(N) levels of recursion, and that means
that qsort could be driven to stack overflow.  Such an overflow seems to
be the only explanation for today's report from Yiqing Jin of a SIGSEGV
in med3_tuple while creating an index of a couple billion entries with a
very large maintenance_work_mem setting.  Therefore, let's spend the few
additional cycles and lines of code needed to choose the smaller partition
for recursion.

Also, fix up the qsort code so that it properly uses size_t not int for
some intermediate values representing numbers of items.  This would only
be a live risk when sorting more than INT_MAX bytes (in qsort/qsort_arg)
or tuples (in qsort_tuple), which I believe would never happen with any
caller in the current core code --- but perhaps it could happen with
call sites in third-party modules?  In any case, this is trouble waiting
to happen, and the corrected code is probably if anything shorter and
faster than before, since it removes sign-extension steps that had to
happen when converting between int and size_t.

In passing, move a couple of CHECK_FOR_INTERRUPTS() calls so that it's
not necessary to preserve the value of "r" across them, and prettify
the output of gen_qsort_tuple.pl a little.

Back-patch to all supported branches.  The odds of hitting this issue
are probably higher in 9.4 and up than before, due to the new ability
to allocate sort workspaces exceeding 1GB, but there's no good reason
to believe that it's impossible to crash older branches this way.

8 years agoAIX: Link the postgres executable with -Wl,-brtllib.
Noah Misch [Thu, 16 Jul 2015 01:00:26 +0000 (21:00 -0400)]
AIX: Link the postgres executable with -Wl,-brtllib.

This allows PostgreSQL modules and their dependencies to have undefined
symbols, resolved at runtime.  Perl module shared objects rely on that
in Perl 5.8.0 and later.  This fixes the crash when PL/PerlU loads such
modules, as the hstore_plperl test suite does.  Module authors can link
using -Wl,-G to permit undefined symbols; by default, linking will fail
as it has.  Back-patch to 9.0 (all supported versions).

8 years agoFix postmaster's handling of a startup-process crash.
Tom Lane [Thu, 9 Jul 2015 17:22:23 +0000 (13:22 -0400)]
Fix postmaster's handling of a startup-process crash.

Ordinarily, a failure (unexpected exit status) of the startup subprocess
should be considered fatal, so the postmaster should just close up shop
and quit.  However, if we sent the startup process a SIGQUIT or SIGKILL
signal, the failure is hardly "unexpected", and we should attempt restart;
this is necessary for recovery from ordinary backend crashes in hot-standby
scenarios.  I attempted to implement the latter rule with a two-line patch
in commit 442231d7f71764b8c628044e7ce2225f9aa43b67, but it now emerges that
that patch was a few bricks shy of a load: it failed to distinguish the
case of a signaled startup process from the case where the new startup
process crashes before reaching database consistency.  That resulted in
infinitely respawning a new startup process only to have it crash again.

To handle this properly, we really must track whether we have sent the
*current* startup process a kill signal.  Rather than add yet another
ad-hoc boolean to the postmaster's state, I chose to unify this with the
existing RecoveryError flag into an enum tracking the startup process's
state.  That seems more consistent with the postmaster's general state
machine design.

Back-patch to 9.0, like the previous patch.

8 years agoFix another broken link in documentation.
Heikki Linnakangas [Thu, 9 Jul 2015 13:00:14 +0000 (16:00 +0300)]
Fix another broken link in documentation.

Tom fixed another one of these in commit 7f32dbcd, but there was another
almost identical one in libpq docs. Per his comment:

HP's web server has apparently become case-sensitive sometime recently.
Per bug #13479 from Daniel Abraham.  Corrected link identified by Alvaro.

8 years agoFix null pointer dereference in "\c" psql command.
Noah Misch [Thu, 9 Jul 2015 00:44:21 +0000 (20:44 -0400)]
Fix null pointer dereference in "\c" psql command.

The psql crash happened when no current connection existed.  (The second
new check is optional given today's undocumented NULL argument handling
in PQhost() etc.)  Back-patch to 9.0 (all supported versions).

8 years agoOops, PQExpBufferDataBroken doesn't exist before 9.2.
Heikki Linnakangas [Tue, 7 Jul 2015 15:54:08 +0000 (18:54 +0300)]
Oops, PQExpBufferDataBroken doesn't exist before 9.2.

My previous back-patching went wrong.

8 years agoImprove handling of out-of-memory in libpq.
Heikki Linnakangas [Tue, 7 Jul 2015 15:37:45 +0000 (18:37 +0300)]
Improve handling of out-of-memory in libpq.

If an allocation fails in the main message handling loop, pqParseInput3
or pqParseInput2, it should not be treated as "not enough data available
yet". Otherwise libpq will wait indefinitely for more data to arrive from
the server, and gets stuck forever.

This isn't a complete fix - getParamDescriptions and getCopyStart still
have the same issue, but it's a step in the right direction.

Michael Paquier and me. Backpatch to all supported versions.

8 years agoTurn install.bat into a pure one line wrapper fort he perl script.
Heikki Linnakangas [Tue, 7 Jul 2015 13:31:52 +0000 (16:31 +0300)]
Turn install.bat into a pure one line wrapper fort he perl script.

Build.bat and vcregress.bat got similar treatment years ago. I'm not sure
why install.bat wasn't treated at the same time, but it seems like a good
idea anyway.

The immediate problem with the old install.bat was that it had quoting
issues, and wouldn't work if the target directory's name contained spaces.
This fixes that problem.

I committed this to master yesterday, this is a backpatch of the same for
all supported versions.

8 years agoMake numeric form of PG version number readily available in Makefiles.
Tom Lane [Sun, 5 Jul 2015 16:01:02 +0000 (12:01 -0400)]
Make numeric form of PG version number readily available in Makefiles.

Expose PG_VERSION_NUM (e.g., "90600") as a Make variable; but for
consistency with the other Make variables holding similar info,
call the variable just VERSION_NUM not PG_VERSION_NUM.

There was some discussion of making this value available as a pg_config
value as well.  However, that would entail substantially more work than
this two-line patch.  Given that there was not exactly universal consensus
that we need this at all, let's just do a minimal amount of work for now.

Back-patch of commit a5d489ccb7e613c7ca3be6141092b8c1d2c13fa7, so that this
variable is actually useful for its intended purpose sometime before 2020.

Michael Paquier, reviewed by Pavel Stehule

8 years agoPL/Perl: Add alternative expected file for Perl 5.22
Peter Eisentraut [Fri, 3 Jul 2015 22:04:33 +0000 (18:04 -0400)]
PL/Perl: Add alternative expected file for Perl 5.22

8 years agoFix broken link in documentation.
Tom Lane [Tue, 30 Jun 2015 22:47:32 +0000 (18:47 -0400)]
Fix broken link in documentation.

HP's web server has apparently become case-sensitive sometime recently.
Per bug #13479 from Daniel Abraham.  Corrected link identified by Alvaro.

8 years agoTest -lrt for sched_yield
Alvaro Herrera [Tue, 30 Jun 2015 17:20:37 +0000 (14:20 -0300)]
Test -lrt for sched_yield

Apparently, this is needed in some Solaris versions.

Author: Oskari Saarenmaa

8 years agoRevoke incorrectly applied patch version
Simon Riggs [Sat, 27 Jun 2015 01:22:45 +0000 (02:22 +0100)]
Revoke incorrectly applied patch version

8 years agoAvoid hot standby cancels from VAC FREEZE
Simon Riggs [Fri, 26 Jun 2015 23:48:27 +0000 (00:48 +0100)]
Avoid hot standby cancels from VAC FREEZE

VACUUM FREEZE generated false cancelations of standby queries on an
otherwise idle master. Caused by an off-by-one error on cutoff_xid
which goes back to original commit.

Backpatch to all versions 9.0+

Analysis and report by Marco Nenciarini

Bug fix by Simon Riggs

8 years agoFix the logic for putting relations into the relcache init file.
Tom Lane [Thu, 25 Jun 2015 18:39:06 +0000 (14:39 -0400)]
Fix the logic for putting relations into the relcache init file.

Commit f3b5565dd4e59576be4c772da364704863e6a835 was a couple of bricks shy
of a load; specifically, it missed putting pg_trigger_tgrelid_tgname_index
into the relcache init file, because that index is not used by any
syscache.  However, we have historically nailed that index into cache for
performance reasons.  The upshot was that load_relcache_init_file always
decided that the init file was busted and silently ignored it, resulting
in a significant hit to backend startup speed.

To fix, reinstantiate RelationIdIsInInitFile() as a wrapper around
RelationSupportsSysCache(), which can know about additional relations
that should be in the init file despite being unknown to syscache.c.

Also install some guards against future mistakes of this type: make
write_relcache_init_file Assert that all nailed relations get written to
the init file, and make load_relcache_init_file emit a WARNING if it takes
the "wrong number of nailed relations" exit path.  Now that we remove the
init files during postmaster startup, that case should never occur in the
field, even if we are starting a minor-version update that added or removed
rels from the nailed set.  So the warning shouldn't ever be seen by end
users, but it will show up in the regression tests if somebody breaks this
logic.

Back-patch to all supported branches, like the previous commit.

8 years agoFix thinko in comment (launcher -> worker)
Alvaro Herrera [Sat, 20 Jun 2015 14:45:58 +0000 (11:45 -0300)]
Fix thinko in comment (launcher -> worker)

8 years agoClamp autovacuum launcher sleep time to 5 minutes
Alvaro Herrera [Fri, 19 Jun 2015 15:44:33 +0000 (12:44 -0300)]
Clamp autovacuum launcher sleep time to 5 minutes

This avoids the problem that it might go to sleep for an unreasonable
amount of time in unusual conditions like the server clock moving
backwards an unreasonable amount of time.

(Simply moving the server clock forward again doesn't solve the problem
unless you wake up the autovacuum launcher manually, say by sending it
SIGHUP).

Per trouble report from Prakash Itnal in
https://www.postgresql.org/message-id/CAHC5u79-UqbapAABH2t4Rh2eYdyge0Zid-X=Xz-ZWZCBK42S0Q@mail.gmail.com

Analyzed independently by Haribabu Kommi and Tom Lane.

8 years agoCheck for out of memory when allocating sqlca.
Michael Meskes [Mon, 15 Jun 2015 12:21:03 +0000 (14:21 +0200)]
Check for out of memory when allocating sqlca.

Patch by Michael Paquier

Conflicts:
src/interfaces/ecpg/ecpglib/connect.c

8 years agoFix memory leak in ecpglib's connect function.
Michael Meskes [Mon, 15 Jun 2015 12:20:09 +0000 (14:20 +0200)]
Fix memory leak in ecpglib's connect function.

Patch by Michael Paquier

8 years agoFixed some memory leaks in ECPG.
Michael Meskes [Fri, 12 Jun 2015 12:52:55 +0000 (14:52 +0200)]
Fixed some memory leaks in ECPG.

Patch by Michael Paquier

Conflicts:
src/interfaces/ecpg/preproc/variable.c
src/interfaces/ecpg/preproc/pgc.l
src/interfaces/ecpg/preproc/descriptor.c

8 years agoFix intoasc() in Informix compat lib. This function used to be a noop.
Michael Meskes [Fri, 12 Jun 2015 12:50:47 +0000 (14:50 +0200)]
Fix intoasc() in Informix compat lib. This function used to be a noop.

Patch by Michael Paquier

8 years agoStamp 9.0.22. REL9_0_22
Tom Lane [Tue, 9 Jun 2015 19:36:16 +0000 (15:36 -0400)]
Stamp 9.0.22.