gitlab-pg_query 1.3.1 → 2.0.4

Sign up to get free protection for your applications and to get access to all the features.
Files changed (480) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +217 -99
  3. data/README.md +92 -69
  4. data/Rakefile +85 -5
  5. data/ext/pg_query/extconf.rb +3 -40
  6. data/ext/pg_query/guc-file.c +0 -0
  7. data/ext/pg_query/include/access/amapi.h +246 -0
  8. data/ext/pg_query/include/access/attmap.h +52 -0
  9. data/ext/pg_query/include/access/attnum.h +64 -0
  10. data/ext/pg_query/include/access/clog.h +61 -0
  11. data/ext/pg_query/include/access/commit_ts.h +77 -0
  12. data/ext/pg_query/include/access/detoast.h +92 -0
  13. data/ext/pg_query/include/access/genam.h +228 -0
  14. data/ext/pg_query/include/access/gin.h +78 -0
  15. data/ext/pg_query/include/access/htup.h +89 -0
  16. data/ext/pg_query/include/access/htup_details.h +819 -0
  17. data/ext/pg_query/include/access/itup.h +161 -0
  18. data/ext/pg_query/include/access/parallel.h +82 -0
  19. data/ext/pg_query/include/access/printtup.h +35 -0
  20. data/ext/pg_query/include/access/relation.h +28 -0
  21. data/ext/pg_query/include/access/relscan.h +176 -0
  22. data/ext/pg_query/include/access/rmgr.h +35 -0
  23. data/ext/pg_query/include/access/rmgrlist.h +49 -0
  24. data/ext/pg_query/include/access/sdir.h +58 -0
  25. data/ext/pg_query/include/access/skey.h +151 -0
  26. data/ext/pg_query/include/access/stratnum.h +83 -0
  27. data/ext/pg_query/include/access/sysattr.h +29 -0
  28. data/ext/pg_query/include/access/table.h +27 -0
  29. data/ext/pg_query/include/access/tableam.h +1825 -0
  30. data/ext/pg_query/include/access/transam.h +265 -0
  31. data/ext/pg_query/include/access/tupconvert.h +51 -0
  32. data/ext/pg_query/include/access/tupdesc.h +154 -0
  33. data/ext/pg_query/include/access/tupmacs.h +247 -0
  34. data/ext/pg_query/include/access/twophase.h +61 -0
  35. data/ext/pg_query/include/access/xact.h +463 -0
  36. data/ext/pg_query/include/access/xlog.h +398 -0
  37. data/ext/pg_query/include/access/xlog_internal.h +330 -0
  38. data/ext/pg_query/include/access/xlogdefs.h +109 -0
  39. data/ext/pg_query/include/access/xloginsert.h +64 -0
  40. data/ext/pg_query/include/access/xlogreader.h +327 -0
  41. data/ext/pg_query/include/access/xlogrecord.h +227 -0
  42. data/ext/pg_query/include/bootstrap/bootstrap.h +62 -0
  43. data/ext/pg_query/include/c.h +1322 -0
  44. data/ext/pg_query/include/catalog/catalog.h +42 -0
  45. data/ext/pg_query/include/catalog/catversion.h +58 -0
  46. data/ext/pg_query/include/catalog/dependency.h +275 -0
  47. data/ext/pg_query/include/catalog/genbki.h +64 -0
  48. data/ext/pg_query/include/catalog/index.h +199 -0
  49. data/ext/pg_query/include/catalog/indexing.h +366 -0
  50. data/ext/pg_query/include/catalog/namespace.h +188 -0
  51. data/ext/pg_query/include/catalog/objectaccess.h +197 -0
  52. data/ext/pg_query/include/catalog/objectaddress.h +84 -0
  53. data/ext/pg_query/include/catalog/pg_aggregate.h +176 -0
  54. data/ext/pg_query/include/catalog/pg_aggregate_d.h +77 -0
  55. data/ext/pg_query/include/catalog/pg_am.h +60 -0
  56. data/ext/pg_query/include/catalog/pg_am_d.h +45 -0
  57. data/ext/pg_query/include/catalog/pg_attribute.h +204 -0
  58. data/ext/pg_query/include/catalog/pg_attribute_d.h +59 -0
  59. data/ext/pg_query/include/catalog/pg_authid.h +58 -0
  60. data/ext/pg_query/include/catalog/pg_authid_d.h +49 -0
  61. data/ext/pg_query/include/catalog/pg_class.h +200 -0
  62. data/ext/pg_query/include/catalog/pg_class_d.h +103 -0
  63. data/ext/pg_query/include/catalog/pg_collation.h +73 -0
  64. data/ext/pg_query/include/catalog/pg_collation_d.h +45 -0
  65. data/ext/pg_query/include/catalog/pg_constraint.h +247 -0
  66. data/ext/pg_query/include/catalog/pg_constraint_d.h +67 -0
  67. data/ext/pg_query/include/catalog/pg_control.h +250 -0
  68. data/ext/pg_query/include/catalog/pg_conversion.h +72 -0
  69. data/ext/pg_query/include/catalog/pg_conversion_d.h +35 -0
  70. data/ext/pg_query/include/catalog/pg_depend.h +73 -0
  71. data/ext/pg_query/include/catalog/pg_depend_d.h +34 -0
  72. data/ext/pg_query/include/catalog/pg_event_trigger.h +51 -0
  73. data/ext/pg_query/include/catalog/pg_event_trigger_d.h +34 -0
  74. data/ext/pg_query/include/catalog/pg_index.h +80 -0
  75. data/ext/pg_query/include/catalog/pg_index_d.h +56 -0
  76. data/ext/pg_query/include/catalog/pg_language.h +67 -0
  77. data/ext/pg_query/include/catalog/pg_language_d.h +39 -0
  78. data/ext/pg_query/include/catalog/pg_namespace.h +59 -0
  79. data/ext/pg_query/include/catalog/pg_namespace_d.h +34 -0
  80. data/ext/pg_query/include/catalog/pg_opclass.h +85 -0
  81. data/ext/pg_query/include/catalog/pg_opclass_d.h +49 -0
  82. data/ext/pg_query/include/catalog/pg_operator.h +102 -0
  83. data/ext/pg_query/include/catalog/pg_operator_d.h +106 -0
  84. data/ext/pg_query/include/catalog/pg_opfamily.h +60 -0
  85. data/ext/pg_query/include/catalog/pg_opfamily_d.h +47 -0
  86. data/ext/pg_query/include/catalog/pg_partitioned_table.h +63 -0
  87. data/ext/pg_query/include/catalog/pg_partitioned_table_d.h +35 -0
  88. data/ext/pg_query/include/catalog/pg_proc.h +211 -0
  89. data/ext/pg_query/include/catalog/pg_proc_d.h +99 -0
  90. data/ext/pg_query/include/catalog/pg_publication.h +115 -0
  91. data/ext/pg_query/include/catalog/pg_publication_d.h +36 -0
  92. data/ext/pg_query/include/catalog/pg_replication_origin.h +57 -0
  93. data/ext/pg_query/include/catalog/pg_replication_origin_d.h +29 -0
  94. data/ext/pg_query/include/catalog/pg_statistic.h +275 -0
  95. data/ext/pg_query/include/catalog/pg_statistic_d.h +194 -0
  96. data/ext/pg_query/include/catalog/pg_statistic_ext.h +74 -0
  97. data/ext/pg_query/include/catalog/pg_statistic_ext_d.h +40 -0
  98. data/ext/pg_query/include/catalog/pg_transform.h +45 -0
  99. data/ext/pg_query/include/catalog/pg_transform_d.h +32 -0
  100. data/ext/pg_query/include/catalog/pg_trigger.h +137 -0
  101. data/ext/pg_query/include/catalog/pg_trigger_d.h +106 -0
  102. data/ext/pg_query/include/catalog/pg_ts_config.h +50 -0
  103. data/ext/pg_query/include/catalog/pg_ts_config_d.h +32 -0
  104. data/ext/pg_query/include/catalog/pg_ts_dict.h +54 -0
  105. data/ext/pg_query/include/catalog/pg_ts_dict_d.h +33 -0
  106. data/ext/pg_query/include/catalog/pg_ts_parser.h +57 -0
  107. data/ext/pg_query/include/catalog/pg_ts_parser_d.h +35 -0
  108. data/ext/pg_query/include/catalog/pg_ts_template.h +48 -0
  109. data/ext/pg_query/include/catalog/pg_ts_template_d.h +32 -0
  110. data/ext/pg_query/include/catalog/pg_type.h +372 -0
  111. data/ext/pg_query/include/catalog/pg_type_d.h +285 -0
  112. data/ext/pg_query/include/catalog/storage.h +48 -0
  113. data/ext/pg_query/include/commands/async.h +54 -0
  114. data/ext/pg_query/include/commands/dbcommands.h +35 -0
  115. data/ext/pg_query/include/commands/defrem.h +173 -0
  116. data/ext/pg_query/include/commands/event_trigger.h +88 -0
  117. data/ext/pg_query/include/commands/explain.h +127 -0
  118. data/ext/pg_query/include/commands/prepare.h +61 -0
  119. data/ext/pg_query/include/commands/tablespace.h +67 -0
  120. data/ext/pg_query/include/commands/trigger.h +277 -0
  121. data/ext/pg_query/include/commands/user.h +37 -0
  122. data/ext/pg_query/include/commands/vacuum.h +293 -0
  123. data/ext/pg_query/include/commands/variable.h +38 -0
  124. data/ext/pg_query/include/common/file_perm.h +56 -0
  125. data/ext/pg_query/include/common/hashfn.h +104 -0
  126. data/ext/pg_query/include/common/ip.h +37 -0
  127. data/ext/pg_query/include/common/keywords.h +33 -0
  128. data/ext/pg_query/include/common/kwlookup.h +44 -0
  129. data/ext/pg_query/include/common/relpath.h +90 -0
  130. data/ext/pg_query/include/common/string.h +19 -0
  131. data/ext/pg_query/include/common/unicode_combining_table.h +196 -0
  132. data/ext/pg_query/include/datatype/timestamp.h +197 -0
  133. data/ext/pg_query/include/executor/execdesc.h +70 -0
  134. data/ext/pg_query/include/executor/executor.h +614 -0
  135. data/ext/pg_query/include/executor/functions.h +41 -0
  136. data/ext/pg_query/include/executor/instrument.h +101 -0
  137. data/ext/pg_query/include/executor/spi.h +175 -0
  138. data/ext/pg_query/include/executor/tablefunc.h +67 -0
  139. data/ext/pg_query/include/executor/tuptable.h +487 -0
  140. data/ext/pg_query/include/fmgr.h +775 -0
  141. data/ext/pg_query/include/funcapi.h +348 -0
  142. data/ext/pg_query/include/getaddrinfo.h +162 -0
  143. data/ext/pg_query/include/jit/jit.h +105 -0
  144. data/ext/pg_query/include/kwlist_d.h +1072 -0
  145. data/ext/pg_query/include/lib/ilist.h +727 -0
  146. data/ext/pg_query/include/lib/pairingheap.h +102 -0
  147. data/ext/pg_query/include/lib/simplehash.h +1059 -0
  148. data/ext/pg_query/include/lib/stringinfo.h +161 -0
  149. data/ext/pg_query/include/libpq/auth.h +29 -0
  150. data/ext/pg_query/include/libpq/crypt.h +46 -0
  151. data/ext/pg_query/include/libpq/hba.h +140 -0
  152. data/ext/pg_query/include/libpq/libpq-be.h +326 -0
  153. data/ext/pg_query/include/libpq/libpq.h +133 -0
  154. data/ext/pg_query/include/libpq/pqcomm.h +208 -0
  155. data/ext/pg_query/include/libpq/pqformat.h +210 -0
  156. data/ext/pg_query/include/libpq/pqsignal.h +42 -0
  157. data/ext/pg_query/include/mb/pg_wchar.h +672 -0
  158. data/ext/pg_query/include/mb/stringinfo_mb.h +24 -0
  159. data/ext/pg_query/include/miscadmin.h +476 -0
  160. data/ext/pg_query/include/nodes/bitmapset.h +122 -0
  161. data/ext/pg_query/include/nodes/execnodes.h +2520 -0
  162. data/ext/pg_query/include/nodes/extensible.h +160 -0
  163. data/ext/pg_query/include/nodes/lockoptions.h +61 -0
  164. data/ext/pg_query/include/nodes/makefuncs.h +108 -0
  165. data/ext/pg_query/include/nodes/memnodes.h +108 -0
  166. data/ext/pg_query/include/nodes/nodeFuncs.h +162 -0
  167. data/ext/pg_query/include/nodes/nodes.h +842 -0
  168. data/ext/pg_query/include/nodes/params.h +170 -0
  169. data/ext/pg_query/include/nodes/parsenodes.h +3579 -0
  170. data/ext/pg_query/include/nodes/pathnodes.h +2556 -0
  171. data/ext/pg_query/include/nodes/pg_list.h +605 -0
  172. data/ext/pg_query/include/nodes/plannodes.h +1251 -0
  173. data/ext/pg_query/include/nodes/primnodes.h +1541 -0
  174. data/ext/pg_query/include/nodes/print.h +34 -0
  175. data/ext/pg_query/include/nodes/tidbitmap.h +75 -0
  176. data/ext/pg_query/include/nodes/value.h +61 -0
  177. data/ext/pg_query/include/optimizer/cost.h +206 -0
  178. data/ext/pg_query/include/optimizer/geqo.h +88 -0
  179. data/ext/pg_query/include/optimizer/geqo_gene.h +45 -0
  180. data/ext/pg_query/include/optimizer/optimizer.h +199 -0
  181. data/ext/pg_query/include/optimizer/paths.h +249 -0
  182. data/ext/pg_query/include/optimizer/planmain.h +119 -0
  183. data/ext/pg_query/include/parser/analyze.h +49 -0
  184. data/ext/pg_query/include/parser/gram.h +1067 -0
  185. data/ext/pg_query/include/parser/gramparse.h +75 -0
  186. data/ext/pg_query/include/parser/kwlist.h +477 -0
  187. data/ext/pg_query/include/parser/parse_agg.h +68 -0
  188. data/ext/pg_query/include/parser/parse_clause.h +54 -0
  189. data/ext/pg_query/include/parser/parse_coerce.h +97 -0
  190. data/ext/pg_query/include/parser/parse_collate.h +27 -0
  191. data/ext/pg_query/include/parser/parse_expr.h +26 -0
  192. data/ext/pg_query/include/parser/parse_func.h +73 -0
  193. data/ext/pg_query/include/parser/parse_node.h +327 -0
  194. data/ext/pg_query/include/parser/parse_oper.h +67 -0
  195. data/ext/pg_query/include/parser/parse_relation.h +123 -0
  196. data/ext/pg_query/include/parser/parse_target.h +46 -0
  197. data/ext/pg_query/include/parser/parse_type.h +60 -0
  198. data/ext/pg_query/include/parser/parser.h +41 -0
  199. data/ext/pg_query/include/parser/parsetree.h +61 -0
  200. data/ext/pg_query/include/parser/scanner.h +152 -0
  201. data/ext/pg_query/include/parser/scansup.h +30 -0
  202. data/ext/pg_query/include/partitioning/partdefs.h +26 -0
  203. data/ext/pg_query/include/pg_config.h +989 -0
  204. data/ext/pg_query/include/pg_config_ext.h +8 -0
  205. data/ext/pg_query/include/pg_config_manual.h +350 -0
  206. data/ext/pg_query/include/pg_config_os.h +8 -0
  207. data/ext/pg_query/include/pg_getopt.h +56 -0
  208. data/ext/pg_query/include/pg_query.h +121 -0
  209. data/ext/pg_query/include/pg_query_enum_defs.c +2454 -0
  210. data/ext/pg_query/include/pg_query_fingerprint_conds.c +875 -0
  211. data/ext/pg_query/include/pg_query_fingerprint_defs.c +12413 -0
  212. data/ext/pg_query/include/pg_query_json_helper.c +61 -0
  213. data/ext/pg_query/include/pg_query_outfuncs_conds.c +686 -0
  214. data/ext/pg_query/include/pg_query_outfuncs_defs.c +2437 -0
  215. data/ext/pg_query/include/pg_query_readfuncs_conds.c +222 -0
  216. data/ext/pg_query/include/pg_query_readfuncs_defs.c +2878 -0
  217. data/ext/pg_query/include/pg_trace.h +17 -0
  218. data/ext/pg_query/include/pgstat.h +1487 -0
  219. data/ext/pg_query/include/pgtime.h +84 -0
  220. data/ext/pg_query/include/pl_gram.h +385 -0
  221. data/ext/pg_query/include/pl_reserved_kwlist.h +52 -0
  222. data/ext/pg_query/include/pl_reserved_kwlist_d.h +114 -0
  223. data/ext/pg_query/include/pl_unreserved_kwlist.h +112 -0
  224. data/ext/pg_query/include/pl_unreserved_kwlist_d.h +246 -0
  225. data/ext/pg_query/include/plerrcodes.h +990 -0
  226. data/ext/pg_query/include/plpgsql.h +1347 -0
  227. data/ext/pg_query/include/port.h +524 -0
  228. data/ext/pg_query/include/port/atomics.h +524 -0
  229. data/ext/pg_query/include/port/atomics/arch-arm.h +26 -0
  230. data/ext/pg_query/include/port/atomics/arch-ppc.h +254 -0
  231. data/ext/pg_query/include/port/atomics/arch-x86.h +252 -0
  232. data/ext/pg_query/include/port/atomics/fallback.h +170 -0
  233. data/ext/pg_query/include/port/atomics/generic-gcc.h +286 -0
  234. data/ext/pg_query/include/port/atomics/generic.h +401 -0
  235. data/ext/pg_query/include/port/pg_bitutils.h +226 -0
  236. data/ext/pg_query/include/port/pg_bswap.h +161 -0
  237. data/ext/pg_query/include/port/pg_crc32c.h +101 -0
  238. data/ext/pg_query/include/portability/instr_time.h +256 -0
  239. data/ext/pg_query/include/postgres.h +764 -0
  240. data/ext/pg_query/include/postgres_ext.h +74 -0
  241. data/ext/pg_query/include/postmaster/autovacuum.h +83 -0
  242. data/ext/pg_query/include/postmaster/bgworker.h +161 -0
  243. data/ext/pg_query/include/postmaster/bgworker_internals.h +64 -0
  244. data/ext/pg_query/include/postmaster/bgwriter.h +45 -0
  245. data/ext/pg_query/include/postmaster/fork_process.h +17 -0
  246. data/ext/pg_query/include/postmaster/interrupt.h +32 -0
  247. data/ext/pg_query/include/postmaster/pgarch.h +39 -0
  248. data/ext/pg_query/include/postmaster/postmaster.h +77 -0
  249. data/ext/pg_query/include/postmaster/syslogger.h +98 -0
  250. data/ext/pg_query/include/postmaster/walwriter.h +21 -0
  251. data/ext/pg_query/include/protobuf-c.h +1106 -0
  252. data/ext/pg_query/include/protobuf-c/protobuf-c.h +1106 -0
  253. data/ext/pg_query/include/protobuf/pg_query.pb-c.h +10846 -0
  254. data/ext/pg_query/include/protobuf/pg_query.pb.h +124718 -0
  255. data/ext/pg_query/include/regex/regex.h +184 -0
  256. data/ext/pg_query/include/replication/logicallauncher.h +31 -0
  257. data/ext/pg_query/include/replication/logicalproto.h +110 -0
  258. data/ext/pg_query/include/replication/logicalworker.h +19 -0
  259. data/ext/pg_query/include/replication/origin.h +73 -0
  260. data/ext/pg_query/include/replication/reorderbuffer.h +467 -0
  261. data/ext/pg_query/include/replication/slot.h +219 -0
  262. data/ext/pg_query/include/replication/syncrep.h +115 -0
  263. data/ext/pg_query/include/replication/walreceiver.h +340 -0
  264. data/ext/pg_query/include/replication/walsender.h +74 -0
  265. data/ext/pg_query/include/rewrite/prs2lock.h +46 -0
  266. data/ext/pg_query/include/rewrite/rewriteHandler.h +40 -0
  267. data/ext/pg_query/include/rewrite/rewriteManip.h +87 -0
  268. data/ext/pg_query/include/rewrite/rewriteSupport.h +26 -0
  269. data/ext/pg_query/include/storage/backendid.h +37 -0
  270. data/ext/pg_query/include/storage/block.h +121 -0
  271. data/ext/pg_query/include/storage/buf.h +46 -0
  272. data/ext/pg_query/include/storage/bufmgr.h +292 -0
  273. data/ext/pg_query/include/storage/bufpage.h +459 -0
  274. data/ext/pg_query/include/storage/condition_variable.h +62 -0
  275. data/ext/pg_query/include/storage/dsm.h +61 -0
  276. data/ext/pg_query/include/storage/dsm_impl.h +75 -0
  277. data/ext/pg_query/include/storage/fd.h +168 -0
  278. data/ext/pg_query/include/storage/ipc.h +81 -0
  279. data/ext/pg_query/include/storage/item.h +19 -0
  280. data/ext/pg_query/include/storage/itemid.h +184 -0
  281. data/ext/pg_query/include/storage/itemptr.h +206 -0
  282. data/ext/pg_query/include/storage/large_object.h +100 -0
  283. data/ext/pg_query/include/storage/latch.h +190 -0
  284. data/ext/pg_query/include/storage/lmgr.h +114 -0
  285. data/ext/pg_query/include/storage/lock.h +612 -0
  286. data/ext/pg_query/include/storage/lockdefs.h +59 -0
  287. data/ext/pg_query/include/storage/lwlock.h +232 -0
  288. data/ext/pg_query/include/storage/lwlocknames.h +51 -0
  289. data/ext/pg_query/include/storage/off.h +57 -0
  290. data/ext/pg_query/include/storage/pg_sema.h +61 -0
  291. data/ext/pg_query/include/storage/pg_shmem.h +90 -0
  292. data/ext/pg_query/include/storage/pmsignal.h +94 -0
  293. data/ext/pg_query/include/storage/predicate.h +87 -0
  294. data/ext/pg_query/include/storage/proc.h +333 -0
  295. data/ext/pg_query/include/storage/proclist_types.h +51 -0
  296. data/ext/pg_query/include/storage/procsignal.h +75 -0
  297. data/ext/pg_query/include/storage/relfilenode.h +99 -0
  298. data/ext/pg_query/include/storage/s_lock.h +1047 -0
  299. data/ext/pg_query/include/storage/sharedfileset.h +45 -0
  300. data/ext/pg_query/include/storage/shm_mq.h +85 -0
  301. data/ext/pg_query/include/storage/shm_toc.h +58 -0
  302. data/ext/pg_query/include/storage/shmem.h +81 -0
  303. data/ext/pg_query/include/storage/sinval.h +153 -0
  304. data/ext/pg_query/include/storage/sinvaladt.h +43 -0
  305. data/ext/pg_query/include/storage/smgr.h +109 -0
  306. data/ext/pg_query/include/storage/spin.h +77 -0
  307. data/ext/pg_query/include/storage/standby.h +91 -0
  308. data/ext/pg_query/include/storage/standbydefs.h +74 -0
  309. data/ext/pg_query/include/storage/sync.h +62 -0
  310. data/ext/pg_query/include/tcop/cmdtag.h +58 -0
  311. data/ext/pg_query/include/tcop/cmdtaglist.h +217 -0
  312. data/ext/pg_query/include/tcop/deparse_utility.h +108 -0
  313. data/ext/pg_query/include/tcop/dest.h +149 -0
  314. data/ext/pg_query/include/tcop/fastpath.h +21 -0
  315. data/ext/pg_query/include/tcop/pquery.h +45 -0
  316. data/ext/pg_query/include/tcop/tcopprot.h +89 -0
  317. data/ext/pg_query/include/tcop/utility.h +108 -0
  318. data/ext/pg_query/include/tsearch/ts_cache.h +98 -0
  319. data/ext/pg_query/include/utils/acl.h +312 -0
  320. data/ext/pg_query/include/utils/aclchk_internal.h +45 -0
  321. data/ext/pg_query/include/utils/array.h +458 -0
  322. data/ext/pg_query/include/utils/builtins.h +127 -0
  323. data/ext/pg_query/include/utils/bytea.h +27 -0
  324. data/ext/pg_query/include/utils/catcache.h +231 -0
  325. data/ext/pg_query/include/utils/date.h +90 -0
  326. data/ext/pg_query/include/utils/datetime.h +343 -0
  327. data/ext/pg_query/include/utils/datum.h +68 -0
  328. data/ext/pg_query/include/utils/dsa.h +123 -0
  329. data/ext/pg_query/include/utils/dynahash.h +19 -0
  330. data/ext/pg_query/include/utils/elog.h +439 -0
  331. data/ext/pg_query/include/utils/errcodes.h +352 -0
  332. data/ext/pg_query/include/utils/expandeddatum.h +159 -0
  333. data/ext/pg_query/include/utils/expandedrecord.h +231 -0
  334. data/ext/pg_query/include/utils/float.h +356 -0
  335. data/ext/pg_query/include/utils/fmgroids.h +2657 -0
  336. data/ext/pg_query/include/utils/fmgrprotos.h +2646 -0
  337. data/ext/pg_query/include/utils/fmgrtab.h +48 -0
  338. data/ext/pg_query/include/utils/guc.h +443 -0
  339. data/ext/pg_query/include/utils/guc_tables.h +272 -0
  340. data/ext/pg_query/include/utils/hsearch.h +149 -0
  341. data/ext/pg_query/include/utils/inval.h +64 -0
  342. data/ext/pg_query/include/utils/lsyscache.h +197 -0
  343. data/ext/pg_query/include/utils/memdebug.h +82 -0
  344. data/ext/pg_query/include/utils/memutils.h +225 -0
  345. data/ext/pg_query/include/utils/numeric.h +76 -0
  346. data/ext/pg_query/include/utils/palloc.h +136 -0
  347. data/ext/pg_query/include/utils/partcache.h +102 -0
  348. data/ext/pg_query/include/utils/pg_locale.h +119 -0
  349. data/ext/pg_query/include/utils/pg_lsn.h +29 -0
  350. data/ext/pg_query/include/utils/pidfile.h +56 -0
  351. data/ext/pg_query/include/utils/plancache.h +235 -0
  352. data/ext/pg_query/include/utils/portal.h +241 -0
  353. data/ext/pg_query/include/utils/probes.h +114 -0
  354. data/ext/pg_query/include/utils/ps_status.h +25 -0
  355. data/ext/pg_query/include/utils/queryenvironment.h +74 -0
  356. data/ext/pg_query/include/utils/regproc.h +28 -0
  357. data/ext/pg_query/include/utils/rel.h +644 -0
  358. data/ext/pg_query/include/utils/relcache.h +151 -0
  359. data/ext/pg_query/include/utils/reltrigger.h +81 -0
  360. data/ext/pg_query/include/utils/resowner.h +86 -0
  361. data/ext/pg_query/include/utils/rls.h +50 -0
  362. data/ext/pg_query/include/utils/ruleutils.h +44 -0
  363. data/ext/pg_query/include/utils/sharedtuplestore.h +61 -0
  364. data/ext/pg_query/include/utils/snapmgr.h +158 -0
  365. data/ext/pg_query/include/utils/snapshot.h +206 -0
  366. data/ext/pg_query/include/utils/sortsupport.h +276 -0
  367. data/ext/pg_query/include/utils/syscache.h +219 -0
  368. data/ext/pg_query/include/utils/timeout.h +88 -0
  369. data/ext/pg_query/include/utils/timestamp.h +116 -0
  370. data/ext/pg_query/include/utils/tuplesort.h +277 -0
  371. data/ext/pg_query/include/utils/tuplestore.h +91 -0
  372. data/ext/pg_query/include/utils/typcache.h +202 -0
  373. data/ext/pg_query/include/utils/tzparser.h +39 -0
  374. data/ext/pg_query/include/utils/varlena.h +39 -0
  375. data/ext/pg_query/include/utils/xml.h +84 -0
  376. data/ext/pg_query/include/xxhash.h +5445 -0
  377. data/ext/pg_query/include/xxhash/xxhash.h +5445 -0
  378. data/ext/pg_query/pg_query.c +104 -0
  379. data/ext/pg_query/pg_query.pb-c.c +37628 -0
  380. data/ext/pg_query/pg_query_deparse.c +9959 -0
  381. data/ext/pg_query/pg_query_fingerprint.c +295 -0
  382. data/ext/pg_query/pg_query_fingerprint.h +8 -0
  383. data/ext/pg_query/pg_query_internal.h +24 -0
  384. data/ext/pg_query/pg_query_json_plpgsql.c +738 -0
  385. data/ext/pg_query/pg_query_json_plpgsql.h +9 -0
  386. data/ext/pg_query/pg_query_normalize.c +439 -0
  387. data/ext/pg_query/pg_query_outfuncs.h +10 -0
  388. data/ext/pg_query/pg_query_outfuncs_json.c +297 -0
  389. data/ext/pg_query/pg_query_outfuncs_protobuf.c +237 -0
  390. data/ext/pg_query/pg_query_parse.c +148 -0
  391. data/ext/pg_query/pg_query_parse_plpgsql.c +460 -0
  392. data/ext/pg_query/pg_query_readfuncs.h +11 -0
  393. data/ext/pg_query/pg_query_readfuncs_protobuf.c +142 -0
  394. data/ext/pg_query/pg_query_ruby.c +108 -12
  395. data/ext/pg_query/pg_query_scan.c +173 -0
  396. data/ext/pg_query/pg_query_split.c +221 -0
  397. data/ext/pg_query/protobuf-c.c +3660 -0
  398. data/ext/pg_query/src_backend_catalog_namespace.c +1051 -0
  399. data/ext/pg_query/src_backend_catalog_pg_proc.c +142 -0
  400. data/ext/pg_query/src_backend_commands_define.c +117 -0
  401. data/ext/pg_query/src_backend_libpq_pqcomm.c +651 -0
  402. data/ext/pg_query/src_backend_nodes_bitmapset.c +513 -0
  403. data/ext/pg_query/src_backend_nodes_copyfuncs.c +6013 -0
  404. data/ext/pg_query/src_backend_nodes_equalfuncs.c +4003 -0
  405. data/ext/pg_query/src_backend_nodes_extensible.c +99 -0
  406. data/ext/pg_query/src_backend_nodes_list.c +922 -0
  407. data/ext/pg_query/src_backend_nodes_makefuncs.c +417 -0
  408. data/ext/pg_query/src_backend_nodes_nodeFuncs.c +1363 -0
  409. data/ext/pg_query/src_backend_nodes_value.c +84 -0
  410. data/ext/pg_query/src_backend_parser_gram.c +47456 -0
  411. data/ext/pg_query/src_backend_parser_parse_expr.c +313 -0
  412. data/ext/pg_query/src_backend_parser_parser.c +497 -0
  413. data/ext/pg_query/src_backend_parser_scan.c +7091 -0
  414. data/ext/pg_query/src_backend_parser_scansup.c +160 -0
  415. data/ext/pg_query/src_backend_postmaster_postmaster.c +2230 -0
  416. data/ext/pg_query/src_backend_storage_ipc_ipc.c +192 -0
  417. data/ext/pg_query/src_backend_storage_lmgr_s_lock.c +370 -0
  418. data/ext/pg_query/src_backend_tcop_postgres.c +776 -0
  419. data/ext/pg_query/src_backend_utils_adt_datum.c +326 -0
  420. data/ext/pg_query/src_backend_utils_adt_expandeddatum.c +98 -0
  421. data/ext/pg_query/src_backend_utils_adt_format_type.c +136 -0
  422. data/ext/pg_query/src_backend_utils_adt_ruleutils.c +1683 -0
  423. data/ext/pg_query/src_backend_utils_error_assert.c +74 -0
  424. data/ext/pg_query/src_backend_utils_error_elog.c +1748 -0
  425. data/ext/pg_query/src_backend_utils_fmgr_fmgr.c +570 -0
  426. data/ext/pg_query/src_backend_utils_hash_dynahash.c +1086 -0
  427. data/ext/pg_query/src_backend_utils_init_globals.c +168 -0
  428. data/ext/pg_query/src_backend_utils_mb_mbutils.c +839 -0
  429. data/ext/pg_query/src_backend_utils_misc_guc.c +1831 -0
  430. data/ext/pg_query/src_backend_utils_mmgr_aset.c +1560 -0
  431. data/ext/pg_query/src_backend_utils_mmgr_mcxt.c +1006 -0
  432. data/ext/pg_query/src_common_encnames.c +158 -0
  433. data/ext/pg_query/src_common_keywords.c +39 -0
  434. data/ext/pg_query/src_common_kwlist_d.h +1081 -0
  435. data/ext/pg_query/src_common_kwlookup.c +91 -0
  436. data/ext/pg_query/src_common_psprintf.c +158 -0
  437. data/ext/pg_query/src_common_string.c +86 -0
  438. data/ext/pg_query/src_common_stringinfo.c +336 -0
  439. data/ext/pg_query/src_common_wchar.c +1651 -0
  440. data/ext/pg_query/src_pl_plpgsql_src_pl_comp.c +1133 -0
  441. data/ext/pg_query/src_pl_plpgsql_src_pl_funcs.c +877 -0
  442. data/ext/pg_query/src_pl_plpgsql_src_pl_gram.c +6533 -0
  443. data/ext/pg_query/src_pl_plpgsql_src_pl_handler.c +107 -0
  444. data/ext/pg_query/src_pl_plpgsql_src_pl_reserved_kwlist_d.h +123 -0
  445. data/ext/pg_query/src_pl_plpgsql_src_pl_scanner.c +671 -0
  446. data/ext/pg_query/src_pl_plpgsql_src_pl_unreserved_kwlist_d.h +255 -0
  447. data/ext/pg_query/src_port_erand48.c +127 -0
  448. data/ext/pg_query/src_port_pg_bitutils.c +246 -0
  449. data/ext/pg_query/src_port_pgsleep.c +69 -0
  450. data/ext/pg_query/src_port_pgstrcasecmp.c +83 -0
  451. data/ext/pg_query/src_port_qsort.c +240 -0
  452. data/ext/pg_query/src_port_random.c +31 -0
  453. data/ext/pg_query/src_port_snprintf.c +1449 -0
  454. data/ext/pg_query/src_port_strerror.c +324 -0
  455. data/ext/pg_query/src_port_strnlen.c +39 -0
  456. data/ext/pg_query/xxhash.c +43 -0
  457. data/lib/pg_query.rb +7 -4
  458. data/lib/pg_query/constants.rb +21 -0
  459. data/lib/pg_query/deparse.rb +15 -1581
  460. data/lib/pg_query/filter_columns.rb +88 -85
  461. data/lib/pg_query/fingerprint.rb +122 -87
  462. data/lib/pg_query/json_field_names.rb +1402 -0
  463. data/lib/pg_query/node.rb +31 -0
  464. data/lib/pg_query/param_refs.rb +42 -37
  465. data/lib/pg_query/parse.rb +220 -203
  466. data/lib/pg_query/parse_error.rb +1 -1
  467. data/lib/pg_query/pg_query_pb.rb +3211 -0
  468. data/lib/pg_query/scan.rb +23 -0
  469. data/lib/pg_query/treewalker.rb +24 -40
  470. data/lib/pg_query/truncate.rb +71 -42
  471. data/lib/pg_query/version.rb +2 -2
  472. metadata +472 -11
  473. data/ext/pg_query/pg_query_ruby.h +0 -10
  474. data/lib/pg_query/deep_dup.rb +0 -16
  475. data/lib/pg_query/deparse/alter_table.rb +0 -42
  476. data/lib/pg_query/deparse/interval.rb +0 -105
  477. data/lib/pg_query/deparse/keywords.rb +0 -159
  478. data/lib/pg_query/deparse/rename.rb +0 -41
  479. data/lib/pg_query/legacy_parsetree.rb +0 -109
  480. data/lib/pg_query/node_types.rb +0 -296
@@ -0,0 +1,160 @@
1
+ /*--------------------------------------------------------------------
2
+ * Symbols referenced in this file:
3
+ * - downcase_truncate_identifier
4
+ * - downcase_identifier
5
+ * - truncate_identifier
6
+ * - scanner_isspace
7
+ *--------------------------------------------------------------------
8
+ */
9
+
10
+ /*-------------------------------------------------------------------------
11
+ *
12
+ * scansup.c
13
+ * support routines for the lex/flex scanner, used by both the normal
14
+ * backend as well as the bootstrap backend
15
+ *
16
+ * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
17
+ * Portions Copyright (c) 1994, Regents of the University of California
18
+ *
19
+ *
20
+ * IDENTIFICATION
21
+ * src/backend/parser/scansup.c
22
+ *
23
+ *-------------------------------------------------------------------------
24
+ */
25
+ #include "postgres.h"
26
+
27
+ #include <ctype.h>
28
+
29
+ #include "mb/pg_wchar.h"
30
+ #include "parser/scansup.h"
31
+
32
+ /* ----------------
33
+ * scanstr
34
+ *
35
+ * if the string passed in has escaped codes, map the escape codes to actual
36
+ * chars
37
+ *
38
+ * the string returned is palloc'd and should eventually be pfree'd by the
39
+ * caller!
40
+ * ----------------
41
+ */
42
+
43
+
44
+
45
+
46
+ /*
47
+ * downcase_truncate_identifier() --- do appropriate downcasing and
48
+ * truncation of an unquoted identifier. Optionally warn of truncation.
49
+ *
50
+ * Returns a palloc'd string containing the adjusted identifier.
51
+ *
52
+ * Note: in some usages the passed string is not null-terminated.
53
+ *
54
+ * Note: the API of this function is designed to allow for downcasing
55
+ * transformations that increase the string length, but we don't yet
56
+ * support that. If you want to implement it, you'll need to fix
57
+ * SplitIdentifierString() in utils/adt/varlena.c.
58
+ */
59
+ char *
60
+ downcase_truncate_identifier(const char *ident, int len, bool warn)
61
+ {
62
+ return downcase_identifier(ident, len, warn, true);
63
+ }
64
+
65
+ /*
66
+ * a workhorse for downcase_truncate_identifier
67
+ */
68
+ char *
69
+ downcase_identifier(const char *ident, int len, bool warn, bool truncate)
70
+ {
71
+ char *result;
72
+ int i;
73
+ bool enc_is_single_byte;
74
+
75
+ result = palloc(len + 1);
76
+ enc_is_single_byte = pg_database_encoding_max_length() == 1;
77
+
78
+ /*
79
+ * SQL99 specifies Unicode-aware case normalization, which we don't yet
80
+ * have the infrastructure for. Instead we use tolower() to provide a
81
+ * locale-aware translation. However, there are some locales where this
82
+ * is not right either (eg, Turkish may do strange things with 'i' and
83
+ * 'I'). Our current compromise is to use tolower() for characters with
84
+ * the high bit set, as long as they aren't part of a multi-byte
85
+ * character, and use an ASCII-only downcasing for 7-bit characters.
86
+ */
87
+ for (i = 0; i < len; i++)
88
+ {
89
+ unsigned char ch = (unsigned char) ident[i];
90
+
91
+ if (ch >= 'A' && ch <= 'Z')
92
+ ch += 'a' - 'A';
93
+ else if (enc_is_single_byte && IS_HIGHBIT_SET(ch) && isupper(ch))
94
+ ch = tolower(ch);
95
+ result[i] = (char) ch;
96
+ }
97
+ result[i] = '\0';
98
+
99
+ if (i >= NAMEDATALEN && truncate)
100
+ truncate_identifier(result, i, warn);
101
+
102
+ return result;
103
+ }
104
+
105
+
106
+ /*
107
+ * truncate_identifier() --- truncate an identifier to NAMEDATALEN-1 bytes.
108
+ *
109
+ * The given string is modified in-place, if necessary. A warning is
110
+ * issued if requested.
111
+ *
112
+ * We require the caller to pass in the string length since this saves a
113
+ * strlen() call in some common usages.
114
+ */
115
+ void
116
+ truncate_identifier(char *ident, int len, bool warn)
117
+ {
118
+ if (len >= NAMEDATALEN)
119
+ {
120
+ len = pg_mbcliplen(ident, len, NAMEDATALEN - 1);
121
+ if (warn)
122
+ {
123
+ /*
124
+ * We avoid using %.*s here because it can misbehave if the data
125
+ * is not valid in what libc thinks is the prevailing encoding.
126
+ */
127
+ char buf[NAMEDATALEN];
128
+
129
+ memcpy(buf, ident, len);
130
+ buf[len] = '\0';
131
+ ereport(NOTICE,
132
+ (errcode(ERRCODE_NAME_TOO_LONG),
133
+ errmsg("identifier \"%s\" will be truncated to \"%s\"",
134
+ ident, buf)));
135
+ }
136
+ ident[len] = '\0';
137
+ }
138
+ }
139
+
140
+ /*
141
+ * scanner_isspace() --- return true if flex scanner considers char whitespace
142
+ *
143
+ * This should be used instead of the potentially locale-dependent isspace()
144
+ * function when it's important to match the lexer's behavior.
145
+ *
146
+ * In principle we might need similar functions for isalnum etc, but for the
147
+ * moment only isspace seems needed.
148
+ */
149
+ bool
150
+ scanner_isspace(char ch)
151
+ {
152
+ /* This must match scan.l's list of {space} characters */
153
+ if (ch == ' ' ||
154
+ ch == '\t' ||
155
+ ch == '\n' ||
156
+ ch == '\r' ||
157
+ ch == '\f')
158
+ return true;
159
+ return false;
160
+ }
@@ -0,0 +1,2230 @@
1
+ /*--------------------------------------------------------------------
2
+ * Symbols referenced in this file:
3
+ * - ClientAuthInProgress
4
+ *--------------------------------------------------------------------
5
+ */
6
+
7
+ /*-------------------------------------------------------------------------
8
+ *
9
+ * postmaster.c
10
+ * This program acts as a clearing house for requests to the
11
+ * POSTGRES system. Frontend programs send a startup message
12
+ * to the Postmaster and the postmaster uses the info in the
13
+ * message to setup a backend process.
14
+ *
15
+ * The postmaster also manages system-wide operations such as
16
+ * startup and shutdown. The postmaster itself doesn't do those
17
+ * operations, mind you --- it just forks off a subprocess to do them
18
+ * at the right times. It also takes care of resetting the system
19
+ * if a backend crashes.
20
+ *
21
+ * The postmaster process creates the shared memory and semaphore
22
+ * pools during startup, but as a rule does not touch them itself.
23
+ * In particular, it is not a member of the PGPROC array of backends
24
+ * and so it cannot participate in lock-manager operations. Keeping
25
+ * the postmaster away from shared memory operations makes it simpler
26
+ * and more reliable. The postmaster is almost always able to recover
27
+ * from crashes of individual backends by resetting shared memory;
28
+ * if it did much with shared memory then it would be prone to crashing
29
+ * along with the backends.
30
+ *
31
+ * When a request message is received, we now fork() immediately.
32
+ * The child process performs authentication of the request, and
33
+ * then becomes a backend if successful. This allows the auth code
34
+ * to be written in a simple single-threaded style (as opposed to the
35
+ * crufty "poor man's multitasking" code that used to be needed).
36
+ * More importantly, it ensures that blockages in non-multithreaded
37
+ * libraries like SSL or PAM cannot cause denial of service to other
38
+ * clients.
39
+ *
40
+ *
41
+ * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
42
+ * Portions Copyright (c) 1994, Regents of the University of California
43
+ *
44
+ *
45
+ * IDENTIFICATION
46
+ * src/backend/postmaster/postmaster.c
47
+ *
48
+ * NOTES
49
+ *
50
+ * Initialization:
51
+ * The Postmaster sets up shared memory data structures
52
+ * for the backends.
53
+ *
54
+ * Synchronization:
55
+ * The Postmaster shares memory with the backends but should avoid
56
+ * touching shared memory, so as not to become stuck if a crashing
57
+ * backend screws up locks or shared memory. Likewise, the Postmaster
58
+ * should never block on messages from frontend clients.
59
+ *
60
+ * Garbage Collection:
61
+ * The Postmaster cleans up after backends if they have an emergency
62
+ * exit and/or core dump.
63
+ *
64
+ * Error Reporting:
65
+ * Use write_stderr() only for reporting "interactive" errors
66
+ * (essentially, bogus arguments on the command line). Once the
67
+ * postmaster is launched, use ereport().
68
+ *
69
+ *-------------------------------------------------------------------------
70
+ */
71
+
72
+ #include "postgres.h"
73
+
74
+ #include <unistd.h>
75
+ #include <signal.h>
76
+ #include <time.h>
77
+ #include <sys/wait.h>
78
+ #include <ctype.h>
79
+ #include <sys/stat.h>
80
+ #include <sys/socket.h>
81
+ #include <fcntl.h>
82
+ #include <sys/param.h>
83
+ #include <netdb.h>
84
+ #include <limits.h>
85
+
86
+ #ifdef HAVE_SYS_SELECT_H
87
+ #include <sys/select.h>
88
+ #endif
89
+
90
+ #ifdef USE_BONJOUR
91
+ #include <dns_sd.h>
92
+ #endif
93
+
94
+ #ifdef USE_SYSTEMD
95
+ #include <systemd/sd-daemon.h>
96
+ #endif
97
+
98
+ #ifdef HAVE_PTHREAD_IS_THREADED_NP
99
+ #include <pthread.h>
100
+ #endif
101
+
102
+ #include "access/transam.h"
103
+ #include "access/xlog.h"
104
+ #include "bootstrap/bootstrap.h"
105
+ #include "catalog/pg_control.h"
106
+ #include "common/file_perm.h"
107
+ #include "common/ip.h"
108
+ #include "common/string.h"
109
+ #include "lib/ilist.h"
110
+ #include "libpq/auth.h"
111
+ #include "libpq/libpq.h"
112
+ #include "libpq/pqformat.h"
113
+ #include "libpq/pqsignal.h"
114
+ #include "miscadmin.h"
115
+ #include "pg_getopt.h"
116
+ #include "pgstat.h"
117
+ #include "port/pg_bswap.h"
118
+ #include "postmaster/autovacuum.h"
119
+ #include "postmaster/bgworker_internals.h"
120
+ #include "postmaster/fork_process.h"
121
+ #include "postmaster/interrupt.h"
122
+ #include "postmaster/pgarch.h"
123
+ #include "postmaster/postmaster.h"
124
+ #include "postmaster/syslogger.h"
125
+ #include "replication/logicallauncher.h"
126
+ #include "replication/walsender.h"
127
+ #include "storage/fd.h"
128
+ #include "storage/ipc.h"
129
+ #include "storage/pg_shmem.h"
130
+ #include "storage/pmsignal.h"
131
+ #include "storage/proc.h"
132
+ #include "tcop/tcopprot.h"
133
+ #include "utils/builtins.h"
134
+ #include "utils/datetime.h"
135
+ #include "utils/memutils.h"
136
+ #include "utils/pidfile.h"
137
+ #include "utils/ps_status.h"
138
+ #include "utils/timeout.h"
139
+ #include "utils/timestamp.h"
140
+ #include "utils/varlena.h"
141
+
142
+ #ifdef EXEC_BACKEND
143
+ #include "storage/spin.h"
144
+ #endif
145
+
146
+
147
+ /*
148
+ * Possible types of a backend. Beyond being the possible bkend_type values in
149
+ * struct bkend, these are OR-able request flag bits for SignalSomeChildren()
150
+ * and CountChildren().
151
+ */
152
+ #define BACKEND_TYPE_NORMAL 0x0001 /* normal backend */
153
+ #define BACKEND_TYPE_AUTOVAC 0x0002 /* autovacuum worker process */
154
+ #define BACKEND_TYPE_WALSND 0x0004 /* walsender process */
155
+ #define BACKEND_TYPE_BGWORKER 0x0008 /* bgworker process */
156
+ #define BACKEND_TYPE_ALL 0x000F /* OR of all the above */
157
+
158
+ /*
159
+ * List of active backends (or child processes anyway; we don't actually
160
+ * know whether a given child has become a backend or is still in the
161
+ * authorization phase). This is used mainly to keep track of how many
162
+ * children we have and send them appropriate signals when necessary.
163
+ *
164
+ * "Special" children such as the startup, bgwriter and autovacuum launcher
165
+ * tasks are not in this list. Autovacuum worker and walsender are in it.
166
+ * Also, "dead_end" children are in it: these are children launched just for
167
+ * the purpose of sending a friendly rejection message to a would-be client.
168
+ * We must track them because they are attached to shared memory, but we know
169
+ * they will never become live backends. dead_end children are not assigned a
170
+ * PMChildSlot.
171
+ *
172
+ * Background workers are in this list, too.
173
+ */
174
+ typedef struct bkend
175
+ {
176
+ pid_t pid; /* process id of backend */
177
+ int32 cancel_key; /* cancel key for cancels for this backend */
178
+ int child_slot; /* PMChildSlot for this backend, if any */
179
+
180
+ /*
181
+ * Flavor of backend or auxiliary process. Note that BACKEND_TYPE_WALSND
182
+ * backends initially announce themselves as BACKEND_TYPE_NORMAL, so if
183
+ * bkend_type is normal, you should check for a recent transition.
184
+ */
185
+ int bkend_type;
186
+ bool dead_end; /* is it going to send an error and quit? */
187
+ bool bgworker_notify; /* gets bgworker start/stop notifications */
188
+ dlist_node elem; /* list link in BackendList */
189
+ } Backend;
190
+
191
+
192
+
193
+ #ifdef EXEC_BACKEND
194
+ static Backend *ShmemBackendArray;
195
+ #endif
196
+
197
+
198
+
199
+
200
+
201
+ /* The socket number we are listening for connections on */
202
+
203
+
204
+ /* The directory names for Unix socket(s) */
205
+
206
+
207
+ /* The TCP listen address(es) */
208
+
209
+
210
+ /*
211
+ * ReservedBackends is the number of backends reserved for superuser use.
212
+ * This number is taken out of the pool size given by MaxConnections so
213
+ * number of backend slots available to non-superusers is
214
+ * (MaxConnections - ReservedBackends). Note what this really means is
215
+ * "if there are <= ReservedBackends connections available, only superusers
216
+ * can make new connections" --- pre-existing superuser connections don't
217
+ * count against the limit.
218
+ */
219
+
220
+
221
+ /* The socket(s) we're listening to. */
222
+ #define MAXLISTEN 64
223
+
224
+
225
+ /*
226
+ * Set by the -o option
227
+ */
228
+
229
+
230
+ /*
231
+ * These globals control the behavior of the postmaster in case some
232
+ * backend dumps core. Normally, it kills all peers of the dead backend
233
+ * and reinitializes shared memory. By specifying -s or -n, we can have
234
+ * the postmaster stop (rather than kill) peers and not reinitialize
235
+ * shared data structures. (Reinit is currently dead code, though.)
236
+ */
237
+
238
+
239
+
240
+ /* still more option variables */
241
+
242
+
243
+
244
+
245
+
246
+ /* for ps display and logging */
247
+
248
+
249
+
250
+
251
+
252
+
253
+
254
+ /* PIDs of special child processes; 0 when not running */
255
+
256
+
257
+
258
+
259
+
260
+
261
+
262
+
263
+
264
+
265
+ /* Startup process's status */
266
+ typedef enum
267
+ {
268
+ STARTUP_NOT_RUNNING,
269
+ STARTUP_RUNNING,
270
+ STARTUP_SIGNALED, /* we sent it a SIGQUIT or SIGKILL */
271
+ STARTUP_CRASHED
272
+ } StartupStatusEnum;
273
+
274
+
275
+
276
+ /* Startup/shutdown state */
277
+ #define NoShutdown 0
278
+ #define SmartShutdown 1
279
+ #define FastShutdown 2
280
+ #define ImmediateShutdown 3
281
+
282
+
283
+
284
+ /* T if recovering from backend crash */
285
+
286
+ /*
287
+ * We use a simple state machine to control startup, shutdown, and
288
+ * crash recovery (which is rather like shutdown followed by startup).
289
+ *
290
+ * After doing all the postmaster initialization work, we enter PM_STARTUP
291
+ * state and the startup process is launched. The startup process begins by
292
+ * reading the control file and other preliminary initialization steps.
293
+ * In a normal startup, or after crash recovery, the startup process exits
294
+ * with exit code 0 and we switch to PM_RUN state. However, archive recovery
295
+ * is handled specially since it takes much longer and we would like to support
296
+ * hot standby during archive recovery.
297
+ *
298
+ * When the startup process is ready to start archive recovery, it signals the
299
+ * postmaster, and we switch to PM_RECOVERY state. The background writer and
300
+ * checkpointer are launched, while the startup process continues applying WAL.
301
+ * If Hot Standby is enabled, then, after reaching a consistent point in WAL
302
+ * redo, startup process signals us again, and we switch to PM_HOT_STANDBY
303
+ * state and begin accepting connections to perform read-only queries. When
304
+ * archive recovery is finished, the startup process exits with exit code 0
305
+ * and we switch to PM_RUN state.
306
+ *
307
+ * Normal child backends can only be launched when we are in PM_RUN or
308
+ * PM_HOT_STANDBY state. (connsAllowed can also restrict launching.)
309
+ * In other states we handle connection requests by launching "dead_end"
310
+ * child processes, which will simply send the client an error message and
311
+ * quit. (We track these in the BackendList so that we can know when they
312
+ * are all gone; this is important because they're still connected to shared
313
+ * memory, and would interfere with an attempt to destroy the shmem segment,
314
+ * possibly leading to SHMALL failure when we try to make a new one.)
315
+ * In PM_WAIT_DEAD_END state we are waiting for all the dead_end children
316
+ * to drain out of the system, and therefore stop accepting connection
317
+ * requests at all until the last existing child has quit (which hopefully
318
+ * will not be very long).
319
+ *
320
+ * Notice that this state variable does not distinguish *why* we entered
321
+ * states later than PM_RUN --- Shutdown and FatalError must be consulted
322
+ * to find that out. FatalError is never true in PM_RECOVERY, PM_HOT_STANDBY,
323
+ * or PM_RUN states, nor in PM_SHUTDOWN states (because we don't enter those
324
+ * states when trying to recover from a crash). It can be true in PM_STARTUP
325
+ * state, because we don't clear it until we've successfully started WAL redo.
326
+ */
327
+ typedef enum
328
+ {
329
+ PM_INIT, /* postmaster starting */
330
+ PM_STARTUP, /* waiting for startup subprocess */
331
+ PM_RECOVERY, /* in archive recovery mode */
332
+ PM_HOT_STANDBY, /* in hot standby mode */
333
+ PM_RUN, /* normal "database is alive" state */
334
+ PM_STOP_BACKENDS, /* need to stop remaining backends */
335
+ PM_WAIT_BACKENDS, /* waiting for live backends to exit */
336
+ PM_SHUTDOWN, /* waiting for checkpointer to do shutdown
337
+ * ckpt */
338
+ PM_SHUTDOWN_2, /* waiting for archiver and walsenders to
339
+ * finish */
340
+ PM_WAIT_DEAD_END, /* waiting for dead_end children to exit */
341
+ PM_NO_CHILDREN /* all important children have exited */
342
+ } PMState;
343
+
344
+
345
+
346
+ /*
347
+ * While performing a "smart shutdown", we restrict new connections but stay
348
+ * in PM_RUN or PM_HOT_STANDBY state until all the client backends are gone.
349
+ * connsAllowed is a sub-state indicator showing the active restriction.
350
+ * It is of no interest unless pmState is PM_RUN or PM_HOT_STANDBY.
351
+ */
352
+ typedef enum
353
+ {
354
+ ALLOW_ALL_CONNS, /* normal not-shutting-down state */
355
+ ALLOW_SUPERUSER_CONNS, /* only superusers can connect */
356
+ ALLOW_NO_CONNS /* no new connections allowed, period */
357
+ } ConnsAllowedState;
358
+
359
+
360
+
361
+ /* Start time of SIGKILL timeout during immediate shutdown or child crash */
362
+ /* Zero means timeout is not running */
363
+
364
+
365
+ /* Length of said timeout */
366
+ #define SIGKILL_CHILDREN_AFTER_SECS 5
367
+
368
+ /* T if we've reached PM_RUN */
369
+
370
+ __thread bool ClientAuthInProgress = false;
371
+ /* T during new-client
372
+ * authentication */
373
+
374
+ /* stderr redirected for syslogger? */
375
+
376
+ /* received START_AUTOVAC_LAUNCHER signal */
377
+
378
+
379
+ /* the launcher needs to be signaled to communicate some condition */
380
+
381
+
382
+ /* received START_WALRECEIVER signal */
383
+
384
+
385
+ /* set when there's a worker that needs to be started up */
386
+
387
+
388
+
389
+ #ifdef USE_SSL
390
+ /* Set when and if SSL has been initialized properly */
391
+ static bool LoadedSSL = false;
392
+ #endif
393
+
394
+ #ifdef USE_BONJOUR
395
+ static DNSServiceRef bonjour_sdref = NULL;
396
+ #endif
397
+
398
+ /*
399
+ * postmaster.c - function prototypes
400
+ */
401
+ static void CloseServerPorts(int status, Datum arg);
402
+ static void unlink_external_pid_file(int status, Datum arg);
403
+ static void getInstallationPaths(const char *argv0);
404
+ static void checkControlFile(void);
405
+ static Port *ConnCreate(int serverFd);
406
+ static void ConnFree(Port *port);
407
+ static void reset_shared(void);
408
+ static void SIGHUP_handler(SIGNAL_ARGS);
409
+ static void pmdie(SIGNAL_ARGS);
410
+ static void reaper(SIGNAL_ARGS);
411
+ static void sigusr1_handler(SIGNAL_ARGS);
412
+ static void process_startup_packet_die(SIGNAL_ARGS);
413
+ static void dummy_handler(SIGNAL_ARGS);
414
+ static void StartupPacketTimeoutHandler(void);
415
+ static void CleanupBackend(int pid, int exitstatus);
416
+ static bool CleanupBackgroundWorker(int pid, int exitstatus);
417
+ static void HandleChildCrash(int pid, int exitstatus, const char *procname);
418
+ static void LogChildExit(int lev, const char *procname,
419
+ int pid, int exitstatus);
420
+ static void PostmasterStateMachine(void);
421
+ static void BackendInitialize(Port *port);
422
+ static void BackendRun(Port *port) pg_attribute_noreturn();
423
+ static void ExitPostmaster(int status) pg_attribute_noreturn();
424
+ static int ServerLoop(void);
425
+ static int BackendStartup(Port *port);
426
+ static int ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done);
427
+ static void SendNegotiateProtocolVersion(List *unrecognized_protocol_options);
428
+ static void processCancelRequest(Port *port, void *pkt);
429
+ static int initMasks(fd_set *rmask);
430
+ static void report_fork_failure_to_client(Port *port, int errnum);
431
+ static CAC_state canAcceptConnections(int backend_type);
432
+ static bool RandomCancelKey(int32 *cancel_key);
433
+ static void signal_child(pid_t pid, int signal);
434
+ static bool SignalSomeChildren(int signal, int targets);
435
+ static void TerminateChildren(int signal);
436
+
437
+ #define SignalChildren(sig) SignalSomeChildren(sig, BACKEND_TYPE_ALL)
438
+
439
+ static int CountChildren(int target);
440
+ static bool assign_backendlist_entry(RegisteredBgWorker *rw);
441
+ static void maybe_start_bgworkers(void);
442
+ static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
443
+ static pid_t StartChildProcess(AuxProcType type);
444
+ static void StartAutovacuumWorker(void);
445
+ static void MaybeStartWalReceiver(void);
446
+ static void InitPostmasterDeathWatchHandle(void);
447
+
448
+ /*
449
+ * Archiver is allowed to start up at the current postmaster state?
450
+ *
451
+ * If WAL archiving is enabled always, we are allowed to start archiver
452
+ * even during recovery.
453
+ */
454
+ #define PgArchStartupAllowed() \
455
+ ((XLogArchivingActive() && pmState == PM_RUN) || \
456
+ (XLogArchivingAlways() && \
457
+ (pmState == PM_RECOVERY || pmState == PM_HOT_STANDBY)))
458
+
459
+ #ifdef EXEC_BACKEND
460
+
461
+ #ifdef WIN32
462
+ #define WNOHANG 0 /* ignored, so any integer value will do */
463
+
464
+ static pid_t waitpid(pid_t pid, int *exitstatus, int options);
465
+ static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
466
+
467
+ static HANDLE win32ChildQueue;
468
+
469
+ typedef struct
470
+ {
471
+ HANDLE waitHandle;
472
+ HANDLE procHandle;
473
+ DWORD procId;
474
+ } win32_deadchild_waitinfo;
475
+ #endif /* WIN32 */
476
+
477
+ static pid_t backend_forkexec(Port *port);
478
+ static pid_t internal_forkexec(int argc, char *argv[], Port *port);
479
+
480
+ /* Type for a socket that can be inherited to a client process */
481
+ #ifdef WIN32
482
+ typedef struct
483
+ {
484
+ SOCKET origsocket; /* Original socket value, or PGINVALID_SOCKET
485
+ * if not a socket */
486
+ WSAPROTOCOL_INFO wsainfo;
487
+ } InheritableSocket;
488
+ #else
489
+ typedef int InheritableSocket;
490
+ #endif
491
+
492
+ /*
493
+ * Structure contains all variables passed to exec:ed backends
494
+ */
495
+ typedef struct
496
+ {
497
+ Port port;
498
+ InheritableSocket portsocket;
499
+ char DataDir[MAXPGPATH];
500
+ pgsocket ListenSocket[MAXLISTEN];
501
+ int32 MyCancelKey;
502
+ int MyPMChildSlot;
503
+ #ifndef WIN32
504
+ unsigned long UsedShmemSegID;
505
+ #else
506
+ void *ShmemProtectiveRegion;
507
+ HANDLE UsedShmemSegID;
508
+ #endif
509
+ void *UsedShmemSegAddr;
510
+ slock_t *ShmemLock;
511
+ VariableCache ShmemVariableCache;
512
+ Backend *ShmemBackendArray;
513
+ #ifndef HAVE_SPINLOCKS
514
+ PGSemaphore *SpinlockSemaArray;
515
+ #endif
516
+ int NamedLWLockTrancheRequests;
517
+ NamedLWLockTranche *NamedLWLockTrancheArray;
518
+ LWLockPadded *MainLWLockArray;
519
+ slock_t *ProcStructLock;
520
+ PROC_HDR *ProcGlobal;
521
+ PGPROC *AuxiliaryProcs;
522
+ PGPROC *PreparedXactProcs;
523
+ PMSignalData *PMSignalState;
524
+ InheritableSocket pgStatSock;
525
+ pid_t PostmasterPid;
526
+ TimestampTz PgStartTime;
527
+ TimestampTz PgReloadTime;
528
+ pg_time_t first_syslogger_file_time;
529
+ bool redirection_done;
530
+ bool IsBinaryUpgrade;
531
+ int max_safe_fds;
532
+ int MaxBackends;
533
+ #ifdef WIN32
534
+ HANDLE PostmasterHandle;
535
+ HANDLE initial_signal_pipe;
536
+ HANDLE syslogPipe[2];
537
+ #else
538
+ int postmaster_alive_fds[2];
539
+ int syslogPipe[2];
540
+ #endif
541
+ char my_exec_path[MAXPGPATH];
542
+ char pkglib_path[MAXPGPATH];
543
+ char ExtraOptions[MAXPGPATH];
544
+ } BackendParameters;
545
+
546
+ static void read_backend_variables(char *id, Port *port);
547
+ static void restore_backend_variables(BackendParameters *param, Port *port);
548
+
549
+ #ifndef WIN32
550
+ static bool save_backend_variables(BackendParameters *param, Port *port);
551
+ #else
552
+ static bool save_backend_variables(BackendParameters *param, Port *port,
553
+ HANDLE childProcess, pid_t childPid);
554
+ #endif
555
+
556
+ static void ShmemBackendArrayAdd(Backend *bn);
557
+ static void ShmemBackendArrayRemove(Backend *bn);
558
+ #endif /* EXEC_BACKEND */
559
+
560
+ #define StartupDataBase() StartChildProcess(StartupProcess)
561
+ #define StartBackgroundWriter() StartChildProcess(BgWriterProcess)
562
+ #define StartCheckpointer() StartChildProcess(CheckpointerProcess)
563
+ #define StartWalWriter() StartChildProcess(WalWriterProcess)
564
+ #define StartWalReceiver() StartChildProcess(WalReceiverProcess)
565
+
566
+ /* Macros to check exit status of a child process */
567
+ #define EXIT_STATUS_0(st) ((st) == 0)
568
+ #define EXIT_STATUS_1(st) (WIFEXITED(st) && WEXITSTATUS(st) == 1)
569
+ #define EXIT_STATUS_3(st) (WIFEXITED(st) && WEXITSTATUS(st) == 3)
570
+
571
+ #ifndef WIN32
572
+ /*
573
+ * File descriptors for pipe used to monitor if postmaster is alive.
574
+ * First is POSTMASTER_FD_WATCH, second is POSTMASTER_FD_OWN.
575
+ */
576
+
577
+ #else
578
+ /* Process handle of postmaster used for the same purpose on Windows */
579
+ HANDLE PostmasterHandle;
580
+ #endif
581
+
582
+ /*
583
+ * Postmaster main entry point
584
+ */
585
+ #ifdef SIGTTIN
586
+ #endif
587
+ #ifdef SIGTTOU
588
+ #endif
589
+ #ifdef SIGXFSZ
590
+ #endif
591
+ #ifdef HAVE_INT_OPTRESET
592
+ #endif
593
+ #ifdef USE_SSL
594
+ #endif
595
+ #ifdef WIN32
596
+ #endif
597
+ #ifdef EXEC_BACKEND
598
+ #endif
599
+ #ifdef USE_BONJOUR
600
+ #endif
601
+ #ifdef HAVE_UNIX_SOCKETS
602
+ #endif
603
+ #ifdef HAVE_PTHREAD_IS_THREADED_NP
604
+ #endif
605
+
606
+
607
+ /*
608
+ * on_proc_exit callback to close server's listen sockets
609
+ */
610
+
611
+
612
+ /*
613
+ * on_proc_exit callback to delete external_pid_file
614
+ */
615
+
616
+
617
+
618
+ /*
619
+ * Compute and check the directory paths to files that are part of the
620
+ * installation (as deduced from the postgres executable's own location)
621
+ */
622
+ #ifdef EXEC_BACKEND
623
+ #endif
624
+
625
+ /*
626
+ * Check that pg_control exists in the correct location in the data directory.
627
+ *
628
+ * No attempt is made to validate the contents of pg_control here. This is
629
+ * just a sanity check to see if we are looking at a real data directory.
630
+ */
631
+
632
+
633
+ /*
634
+ * Determine how long should we let ServerLoop sleep.
635
+ *
636
+ * In normal conditions we wait at most one minute, to ensure that the other
637
+ * background tasks handled by ServerLoop get done even when no requests are
638
+ * arriving. However, if there are background workers waiting to be started,
639
+ * we don't actually sleep so that they are quickly serviced. Other exception
640
+ * cases are as shown in the code.
641
+ */
642
+
643
+
644
+ /*
645
+ * Main idle loop of postmaster
646
+ *
647
+ * NB: Needs to be called with signals blocked
648
+ */
649
+ #ifdef HAVE_PTHREAD_IS_THREADED_NP
650
+ #endif
651
+
652
+ /*
653
+ * Initialise the masks for select() for the ports we are listening on.
654
+ * Return the number of sockets to listen on.
655
+ */
656
+
657
+
658
+
659
+ /*
660
+ * Read a client's startup packet and do something according to it.
661
+ *
662
+ * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
663
+ * not return at all.
664
+ *
665
+ * (Note that ereport(FATAL) stuff is sent to the client, so only use it
666
+ * if that's what you want. Return STATUS_ERROR if you don't want to
667
+ * send anything to the client, which would typically be appropriate
668
+ * if we detect a communications failure.)
669
+ *
670
+ * Set ssl_done and/or gss_done when negotiation of an encrypted layer
671
+ * (currently, TLS or GSSAPI) is completed. A successful negotiation of either
672
+ * encryption layer sets both flags, but a rejected negotiation sets only the
673
+ * flag for that layer, since the client may wish to try the other one. We
674
+ * should make no assumption here about the order in which the client may make
675
+ * requests.
676
+ */
677
+ #ifdef USE_SSL
678
+ #else
679
+ #endif
680
+ #ifdef USE_SSL
681
+ #endif
682
+ #ifdef ENABLE_GSS
683
+ #endif
684
+ #ifdef ENABLE_GSS
685
+ #endif
686
+
687
+ /*
688
+ * Send a NegotiateProtocolVersion to the client. This lets the client know
689
+ * that they have requested a newer minor protocol version than we are able
690
+ * to speak. We'll speak the highest version we know about; the client can,
691
+ * of course, abandon the connection if that's a problem.
692
+ *
693
+ * We also include in the response a list of protocol options we didn't
694
+ * understand. This allows clients to include optional parameters that might
695
+ * be present either in newer protocol versions or third-party protocol
696
+ * extensions without fear of having to reconnect if those options are not
697
+ * understood, while at the same time making certain that the client is aware
698
+ * of which options were actually accepted.
699
+ */
700
+
701
+
702
+ /*
703
+ * The client has sent a cancel request packet, not a normal
704
+ * start-a-new-connection packet. Perform the necessary processing.
705
+ * Nothing is sent back to the client.
706
+ */
707
+ #ifndef EXEC_BACKEND
708
+ #else
709
+ #endif
710
+ #ifndef EXEC_BACKEND
711
+ #else
712
+ #endif
713
+ #ifndef EXEC_BACKEND /* make GNU Emacs 26.1 see brace balance */
714
+ #else
715
+ #endif
716
+
717
+ /*
718
+ * canAcceptConnections --- check to see if database state allows connections
719
+ * of the specified type. backend_type can be BACKEND_TYPE_NORMAL,
720
+ * BACKEND_TYPE_AUTOVAC, or BACKEND_TYPE_BGWORKER. (Note that we don't yet
721
+ * know whether a NORMAL connection might turn into a walsender.)
722
+ */
723
+
724
+
725
+
726
+ /*
727
+ * ConnCreate -- create a local connection data structure
728
+ *
729
+ * Returns NULL on failure, other than out-of-memory which is fatal.
730
+ */
731
+
732
+
733
+
734
+ /*
735
+ * ConnFree -- free a local connection data structure
736
+ *
737
+ * Caller has already closed the socket if any, so there's not much
738
+ * to do here.
739
+ */
740
+
741
+
742
+
743
+ /*
744
+ * ClosePostmasterPorts -- close all the postmaster's open sockets
745
+ *
746
+ * This is called during child process startup to release file descriptors
747
+ * that are not needed by that child process. The postmaster still has
748
+ * them open, of course.
749
+ *
750
+ * Note: we pass am_syslogger as a boolean because we don't want to set
751
+ * the global variable yet when this is called.
752
+ */
753
+ #ifndef WIN32
754
+ #endif
755
+ #ifndef WIN32
756
+ #else
757
+ #endif
758
+ #ifdef USE_BONJOUR
759
+ #endif
760
+
761
+
762
+ /*
763
+ * InitProcessGlobals -- set MyProcPid, MyStartTime[stamp], random seeds
764
+ *
765
+ * Called early in the postmaster and every backend.
766
+ */
767
+
768
+
769
+
770
+ /*
771
+ * reset_shared -- reset shared memory and semaphores
772
+ */
773
+
774
+
775
+
776
+ /*
777
+ * SIGHUP -- reread config files, and tell children to do same
778
+ */
779
+ #ifdef WIN32
780
+ #endif
781
+ #ifdef USE_SSL
782
+ #endif
783
+ #ifdef EXEC_BACKEND
784
+ #endif
785
+ #ifdef WIN32
786
+ #endif
787
+
788
+
789
+ /*
790
+ * pmdie -- signal handler for processing various postmaster signals.
791
+ */
792
+ #ifdef WIN32
793
+ #endif
794
+ #ifdef USE_SYSTEMD
795
+ #endif
796
+ #ifdef USE_SYSTEMD
797
+ #endif
798
+ #ifdef USE_SYSTEMD
799
+ #endif
800
+ #ifdef WIN32
801
+ #endif
802
+
803
+ /*
804
+ * Reaper -- signal handler to cleanup after a child process dies.
805
+ */
806
+ #ifdef WIN32
807
+ #endif
808
+ #ifdef USE_SYSTEMD
809
+ #endif
810
+ #ifdef WIN32
811
+ #endif
812
+
813
+ /*
814
+ * Scan the bgworkers list and see if the given PID (which has just stopped
815
+ * or crashed) is in it. Handle its shutdown if so, and return true. If not a
816
+ * bgworker, return false.
817
+ *
818
+ * This is heavily based on CleanupBackend. One important difference is that
819
+ * we don't know yet that the dying process is a bgworker, so we must be silent
820
+ * until we're sure it is.
821
+ */
822
+ #ifdef WIN32
823
+ #endif
824
+ #ifdef EXEC_BACKEND
825
+ #endif
826
+
827
+ /*
828
+ * CleanupBackend -- cleanup after terminated backend.
829
+ *
830
+ * Remove all local state associated with backend.
831
+ *
832
+ * If you change this, see also CleanupBackgroundWorker.
833
+ */
834
+ #ifdef WIN32
835
+ #endif
836
+ #ifdef EXEC_BACKEND
837
+ #endif
838
+
839
+ /*
840
+ * HandleChildCrash -- cleanup after failed backend, bgwriter, checkpointer,
841
+ * walwriter, autovacuum, or background worker.
842
+ *
843
+ * The objectives here are to clean up our local state about the child
844
+ * process, and to signal all other remaining children to quickdie.
845
+ */
846
+ #ifdef EXEC_BACKEND
847
+ #endif
848
+ #ifdef EXEC_BACKEND
849
+ #endif
850
+
851
+ /*
852
+ * Log the death of a child process.
853
+ */
854
+ #if defined(WIN32)
855
+ #else
856
+ #endif
857
+
858
+ /*
859
+ * Advance the postmaster's state machine and take actions as appropriate
860
+ *
861
+ * This is common code for pmdie(), reaper() and sigusr1_handler(), which
862
+ * receive the signals that might mean we need to change state.
863
+ */
864
+
865
+
866
+
867
+ /*
868
+ * Send a signal to a postmaster child process
869
+ *
870
+ * On systems that have setsid(), each child process sets itself up as a
871
+ * process group leader. For signals that are generally interpreted in the
872
+ * appropriate fashion, we signal the entire process group not just the
873
+ * direct child process. This allows us to, for example, SIGQUIT a blocked
874
+ * archive_recovery script, or SIGINT a script being run by a backend via
875
+ * system().
876
+ *
877
+ * There is a race condition for recently-forked children: they might not
878
+ * have executed setsid() yet. So we signal the child directly as well as
879
+ * the group. We assume such a child will handle the signal before trying
880
+ * to spawn any grandchild processes. We also assume that signaling the
881
+ * child twice will not cause any problems.
882
+ */
883
+ #ifdef HAVE_SETSID
884
+ #endif
885
+
886
+ /*
887
+ * Send a signal to the targeted children (but NOT special children;
888
+ * dead_end children are never signaled, either).
889
+ */
890
+
891
+
892
+ /*
893
+ * Send a termination signal to children. This considers all of our children
894
+ * processes, except syslogger and dead_end backends.
895
+ */
896
+
897
+
898
+ /*
899
+ * BackendStartup -- start backend process
900
+ *
901
+ * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
902
+ *
903
+ * Note: if you change this code, also consider StartAutovacuumWorker.
904
+ */
905
+ #ifdef EXEC_BACKEND
906
+ #else /* !EXEC_BACKEND */
907
+ #endif /* EXEC_BACKEND */
908
+ #ifdef EXEC_BACKEND
909
+ #endif
910
+
911
+ /*
912
+ * Try to report backend fork() failure to client before we close the
913
+ * connection. Since we do not care to risk blocking the postmaster on
914
+ * this connection, we set the connection to non-blocking and try only once.
915
+ *
916
+ * This is grungy special-purpose code; we cannot use backend libpq since
917
+ * it's not up and running.
918
+ */
919
+
920
+
921
+
922
+ /*
923
+ * BackendInitialize -- initialize an interactive (postmaster-child)
924
+ * backend process, and collect the client's startup packet.
925
+ *
926
+ * returns: nothing. Will not return at all if there's any failure.
927
+ *
928
+ * Note: this code does not depend on having any access to shared memory.
929
+ * In the EXEC_BACKEND case, we are physically attached to shared memory
930
+ * but have not yet set up most of our local pointers to shmem structures.
931
+ */
932
+
933
+
934
+
935
+ /*
936
+ * BackendRun -- set up the backend's argument list and invoke PostgresMain()
937
+ *
938
+ * returns:
939
+ * Shouldn't return at all.
940
+ * If PostgresMain() fails, return status.
941
+ */
942
+
943
+
944
+
945
+ #ifdef EXEC_BACKEND
946
+
947
+ /*
948
+ * postmaster_forkexec -- fork and exec a postmaster subprocess
949
+ *
950
+ * The caller must have set up the argv array already, except for argv[2]
951
+ * which will be filled with the name of the temp variable file.
952
+ *
953
+ * Returns the child process PID, or -1 on fork failure (a suitable error
954
+ * message has been logged on failure).
955
+ *
956
+ * All uses of this routine will dispatch to SubPostmasterMain in the
957
+ * child process.
958
+ */
959
+ pid_t
960
+ postmaster_forkexec(int argc, char *argv[])
961
+ {
962
+ Port port;
963
+
964
+ /* This entry point passes dummy values for the Port variables */
965
+ memset(&port, 0, sizeof(port));
966
+ return internal_forkexec(argc, argv, &port);
967
+ }
968
+
969
+ /*
970
+ * backend_forkexec -- fork/exec off a backend process
971
+ *
972
+ * Some operating systems (WIN32) don't have fork() so we have to simulate
973
+ * it by storing parameters that need to be passed to the child and
974
+ * then create a new child process.
975
+ *
976
+ * returns the pid of the fork/exec'd process, or -1 on failure
977
+ */
978
+ static pid_t
979
+ backend_forkexec(Port *port)
980
+ {
981
+ char *av[4];
982
+ int ac = 0;
983
+
984
+ av[ac++] = "postgres";
985
+ av[ac++] = "--forkbackend";
986
+ av[ac++] = NULL; /* filled in by internal_forkexec */
987
+
988
+ av[ac] = NULL;
989
+ Assert(ac < lengthof(av));
990
+
991
+ return internal_forkexec(ac, av, port);
992
+ }
993
+
994
+ #ifndef WIN32
995
+
996
+ /*
997
+ * internal_forkexec non-win32 implementation
998
+ *
999
+ * - writes out backend variables to the parameter file
1000
+ * - fork():s, and then exec():s the child process
1001
+ */
1002
+ static pid_t
1003
+ internal_forkexec(int argc, char *argv[], Port *port)
1004
+ {
1005
+ static unsigned long tmpBackendFileNum = 0;
1006
+ pid_t pid;
1007
+ char tmpfilename[MAXPGPATH];
1008
+ BackendParameters param;
1009
+ FILE *fp;
1010
+
1011
+ if (!save_backend_variables(&param, port))
1012
+ return -1; /* log made by save_backend_variables */
1013
+
1014
+ /* Calculate name for temp file */
1015
+ snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu",
1016
+ PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
1017
+ MyProcPid, ++tmpBackendFileNum);
1018
+
1019
+ /* Open file */
1020
+ fp = AllocateFile(tmpfilename, PG_BINARY_W);
1021
+ if (!fp)
1022
+ {
1023
+ /*
1024
+ * As in OpenTemporaryFileInTablespace, try to make the temp-file
1025
+ * directory, ignoring errors.
1026
+ */
1027
+ (void) MakePGDirectory(PG_TEMP_FILES_DIR);
1028
+
1029
+ fp = AllocateFile(tmpfilename, PG_BINARY_W);
1030
+ if (!fp)
1031
+ {
1032
+ ereport(LOG,
1033
+ (errcode_for_file_access(),
1034
+ errmsg("could not create file \"%s\": %m",
1035
+ tmpfilename)));
1036
+ return -1;
1037
+ }
1038
+ }
1039
+
1040
+ if (fwrite(&param, sizeof(param), 1, fp) != 1)
1041
+ {
1042
+ ereport(LOG,
1043
+ (errcode_for_file_access(),
1044
+ errmsg("could not write to file \"%s\": %m", tmpfilename)));
1045
+ FreeFile(fp);
1046
+ return -1;
1047
+ }
1048
+
1049
+ /* Release file */
1050
+ if (FreeFile(fp))
1051
+ {
1052
+ ereport(LOG,
1053
+ (errcode_for_file_access(),
1054
+ errmsg("could not write to file \"%s\": %m", tmpfilename)));
1055
+ return -1;
1056
+ }
1057
+
1058
+ /* Make sure caller set up argv properly */
1059
+ Assert(argc >= 3);
1060
+ Assert(argv[argc] == NULL);
1061
+ Assert(strncmp(argv[1], "--fork", 6) == 0);
1062
+ Assert(argv[2] == NULL);
1063
+
1064
+ /* Insert temp file name after --fork argument */
1065
+ argv[2] = tmpfilename;
1066
+
1067
+ /* Fire off execv in child */
1068
+ if ((pid = fork_process()) == 0)
1069
+ {
1070
+ if (execv(postgres_exec_path, argv) < 0)
1071
+ {
1072
+ ereport(LOG,
1073
+ (errmsg("could not execute server process \"%s\": %m",
1074
+ postgres_exec_path)));
1075
+ /* We're already in the child process here, can't return */
1076
+ exit(1);
1077
+ }
1078
+ }
1079
+
1080
+ return pid; /* Parent returns pid, or -1 on fork failure */
1081
+ }
1082
+ #else /* WIN32 */
1083
+
1084
+ /*
1085
+ * internal_forkexec win32 implementation
1086
+ *
1087
+ * - starts backend using CreateProcess(), in suspended state
1088
+ * - writes out backend variables to the parameter file
1089
+ * - during this, duplicates handles and sockets required for
1090
+ * inheritance into the new process
1091
+ * - resumes execution of the new process once the backend parameter
1092
+ * file is complete.
1093
+ */
1094
+ static pid_t
1095
+ internal_forkexec(int argc, char *argv[], Port *port)
1096
+ {
1097
+ int retry_count = 0;
1098
+ STARTUPINFO si;
1099
+ PROCESS_INFORMATION pi;
1100
+ int i;
1101
+ int j;
1102
+ char cmdLine[MAXPGPATH * 2];
1103
+ HANDLE paramHandle;
1104
+ BackendParameters *param;
1105
+ SECURITY_ATTRIBUTES sa;
1106
+ char paramHandleStr[32];
1107
+ win32_deadchild_waitinfo *childinfo;
1108
+
1109
+ /* Make sure caller set up argv properly */
1110
+ Assert(argc >= 3);
1111
+ Assert(argv[argc] == NULL);
1112
+ Assert(strncmp(argv[1], "--fork", 6) == 0);
1113
+ Assert(argv[2] == NULL);
1114
+
1115
+ /* Resume here if we need to retry */
1116
+ retry:
1117
+
1118
+ /* Set up shared memory for parameter passing */
1119
+ ZeroMemory(&sa, sizeof(sa));
1120
+ sa.nLength = sizeof(sa);
1121
+ sa.bInheritHandle = TRUE;
1122
+ paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE,
1123
+ &sa,
1124
+ PAGE_READWRITE,
1125
+ 0,
1126
+ sizeof(BackendParameters),
1127
+ NULL);
1128
+ if (paramHandle == INVALID_HANDLE_VALUE)
1129
+ {
1130
+ elog(LOG, "could not create backend parameter file mapping: error code %lu",
1131
+ GetLastError());
1132
+ return -1;
1133
+ }
1134
+
1135
+ param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters));
1136
+ if (!param)
1137
+ {
1138
+ elog(LOG, "could not map backend parameter memory: error code %lu",
1139
+ GetLastError());
1140
+ CloseHandle(paramHandle);
1141
+ return -1;
1142
+ }
1143
+
1144
+ /* Insert temp file name after --fork argument */
1145
+ #ifdef _WIN64
1146
+ sprintf(paramHandleStr, "%llu", (LONG_PTR) paramHandle);
1147
+ #else
1148
+ sprintf(paramHandleStr, "%lu", (DWORD) paramHandle);
1149
+ #endif
1150
+ argv[2] = paramHandleStr;
1151
+
1152
+ /* Format the cmd line */
1153
+ cmdLine[sizeof(cmdLine) - 1] = '\0';
1154
+ cmdLine[sizeof(cmdLine) - 2] = '\0';
1155
+ snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path);
1156
+ i = 0;
1157
+ while (argv[++i] != NULL)
1158
+ {
1159
+ j = strlen(cmdLine);
1160
+ snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
1161
+ }
1162
+ if (cmdLine[sizeof(cmdLine) - 2] != '\0')
1163
+ {
1164
+ elog(LOG, "subprocess command line too long");
1165
+ UnmapViewOfFile(param);
1166
+ CloseHandle(paramHandle);
1167
+ return -1;
1168
+ }
1169
+
1170
+ memset(&pi, 0, sizeof(pi));
1171
+ memset(&si, 0, sizeof(si));
1172
+ si.cb = sizeof(si);
1173
+
1174
+ /*
1175
+ * Create the subprocess in a suspended state. This will be resumed later,
1176
+ * once we have written out the parameter file.
1177
+ */
1178
+ if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED,
1179
+ NULL, NULL, &si, &pi))
1180
+ {
1181
+ elog(LOG, "CreateProcess call failed: %m (error code %lu)",
1182
+ GetLastError());
1183
+ UnmapViewOfFile(param);
1184
+ CloseHandle(paramHandle);
1185
+ return -1;
1186
+ }
1187
+
1188
+ if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId))
1189
+ {
1190
+ /*
1191
+ * log made by save_backend_variables, but we have to clean up the
1192
+ * mess with the half-started process
1193
+ */
1194
+ if (!TerminateProcess(pi.hProcess, 255))
1195
+ ereport(LOG,
1196
+ (errmsg_internal("could not terminate unstarted process: error code %lu",
1197
+ GetLastError())));
1198
+ CloseHandle(pi.hProcess);
1199
+ CloseHandle(pi.hThread);
1200
+ UnmapViewOfFile(param);
1201
+ CloseHandle(paramHandle);
1202
+ return -1; /* log made by save_backend_variables */
1203
+ }
1204
+
1205
+ /* Drop the parameter shared memory that is now inherited to the backend */
1206
+ if (!UnmapViewOfFile(param))
1207
+ elog(LOG, "could not unmap view of backend parameter file: error code %lu",
1208
+ GetLastError());
1209
+ if (!CloseHandle(paramHandle))
1210
+ elog(LOG, "could not close handle to backend parameter file: error code %lu",
1211
+ GetLastError());
1212
+
1213
+ /*
1214
+ * Reserve the memory region used by our main shared memory segment before
1215
+ * we resume the child process. Normally this should succeed, but if ASLR
1216
+ * is active then it might sometimes fail due to the stack or heap having
1217
+ * gotten mapped into that range. In that case, just terminate the
1218
+ * process and retry.
1219
+ */
1220
+ if (!pgwin32_ReserveSharedMemoryRegion(pi.hProcess))
1221
+ {
1222
+ /* pgwin32_ReserveSharedMemoryRegion already made a log entry */
1223
+ if (!TerminateProcess(pi.hProcess, 255))
1224
+ ereport(LOG,
1225
+ (errmsg_internal("could not terminate process that failed to reserve memory: error code %lu",
1226
+ GetLastError())));
1227
+ CloseHandle(pi.hProcess);
1228
+ CloseHandle(pi.hThread);
1229
+ if (++retry_count < 100)
1230
+ goto retry;
1231
+ ereport(LOG,
1232
+ (errmsg("giving up after too many tries to reserve shared memory"),
1233
+ errhint("This might be caused by ASLR or antivirus software.")));
1234
+ return -1;
1235
+ }
1236
+
1237
+ /*
1238
+ * Now that the backend variables are written out, we start the child
1239
+ * thread so it can start initializing while we set up the rest of the
1240
+ * parent state.
1241
+ */
1242
+ if (ResumeThread(pi.hThread) == -1)
1243
+ {
1244
+ if (!TerminateProcess(pi.hProcess, 255))
1245
+ {
1246
+ ereport(LOG,
1247
+ (errmsg_internal("could not terminate unstartable process: error code %lu",
1248
+ GetLastError())));
1249
+ CloseHandle(pi.hProcess);
1250
+ CloseHandle(pi.hThread);
1251
+ return -1;
1252
+ }
1253
+ CloseHandle(pi.hProcess);
1254
+ CloseHandle(pi.hThread);
1255
+ ereport(LOG,
1256
+ (errmsg_internal("could not resume thread of unstarted process: error code %lu",
1257
+ GetLastError())));
1258
+ return -1;
1259
+ }
1260
+
1261
+ /*
1262
+ * Queue a waiter to signal when this child dies. The wait will be handled
1263
+ * automatically by an operating system thread pool.
1264
+ *
1265
+ * Note: use malloc instead of palloc, since it needs to be thread-safe.
1266
+ * Struct will be free():d from the callback function that runs on a
1267
+ * different thread.
1268
+ */
1269
+ childinfo = malloc(sizeof(win32_deadchild_waitinfo));
1270
+ if (!childinfo)
1271
+ ereport(FATAL,
1272
+ (errcode(ERRCODE_OUT_OF_MEMORY),
1273
+ errmsg("out of memory")));
1274
+
1275
+ childinfo->procHandle = pi.hProcess;
1276
+ childinfo->procId = pi.dwProcessId;
1277
+
1278
+ if (!RegisterWaitForSingleObject(&childinfo->waitHandle,
1279
+ pi.hProcess,
1280
+ pgwin32_deadchild_callback,
1281
+ childinfo,
1282
+ INFINITE,
1283
+ WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD))
1284
+ ereport(FATAL,
1285
+ (errmsg_internal("could not register process for wait: error code %lu",
1286
+ GetLastError())));
1287
+
1288
+ /* Don't close pi.hProcess here - the wait thread needs access to it */
1289
+
1290
+ CloseHandle(pi.hThread);
1291
+
1292
+ return pi.dwProcessId;
1293
+ }
1294
+ #endif /* WIN32 */
1295
+
1296
+
1297
+ /*
1298
+ * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
1299
+ * to what it would be if we'd simply forked on Unix, and then
1300
+ * dispatch to the appropriate place.
1301
+ *
1302
+ * The first two command line arguments are expected to be "--forkFOO"
1303
+ * (where FOO indicates which postmaster child we are to become), and
1304
+ * the name of a variables file that we can read to load data that would
1305
+ * have been inherited by fork() on Unix. Remaining arguments go to the
1306
+ * subprocess FooMain() routine.
1307
+ */
1308
+ void
1309
+ SubPostmasterMain(int argc, char *argv[])
1310
+ {
1311
+ Port port;
1312
+
1313
+ /* In EXEC_BACKEND case we will not have inherited these settings */
1314
+ IsPostmasterEnvironment = true;
1315
+ whereToSendOutput = DestNone;
1316
+
1317
+ /* Setup as postmaster child */
1318
+ InitPostmasterChild();
1319
+
1320
+ /* Setup essential subsystems (to ensure elog() behaves sanely) */
1321
+ InitializeGUCOptions();
1322
+
1323
+ /* Check we got appropriate args */
1324
+ if (argc < 3)
1325
+ elog(FATAL, "invalid subpostmaster invocation");
1326
+
1327
+ /* Read in the variables file */
1328
+ memset(&port, 0, sizeof(Port));
1329
+ read_backend_variables(argv[2], &port);
1330
+
1331
+ /* Close the postmaster's sockets (as soon as we know them) */
1332
+ ClosePostmasterPorts(strcmp(argv[1], "--forklog") == 0);
1333
+
1334
+ /*
1335
+ * If appropriate, physically re-attach to shared memory segment. We want
1336
+ * to do this before going any further to ensure that we can attach at the
1337
+ * same address the postmaster used. On the other hand, if we choose not
1338
+ * to re-attach, we may have other cleanup to do.
1339
+ *
1340
+ * If testing EXEC_BACKEND on Linux, you should run this as root before
1341
+ * starting the postmaster:
1342
+ *
1343
+ * echo 0 >/proc/sys/kernel/randomize_va_space
1344
+ *
1345
+ * This prevents using randomized stack and code addresses that cause the
1346
+ * child process's memory map to be different from the parent's, making it
1347
+ * sometimes impossible to attach to shared memory at the desired address.
1348
+ * Return the setting to its old value (usually '1' or '2') when finished.
1349
+ */
1350
+ if (strcmp(argv[1], "--forkbackend") == 0 ||
1351
+ strcmp(argv[1], "--forkavlauncher") == 0 ||
1352
+ strcmp(argv[1], "--forkavworker") == 0 ||
1353
+ strcmp(argv[1], "--forkboot") == 0 ||
1354
+ strncmp(argv[1], "--forkbgworker=", 15) == 0)
1355
+ PGSharedMemoryReAttach();
1356
+ else
1357
+ PGSharedMemoryNoReAttach();
1358
+
1359
+ /* autovacuum needs this set before calling InitProcess */
1360
+ if (strcmp(argv[1], "--forkavlauncher") == 0)
1361
+ AutovacuumLauncherIAm();
1362
+ if (strcmp(argv[1], "--forkavworker") == 0)
1363
+ AutovacuumWorkerIAm();
1364
+
1365
+ /*
1366
+ * Start our win32 signal implementation. This has to be done after we
1367
+ * read the backend variables, because we need to pick up the signal pipe
1368
+ * from the parent process.
1369
+ */
1370
+ #ifdef WIN32
1371
+ pgwin32_signal_initialize();
1372
+ #endif
1373
+
1374
+ /* In EXEC_BACKEND case we will not have inherited these settings */
1375
+ pqinitmask();
1376
+ PG_SETMASK(&BlockSig);
1377
+
1378
+ /* Read in remaining GUC variables */
1379
+ read_nondefault_variables();
1380
+
1381
+ /*
1382
+ * Check that the data directory looks valid, which will also check the
1383
+ * privileges on the data directory and update our umask and file/group
1384
+ * variables for creating files later. Note: this should really be done
1385
+ * before we create any files or directories.
1386
+ */
1387
+ checkDataDir();
1388
+
1389
+ /*
1390
+ * (re-)read control file, as it contains config. The postmaster will
1391
+ * already have read this, but this process doesn't know about that.
1392
+ */
1393
+ LocalProcessControlFile(false);
1394
+
1395
+ /*
1396
+ * Reload any libraries that were preloaded by the postmaster. Since we
1397
+ * exec'd this process, those libraries didn't come along with us; but we
1398
+ * should load them into all child processes to be consistent with the
1399
+ * non-EXEC_BACKEND behavior.
1400
+ */
1401
+ process_shared_preload_libraries();
1402
+
1403
+ /* Run backend or appropriate child */
1404
+ if (strcmp(argv[1], "--forkbackend") == 0)
1405
+ {
1406
+ Assert(argc == 3); /* shouldn't be any more args */
1407
+
1408
+ /*
1409
+ * Need to reinitialize the SSL library in the backend, since the
1410
+ * context structures contain function pointers and cannot be passed
1411
+ * through the parameter file.
1412
+ *
1413
+ * If for some reason reload fails (maybe the user installed broken
1414
+ * key files), soldier on without SSL; that's better than all
1415
+ * connections becoming impossible.
1416
+ *
1417
+ * XXX should we do this in all child processes? For the moment it's
1418
+ * enough to do it in backend children.
1419
+ */
1420
+ #ifdef USE_SSL
1421
+ if (EnableSSL)
1422
+ {
1423
+ if (secure_initialize(false) == 0)
1424
+ LoadedSSL = true;
1425
+ else
1426
+ ereport(LOG,
1427
+ (errmsg("SSL configuration could not be loaded in child process")));
1428
+ }
1429
+ #endif
1430
+
1431
+ /*
1432
+ * Perform additional initialization and collect startup packet.
1433
+ *
1434
+ * We want to do this before InitProcess() for a couple of reasons: 1.
1435
+ * so that we aren't eating up a PGPROC slot while waiting on the
1436
+ * client. 2. so that if InitProcess() fails due to being out of
1437
+ * PGPROC slots, we have already initialized libpq and are able to
1438
+ * report the error to the client.
1439
+ */
1440
+ BackendInitialize(&port);
1441
+
1442
+ /* Restore basic shared memory pointers */
1443
+ InitShmemAccess(UsedShmemSegAddr);
1444
+
1445
+ /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
1446
+ InitProcess();
1447
+
1448
+ /* Attach process to shared data structures */
1449
+ CreateSharedMemoryAndSemaphores();
1450
+
1451
+ /* And run the backend */
1452
+ BackendRun(&port); /* does not return */
1453
+ }
1454
+ if (strcmp(argv[1], "--forkboot") == 0)
1455
+ {
1456
+ /* Restore basic shared memory pointers */
1457
+ InitShmemAccess(UsedShmemSegAddr);
1458
+
1459
+ /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
1460
+ InitAuxiliaryProcess();
1461
+
1462
+ /* Attach process to shared data structures */
1463
+ CreateSharedMemoryAndSemaphores();
1464
+
1465
+ AuxiliaryProcessMain(argc - 2, argv + 2); /* does not return */
1466
+ }
1467
+ if (strcmp(argv[1], "--forkavlauncher") == 0)
1468
+ {
1469
+ /* Restore basic shared memory pointers */
1470
+ InitShmemAccess(UsedShmemSegAddr);
1471
+
1472
+ /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
1473
+ InitProcess();
1474
+
1475
+ /* Attach process to shared data structures */
1476
+ CreateSharedMemoryAndSemaphores();
1477
+
1478
+ AutoVacLauncherMain(argc - 2, argv + 2); /* does not return */
1479
+ }
1480
+ if (strcmp(argv[1], "--forkavworker") == 0)
1481
+ {
1482
+ /* Restore basic shared memory pointers */
1483
+ InitShmemAccess(UsedShmemSegAddr);
1484
+
1485
+ /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
1486
+ InitProcess();
1487
+
1488
+ /* Attach process to shared data structures */
1489
+ CreateSharedMemoryAndSemaphores();
1490
+
1491
+ AutoVacWorkerMain(argc - 2, argv + 2); /* does not return */
1492
+ }
1493
+ if (strncmp(argv[1], "--forkbgworker=", 15) == 0)
1494
+ {
1495
+ int shmem_slot;
1496
+
1497
+ /* do this as early as possible; in particular, before InitProcess() */
1498
+ IsBackgroundWorker = true;
1499
+
1500
+ /* Restore basic shared memory pointers */
1501
+ InitShmemAccess(UsedShmemSegAddr);
1502
+
1503
+ /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
1504
+ InitProcess();
1505
+
1506
+ /* Attach process to shared data structures */
1507
+ CreateSharedMemoryAndSemaphores();
1508
+
1509
+ /* Fetch MyBgworkerEntry from shared memory */
1510
+ shmem_slot = atoi(argv[1] + 15);
1511
+ MyBgworkerEntry = BackgroundWorkerEntry(shmem_slot);
1512
+
1513
+ StartBackgroundWorker();
1514
+ }
1515
+ if (strcmp(argv[1], "--forkarch") == 0)
1516
+ {
1517
+ /* Do not want to attach to shared memory */
1518
+
1519
+ PgArchiverMain(argc, argv); /* does not return */
1520
+ }
1521
+ if (strcmp(argv[1], "--forkcol") == 0)
1522
+ {
1523
+ /* Do not want to attach to shared memory */
1524
+
1525
+ PgstatCollectorMain(argc, argv); /* does not return */
1526
+ }
1527
+ if (strcmp(argv[1], "--forklog") == 0)
1528
+ {
1529
+ /* Do not want to attach to shared memory */
1530
+
1531
+ SysLoggerMain(argc, argv); /* does not return */
1532
+ }
1533
+
1534
+ abort(); /* shouldn't get here */
1535
+ }
1536
+ #endif /* EXEC_BACKEND */
1537
+
1538
+
1539
+ /*
1540
+ * ExitPostmaster -- cleanup
1541
+ *
1542
+ * Do NOT call exit() directly --- always go through here!
1543
+ */
1544
+ #ifdef HAVE_PTHREAD_IS_THREADED_NP
1545
+ #endif
1546
+
1547
+ /*
1548
+ * sigusr1_handler - handle signal conditions from child processes
1549
+ */
1550
+ #ifdef WIN32
1551
+ #endif
1552
+ #ifdef USE_SYSTEMD
1553
+ #endif
1554
+ #ifdef USE_SYSTEMD
1555
+ #endif
1556
+ #ifdef WIN32
1557
+ #endif
1558
+
1559
+ /*
1560
+ * SIGTERM while processing startup packet.
1561
+ * Clean up and exit(1).
1562
+ *
1563
+ * Running proc_exit() from a signal handler is pretty unsafe, since we
1564
+ * can't know what code we've interrupted. But the alternative of using
1565
+ * _exit(2) is also unpalatable, since it'd mean that a "fast shutdown"
1566
+ * would cause a database crash cycle (forcing WAL replay at restart)
1567
+ * if any sessions are in authentication. So we live with it for now.
1568
+ *
1569
+ * One might be tempted to try to send a message indicating why we are
1570
+ * disconnecting. However, that would make this even more unsafe. Also,
1571
+ * it seems undesirable to provide clues about the database's state to
1572
+ * a client that has not yet completed authentication.
1573
+ */
1574
+
1575
+
1576
+ /*
1577
+ * Dummy signal handler
1578
+ *
1579
+ * We use this for signals that we don't actually use in the postmaster,
1580
+ * but we do use in backends. If we were to SIG_IGN such signals in the
1581
+ * postmaster, then a newly started backend might drop a signal that arrives
1582
+ * before it's able to reconfigure its signal processing. (See notes in
1583
+ * tcop/postgres.c.)
1584
+ */
1585
+
1586
+
1587
+ /*
1588
+ * Timeout while processing startup packet.
1589
+ * As for process_startup_packet_die(), we clean up and exit(1).
1590
+ *
1591
+ * This is theoretically just as hazardous as in process_startup_packet_die(),
1592
+ * although in practice we're almost certainly waiting for client input,
1593
+ * which greatly reduces the risk.
1594
+ */
1595
+
1596
+
1597
+
1598
+ /*
1599
+ * Generate a random cancel key.
1600
+ */
1601
+
1602
+
1603
+ /*
1604
+ * Count up number of child processes of specified types (dead_end children
1605
+ * are always excluded).
1606
+ */
1607
+
1608
+
1609
+
1610
+ /*
1611
+ * StartChildProcess -- start an auxiliary process for the postmaster
1612
+ *
1613
+ * "type" determines what kind of child will be started. All child types
1614
+ * initially go to AuxiliaryProcessMain, which will handle common setup.
1615
+ *
1616
+ * Return value of StartChildProcess is subprocess' PID, or 0 if failed
1617
+ * to start subprocess.
1618
+ */
1619
+ #ifdef EXEC_BACKEND
1620
+ #endif
1621
+ #ifdef EXEC_BACKEND
1622
+ #else /* !EXEC_BACKEND */
1623
+ #endif /* EXEC_BACKEND */
1624
+
1625
+ /*
1626
+ * StartAutovacuumWorker
1627
+ * Start an autovac worker process.
1628
+ *
1629
+ * This function is here because it enters the resulting PID into the
1630
+ * postmaster's private backends list.
1631
+ *
1632
+ * NB -- this code very roughly matches BackendStartup.
1633
+ */
1634
+ #ifdef EXEC_BACKEND
1635
+ #endif
1636
+
1637
+ /*
1638
+ * MaybeStartWalReceiver
1639
+ * Start the WAL receiver process, if not running and our state allows.
1640
+ *
1641
+ * Note: if WalReceiverPID is already nonzero, it might seem that we should
1642
+ * clear WalReceiverRequested. However, there's a race condition if the
1643
+ * walreceiver terminates and the startup process immediately requests a new
1644
+ * one: it's quite possible to get the signal for the request before reaping
1645
+ * the dead walreceiver process. Better to risk launching an extra
1646
+ * walreceiver than to miss launching one we need. (The walreceiver code
1647
+ * has logic to recognize that it should go away if not needed.)
1648
+ */
1649
+
1650
+
1651
+
1652
+ /*
1653
+ * Create the opts file
1654
+ */
1655
+ #define OPTS_FILE "postmaster.opts"
1656
+
1657
+
1658
+ /*
1659
+ * MaxLivePostmasterChildren
1660
+ *
1661
+ * This reports the number of entries needed in per-child-process arrays
1662
+ * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray).
1663
+ * These arrays include regular backends, autovac workers, walsenders
1664
+ * and background workers, but not special children nor dead_end children.
1665
+ * This allows the arrays to have a fixed maximum size, to wit the same
1666
+ * too-many-children limit enforced by canAcceptConnections(). The exact value
1667
+ * isn't too critical as long as it's more than MaxBackends.
1668
+ */
1669
+
1670
+
1671
+ /*
1672
+ * Connect background worker to a database.
1673
+ */
1674
+
1675
+
1676
+ /*
1677
+ * Connect background worker to a database using OIDs.
1678
+ */
1679
+
1680
+
1681
+ /*
1682
+ * Block/unblock signals in a background worker
1683
+ */
1684
+
1685
+
1686
+
1687
+
1688
+ #ifdef EXEC_BACKEND
1689
+ static pid_t
1690
+ bgworker_forkexec(int shmem_slot)
1691
+ {
1692
+ char *av[10];
1693
+ int ac = 0;
1694
+ char forkav[MAXPGPATH];
1695
+
1696
+ snprintf(forkav, MAXPGPATH, "--forkbgworker=%d", shmem_slot);
1697
+
1698
+ av[ac++] = "postgres";
1699
+ av[ac++] = forkav;
1700
+ av[ac++] = NULL; /* filled in by postmaster_forkexec */
1701
+ av[ac] = NULL;
1702
+
1703
+ Assert(ac < lengthof(av));
1704
+
1705
+ return postmaster_forkexec(ac, av);
1706
+ }
1707
+ #endif
1708
+
1709
+ /*
1710
+ * Start a new bgworker.
1711
+ * Starting time conditions must have been checked already.
1712
+ *
1713
+ * Returns true on success, false on failure.
1714
+ * In either case, update the RegisteredBgWorker's state appropriately.
1715
+ *
1716
+ * This code is heavily based on autovacuum.c, q.v.
1717
+ */
1718
+ #ifdef EXEC_BACKEND
1719
+ #else
1720
+ #endif
1721
+ #ifndef EXEC_BACKEND
1722
+ #endif
1723
+ #ifdef EXEC_BACKEND
1724
+ #endif
1725
+
1726
+ /*
1727
+ * Does the current postmaster state require starting a worker with the
1728
+ * specified start_time?
1729
+ */
1730
+
1731
+
1732
+ /*
1733
+ * Allocate the Backend struct for a connected background worker, but don't
1734
+ * add it to the list of backends just yet.
1735
+ *
1736
+ * On failure, return false without changing any worker state.
1737
+ *
1738
+ * Some info from the Backend is copied into the passed rw.
1739
+ */
1740
+
1741
+
1742
+ /*
1743
+ * If the time is right, start background worker(s).
1744
+ *
1745
+ * As a side effect, the bgworker control variables are set or reset
1746
+ * depending on whether more workers may need to be started.
1747
+ *
1748
+ * We limit the number of workers started per call, to avoid consuming the
1749
+ * postmaster's attention for too long when many such requests are pending.
1750
+ * As long as StartWorkerNeeded is true, ServerLoop will not block and will
1751
+ * call this function again after dealing with any other issues.
1752
+ */
1753
+ #define MAX_BGWORKERS_TO_LAUNCH 100
1754
+
1755
+ /*
1756
+ * When a backend asks to be notified about worker state changes, we
1757
+ * set a flag in its backend entry. The background worker machinery needs
1758
+ * to know when such backends exit.
1759
+ */
1760
+
1761
+
1762
+ #ifdef EXEC_BACKEND
1763
+
1764
+ /*
1765
+ * The following need to be available to the save/restore_backend_variables
1766
+ * functions. They are marked NON_EXEC_STATIC in their home modules.
1767
+ */
1768
+ extern slock_t *ShmemLock;
1769
+ extern slock_t *ProcStructLock;
1770
+ extern PGPROC *AuxiliaryProcs;
1771
+ extern PMSignalData *PMSignalState;
1772
+ extern pgsocket pgStatSock;
1773
+ extern pg_time_t first_syslogger_file_time;
1774
+
1775
+ #ifndef WIN32
1776
+ #define write_inheritable_socket(dest, src, childpid) ((*(dest) = (src)), true)
1777
+ #define read_inheritable_socket(dest, src) (*(dest) = *(src))
1778
+ #else
1779
+ static bool write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE child);
1780
+ static bool write_inheritable_socket(InheritableSocket *dest, SOCKET src,
1781
+ pid_t childPid);
1782
+ static void read_inheritable_socket(SOCKET *dest, InheritableSocket *src);
1783
+ #endif
1784
+
1785
+
1786
+ /* Save critical backend variables into the BackendParameters struct */
1787
+ #ifndef WIN32
1788
+ static bool
1789
+ save_backend_variables(BackendParameters *param, Port *port)
1790
+ #else
1791
+ static bool
1792
+ save_backend_variables(BackendParameters *param, Port *port,
1793
+ HANDLE childProcess, pid_t childPid)
1794
+ #endif
1795
+ {
1796
+ memcpy(&param->port, port, sizeof(Port));
1797
+ if (!write_inheritable_socket(&param->portsocket, port->sock, childPid))
1798
+ return false;
1799
+
1800
+ strlcpy(param->DataDir, DataDir, MAXPGPATH);
1801
+
1802
+ memcpy(&param->ListenSocket, &ListenSocket, sizeof(ListenSocket));
1803
+
1804
+ param->MyCancelKey = MyCancelKey;
1805
+ param->MyPMChildSlot = MyPMChildSlot;
1806
+
1807
+ #ifdef WIN32
1808
+ param->ShmemProtectiveRegion = ShmemProtectiveRegion;
1809
+ #endif
1810
+ param->UsedShmemSegID = UsedShmemSegID;
1811
+ param->UsedShmemSegAddr = UsedShmemSegAddr;
1812
+
1813
+ param->ShmemLock = ShmemLock;
1814
+ param->ShmemVariableCache = ShmemVariableCache;
1815
+ param->ShmemBackendArray = ShmemBackendArray;
1816
+
1817
+ #ifndef HAVE_SPINLOCKS
1818
+ param->SpinlockSemaArray = SpinlockSemaArray;
1819
+ #endif
1820
+ param->NamedLWLockTrancheRequests = NamedLWLockTrancheRequests;
1821
+ param->NamedLWLockTrancheArray = NamedLWLockTrancheArray;
1822
+ param->MainLWLockArray = MainLWLockArray;
1823
+ param->ProcStructLock = ProcStructLock;
1824
+ param->ProcGlobal = ProcGlobal;
1825
+ param->AuxiliaryProcs = AuxiliaryProcs;
1826
+ param->PreparedXactProcs = PreparedXactProcs;
1827
+ param->PMSignalState = PMSignalState;
1828
+ if (!write_inheritable_socket(&param->pgStatSock, pgStatSock, childPid))
1829
+ return false;
1830
+
1831
+ param->PostmasterPid = PostmasterPid;
1832
+ param->PgStartTime = PgStartTime;
1833
+ param->PgReloadTime = PgReloadTime;
1834
+ param->first_syslogger_file_time = first_syslogger_file_time;
1835
+
1836
+ param->redirection_done = redirection_done;
1837
+ param->IsBinaryUpgrade = IsBinaryUpgrade;
1838
+ param->max_safe_fds = max_safe_fds;
1839
+
1840
+ param->MaxBackends = MaxBackends;
1841
+
1842
+ #ifdef WIN32
1843
+ param->PostmasterHandle = PostmasterHandle;
1844
+ if (!write_duplicated_handle(&param->initial_signal_pipe,
1845
+ pgwin32_create_signal_listener(childPid),
1846
+ childProcess))
1847
+ return false;
1848
+ #else
1849
+ memcpy(&param->postmaster_alive_fds, &postmaster_alive_fds,
1850
+ sizeof(postmaster_alive_fds));
1851
+ #endif
1852
+
1853
+ memcpy(&param->syslogPipe, &syslogPipe, sizeof(syslogPipe));
1854
+
1855
+ strlcpy(param->my_exec_path, my_exec_path, MAXPGPATH);
1856
+
1857
+ strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH);
1858
+
1859
+ strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
1860
+
1861
+ return true;
1862
+ }
1863
+
1864
+
1865
+ #ifdef WIN32
1866
+ /*
1867
+ * Duplicate a handle for usage in a child process, and write the child
1868
+ * process instance of the handle to the parameter file.
1869
+ */
1870
+ static bool
1871
+ write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE childProcess)
1872
+ {
1873
+ HANDLE hChild = INVALID_HANDLE_VALUE;
1874
+
1875
+ if (!DuplicateHandle(GetCurrentProcess(),
1876
+ src,
1877
+ childProcess,
1878
+ &hChild,
1879
+ 0,
1880
+ TRUE,
1881
+ DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
1882
+ {
1883
+ ereport(LOG,
1884
+ (errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %lu",
1885
+ GetLastError())));
1886
+ return false;
1887
+ }
1888
+
1889
+ *dest = hChild;
1890
+ return true;
1891
+ }
1892
+
1893
+ /*
1894
+ * Duplicate a socket for usage in a child process, and write the resulting
1895
+ * structure to the parameter file.
1896
+ * This is required because a number of LSPs (Layered Service Providers) very
1897
+ * common on Windows (antivirus, firewalls, download managers etc) break
1898
+ * straight socket inheritance.
1899
+ */
1900
+ static bool
1901
+ write_inheritable_socket(InheritableSocket *dest, SOCKET src, pid_t childpid)
1902
+ {
1903
+ dest->origsocket = src;
1904
+ if (src != 0 && src != PGINVALID_SOCKET)
1905
+ {
1906
+ /* Actual socket */
1907
+ if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0)
1908
+ {
1909
+ ereport(LOG,
1910
+ (errmsg("could not duplicate socket %d for use in backend: error code %d",
1911
+ (int) src, WSAGetLastError())));
1912
+ return false;
1913
+ }
1914
+ }
1915
+ return true;
1916
+ }
1917
+
1918
+ /*
1919
+ * Read a duplicate socket structure back, and get the socket descriptor.
1920
+ */
1921
+ static void
1922
+ read_inheritable_socket(SOCKET *dest, InheritableSocket *src)
1923
+ {
1924
+ SOCKET s;
1925
+
1926
+ if (src->origsocket == PGINVALID_SOCKET || src->origsocket == 0)
1927
+ {
1928
+ /* Not a real socket! */
1929
+ *dest = src->origsocket;
1930
+ }
1931
+ else
1932
+ {
1933
+ /* Actual socket, so create from structure */
1934
+ s = WSASocket(FROM_PROTOCOL_INFO,
1935
+ FROM_PROTOCOL_INFO,
1936
+ FROM_PROTOCOL_INFO,
1937
+ &src->wsainfo,
1938
+ 0,
1939
+ 0);
1940
+ if (s == INVALID_SOCKET)
1941
+ {
1942
+ write_stderr("could not create inherited socket: error code %d\n",
1943
+ WSAGetLastError());
1944
+ exit(1);
1945
+ }
1946
+ *dest = s;
1947
+
1948
+ /*
1949
+ * To make sure we don't get two references to the same socket, close
1950
+ * the original one. (This would happen when inheritance actually
1951
+ * works..
1952
+ */
1953
+ closesocket(src->origsocket);
1954
+ }
1955
+ }
1956
+ #endif
1957
+
1958
+ static void
1959
+ read_backend_variables(char *id, Port *port)
1960
+ {
1961
+ BackendParameters param;
1962
+
1963
+ #ifndef WIN32
1964
+ /* Non-win32 implementation reads from file */
1965
+ FILE *fp;
1966
+
1967
+ /* Open file */
1968
+ fp = AllocateFile(id, PG_BINARY_R);
1969
+ if (!fp)
1970
+ {
1971
+ write_stderr("could not open backend variables file \"%s\": %s\n",
1972
+ id, strerror(errno));
1973
+ exit(1);
1974
+ }
1975
+
1976
+ if (fread(&param, sizeof(param), 1, fp) != 1)
1977
+ {
1978
+ write_stderr("could not read from backend variables file \"%s\": %s\n",
1979
+ id, strerror(errno));
1980
+ exit(1);
1981
+ }
1982
+
1983
+ /* Release file */
1984
+ FreeFile(fp);
1985
+ if (unlink(id) != 0)
1986
+ {
1987
+ write_stderr("could not remove file \"%s\": %s\n",
1988
+ id, strerror(errno));
1989
+ exit(1);
1990
+ }
1991
+ #else
1992
+ /* Win32 version uses mapped file */
1993
+ HANDLE paramHandle;
1994
+ BackendParameters *paramp;
1995
+
1996
+ #ifdef _WIN64
1997
+ paramHandle = (HANDLE) _atoi64(id);
1998
+ #else
1999
+ paramHandle = (HANDLE) atol(id);
2000
+ #endif
2001
+ paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0);
2002
+ if (!paramp)
2003
+ {
2004
+ write_stderr("could not map view of backend variables: error code %lu\n",
2005
+ GetLastError());
2006
+ exit(1);
2007
+ }
2008
+
2009
+ memcpy(&param, paramp, sizeof(BackendParameters));
2010
+
2011
+ if (!UnmapViewOfFile(paramp))
2012
+ {
2013
+ write_stderr("could not unmap view of backend variables: error code %lu\n",
2014
+ GetLastError());
2015
+ exit(1);
2016
+ }
2017
+
2018
+ if (!CloseHandle(paramHandle))
2019
+ {
2020
+ write_stderr("could not close handle to backend parameter variables: error code %lu\n",
2021
+ GetLastError());
2022
+ exit(1);
2023
+ }
2024
+ #endif
2025
+
2026
+ restore_backend_variables(&param, port);
2027
+ }
2028
+
2029
+ /* Restore critical backend variables from the BackendParameters struct */
2030
+ static void
2031
+ restore_backend_variables(BackendParameters *param, Port *port)
2032
+ {
2033
+ memcpy(port, &param->port, sizeof(Port));
2034
+ read_inheritable_socket(&port->sock, &param->portsocket);
2035
+
2036
+ SetDataDir(param->DataDir);
2037
+
2038
+ memcpy(&ListenSocket, &param->ListenSocket, sizeof(ListenSocket));
2039
+
2040
+ MyCancelKey = param->MyCancelKey;
2041
+ MyPMChildSlot = param->MyPMChildSlot;
2042
+
2043
+ #ifdef WIN32
2044
+ ShmemProtectiveRegion = param->ShmemProtectiveRegion;
2045
+ #endif
2046
+ UsedShmemSegID = param->UsedShmemSegID;
2047
+ UsedShmemSegAddr = param->UsedShmemSegAddr;
2048
+
2049
+ ShmemLock = param->ShmemLock;
2050
+ ShmemVariableCache = param->ShmemVariableCache;
2051
+ ShmemBackendArray = param->ShmemBackendArray;
2052
+
2053
+ #ifndef HAVE_SPINLOCKS
2054
+ SpinlockSemaArray = param->SpinlockSemaArray;
2055
+ #endif
2056
+ NamedLWLockTrancheRequests = param->NamedLWLockTrancheRequests;
2057
+ NamedLWLockTrancheArray = param->NamedLWLockTrancheArray;
2058
+ MainLWLockArray = param->MainLWLockArray;
2059
+ ProcStructLock = param->ProcStructLock;
2060
+ ProcGlobal = param->ProcGlobal;
2061
+ AuxiliaryProcs = param->AuxiliaryProcs;
2062
+ PreparedXactProcs = param->PreparedXactProcs;
2063
+ PMSignalState = param->PMSignalState;
2064
+ read_inheritable_socket(&pgStatSock, &param->pgStatSock);
2065
+
2066
+ PostmasterPid = param->PostmasterPid;
2067
+ PgStartTime = param->PgStartTime;
2068
+ PgReloadTime = param->PgReloadTime;
2069
+ first_syslogger_file_time = param->first_syslogger_file_time;
2070
+
2071
+ redirection_done = param->redirection_done;
2072
+ IsBinaryUpgrade = param->IsBinaryUpgrade;
2073
+ max_safe_fds = param->max_safe_fds;
2074
+
2075
+ MaxBackends = param->MaxBackends;
2076
+
2077
+ #ifdef WIN32
2078
+ PostmasterHandle = param->PostmasterHandle;
2079
+ pgwin32_initial_signal_pipe = param->initial_signal_pipe;
2080
+ #else
2081
+ memcpy(&postmaster_alive_fds, &param->postmaster_alive_fds,
2082
+ sizeof(postmaster_alive_fds));
2083
+ #endif
2084
+
2085
+ memcpy(&syslogPipe, &param->syslogPipe, sizeof(syslogPipe));
2086
+
2087
+ strlcpy(my_exec_path, param->my_exec_path, MAXPGPATH);
2088
+
2089
+ strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);
2090
+
2091
+ strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
2092
+
2093
+ /*
2094
+ * We need to restore fd.c's counts of externally-opened FDs; to avoid
2095
+ * confusion, be sure to do this after restoring max_safe_fds. (Note:
2096
+ * BackendInitialize will handle this for port->sock.)
2097
+ */
2098
+ #ifndef WIN32
2099
+ if (postmaster_alive_fds[0] >= 0)
2100
+ ReserveExternalFD();
2101
+ if (postmaster_alive_fds[1] >= 0)
2102
+ ReserveExternalFD();
2103
+ #endif
2104
+ if (pgStatSock != PGINVALID_SOCKET)
2105
+ ReserveExternalFD();
2106
+ }
2107
+
2108
+
2109
+ Size
2110
+ ShmemBackendArraySize(void)
2111
+ {
2112
+ return mul_size(MaxLivePostmasterChildren(), sizeof(Backend));
2113
+ }
2114
+
2115
+ void
2116
+ ShmemBackendArrayAllocation(void)
2117
+ {
2118
+ Size size = ShmemBackendArraySize();
2119
+
2120
+ ShmemBackendArray = (Backend *) ShmemAlloc(size);
2121
+ /* Mark all slots as empty */
2122
+ memset(ShmemBackendArray, 0, size);
2123
+ }
2124
+
2125
+ static void
2126
+ ShmemBackendArrayAdd(Backend *bn)
2127
+ {
2128
+ /* The array slot corresponding to my PMChildSlot should be free */
2129
+ int i = bn->child_slot - 1;
2130
+
2131
+ Assert(ShmemBackendArray[i].pid == 0);
2132
+ ShmemBackendArray[i] = *bn;
2133
+ }
2134
+
2135
+ static void
2136
+ ShmemBackendArrayRemove(Backend *bn)
2137
+ {
2138
+ int i = bn->child_slot - 1;
2139
+
2140
+ Assert(ShmemBackendArray[i].pid == bn->pid);
2141
+ /* Mark the slot as empty */
2142
+ ShmemBackendArray[i].pid = 0;
2143
+ }
2144
+ #endif /* EXEC_BACKEND */
2145
+
2146
+
2147
+ #ifdef WIN32
2148
+
2149
+ /*
2150
+ * Subset implementation of waitpid() for Windows. We assume pid is -1
2151
+ * (that is, check all child processes) and options is WNOHANG (don't wait).
2152
+ */
2153
+ static pid_t
2154
+ waitpid(pid_t pid, int *exitstatus, int options)
2155
+ {
2156
+ DWORD dwd;
2157
+ ULONG_PTR key;
2158
+ OVERLAPPED *ovl;
2159
+
2160
+ /*
2161
+ * Check if there are any dead children. If there are, return the pid of
2162
+ * the first one that died.
2163
+ */
2164
+ if (GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0))
2165
+ {
2166
+ *exitstatus = (int) key;
2167
+ return dwd;
2168
+ }
2169
+
2170
+ return -1;
2171
+ }
2172
+
2173
+ /*
2174
+ * Note! Code below executes on a thread pool! All operations must
2175
+ * be thread safe! Note that elog() and friends must *not* be used.
2176
+ */
2177
+ static void WINAPI
2178
+ pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
2179
+ {
2180
+ win32_deadchild_waitinfo *childinfo = (win32_deadchild_waitinfo *) lpParameter;
2181
+ DWORD exitcode;
2182
+
2183
+ if (TimerOrWaitFired)
2184
+ return; /* timeout. Should never happen, since we use
2185
+ * INFINITE as timeout value. */
2186
+
2187
+ /*
2188
+ * Remove handle from wait - required even though it's set to wait only
2189
+ * once
2190
+ */
2191
+ UnregisterWaitEx(childinfo->waitHandle, NULL);
2192
+
2193
+ if (!GetExitCodeProcess(childinfo->procHandle, &exitcode))
2194
+ {
2195
+ /*
2196
+ * Should never happen. Inform user and set a fixed exitcode.
2197
+ */
2198
+ write_stderr("could not read exit code for process\n");
2199
+ exitcode = 255;
2200
+ }
2201
+
2202
+ if (!PostQueuedCompletionStatus(win32ChildQueue, childinfo->procId, (ULONG_PTR) exitcode, NULL))
2203
+ write_stderr("could not post child completion status\n");
2204
+
2205
+ /*
2206
+ * Handle is per-process, so we close it here instead of in the
2207
+ * originating thread
2208
+ */
2209
+ CloseHandle(childinfo->procHandle);
2210
+
2211
+ /*
2212
+ * Free struct that was allocated before the call to
2213
+ * RegisterWaitForSingleObject()
2214
+ */
2215
+ free(childinfo);
2216
+
2217
+ /* Queue SIGCHLD signal */
2218
+ pg_queue_signal(SIGCHLD);
2219
+ }
2220
+ #endif /* WIN32 */
2221
+
2222
+ /*
2223
+ * Initialize one and only handle for monitoring postmaster death.
2224
+ *
2225
+ * Called once in the postmaster, so that child processes can subsequently
2226
+ * monitor if their parent is dead.
2227
+ */
2228
+ #ifndef WIN32
2229
+ #else
2230
+ #endif /* WIN32 */