1/*-
2 * Copyright (c) 1992, 1993, 1994
3 *	The Regents of the University of California.  All rights reserved.
4 * Copyright (c) 1992, 1993, 1994, 1995, 1996
5 *	Keith Bostic.  All rights reserved.
6 *
7 * See the LICENSE file for redistribution information.
8 */
9
10#include "config.h"
11
12#include <sys/cdefs.h>
13#if 0
14#ifndef lint
15static const char sccsid[] = "Id: db.c,v 10.48 2002/06/08 19:32:52 skimo Exp  (Berkeley) Date: 2002/06/08 19:32:52 ";
16#endif /* not lint */
17#else
18__RCSID("$NetBSD: vi_db.c,v 1.6 2014/01/26 21:43:45 christos Exp $");
19#endif
20
21#include <sys/types.h>
22#include <sys/queue.h>
23#include <sys/time.h>
24#include <sys/stat.h>
25
26#include <bitstring.h>
27#include <errno.h>
28#include <limits.h>
29#include <stdio.h>
30#include <string.h>
31#include <stdlib.h>
32#include <unistd.h>
33
34#include "common.h"
35#include "dbinternal.h"
36#include "../vi/vi.h"
37
38static int append __P((SCR*, db_recno_t, const CHAR_T*, size_t, lnop_t, int));
39
40/*
41 * db_eget --
42 *	Front-end to db_get, special case handling for empty files.
43 *
44 * PUBLIC: int db_eget __P((SCR *, db_recno_t, CHAR_T **, size_t *, int *));
45 */
46int
47db_eget(SCR *sp, db_recno_t lno, CHAR_T **pp, size_t *lenp, int *isemptyp)
48
49	               				/* Line number. */
50	            				/* Pointer store. */
51	             				/* Length store. */
52
53{
54	db_recno_t l1;
55
56	if (isemptyp != NULL)
57		*isemptyp = 0;
58
59	/* If the line exists, simply return it. */
60	if (!db_get(sp, lno, 0, pp, lenp))
61		return (0);
62
63	/*
64	 * If the user asked for line 0 or line 1, i.e. the only possible
65	 * line in an empty file, find the last line of the file; db_last
66	 * fails loudly.
67	 */
68	if ((lno == 0 || lno == 1) && db_last(sp, &l1))
69		return (1);
70
71	/* If the file isn't empty, fail loudly. */
72	if ((lno != 0 && lno != 1) || l1 != 0) {
73		db_err(sp, lno);
74		return (1);
75	}
76
77	if (isemptyp != NULL)
78		*isemptyp = 1;
79
80	return (1);
81}
82
83/*
84 * db_get --
85 *	Look in the text buffers for a line, followed by the cache, followed
86 *	by the database.
87 *
88 * PUBLIC: int db_get __P((SCR *, db_recno_t, u_int32_t, CHAR_T **, size_t *));
89 */
90int
91db_get(SCR *sp, db_recno_t lno, u_int32_t flags, CHAR_T **pp, size_t *lenp)
92		/* Line number. */ /* Pointer store. */ /* Length store. */
93{
94	DBT data, key;
95	EXF *ep;
96	TEXT *tp;
97	db_recno_t l1, l2;
98	const CHAR_T *wp;
99	size_t wlen;
100	size_t nlen;
101
102	/*
103	 * The underlying recno stuff handles zero by returning NULL, but
104	 * have to have an OOB condition for the look-aside into the input
105	 * buffer anyway.
106	 */
107	if (lno == 0)
108		goto err1;
109
110	/* Check for no underlying file. */
111	if ((ep = sp->ep) == NULL) {
112		ex_emsg(sp, NULL, EXM_NOFILEYET);
113		goto err3;
114	}
115
116	if (LF_ISSET(DBG_NOCACHE))
117		goto nocache;
118
119	/*
120	 * Look-aside into the TEXT buffers and see if the line we want
121	 * is there.
122	 */
123	if (F_ISSET(sp, SC_TINPUT)) {
124		l1 = TAILQ_FIRST(&sp->tiq)->lno;
125		l2 = TAILQ_LAST(&sp->tiq, _texth)->lno;
126		if (l1 <= lno && l2 >= lno) {
127#if defined(DEBUG) && 0
128			vtrace(sp,
129			    "retrieve TEXT buffer line %lu\n", (u_long)lno);
130#endif
131			for (tp = TAILQ_FIRST(&sp->tiq);
132			    tp->lno != lno; tp = TAILQ_NEXT(tp, q));
133			if (lenp != NULL)
134				*lenp = tp->len;
135			if (pp != NULL)
136				*pp = tp->lb;
137			return (0);
138		}
139		/*
140		 * Adjust the line number for the number of lines used
141		 * by the text input buffers.
142		 */
143		if (lno > l2)
144			lno -= l2 - l1;
145	}
146
147	/* Look-aside into the cache, and see if the line we want is there. */
148	if (lno == sp->c_lno) {
149#if defined(DEBUG) && 0
150		vtrace(sp, "retrieve cached line %lu\n", (u_long)lno);
151#endif
152		if (lenp != NULL)
153			*lenp = sp->c_len;
154		if (pp != NULL)
155			*pp = sp->c_lp;
156		return (0);
157	}
158	sp->c_lno = OOBLNO;
159
160nocache:
161	nlen = 1024;
162retry:
163	/* data.size contains length in bytes */
164	BINC_GOTO(sp, CHAR_T, sp->c_lp, sp->c_blen, nlen);
165
166	/* Get the line from the underlying database. */
167	memset(&key, 0, sizeof(key));
168	key.data = &lno;
169	key.size = sizeof(lno);
170	memset(&data, 0, sizeof(data));
171	data.data = sp->c_lp;
172	data.ulen = sp->c_blen;
173	data.flags = DB_DBT_USERMEM;
174	switch (ep->db->get(ep->db, NULL, &key, &data, 0)) {
175	case DB_BUFFER_SMALL:
176		nlen = data.size;
177		goto retry;
178        default:
179		goto err2;
180	case DB_NOTFOUND:
181err1:		if (LF_ISSET(DBG_FATAL))
182err2:			db_err(sp, lno);
183alloc_err:
184err3:		if (lenp != NULL)
185			*lenp = 0;
186		if (pp != NULL)
187			*pp = NULL;
188		return (1);
189	case 0:
190		;
191	}
192
193	if (FILE2INT(sp, data.data, data.size, wp, wlen)) {
194	    if (!F_ISSET(sp, SC_CONV_ERROR)) {
195		F_SET(sp, SC_CONV_ERROR);
196		msgq(sp, M_ERR, "324|Conversion error on line %d", lno);
197	    }
198	    goto err3;
199	}
200
201	/* Reset the cache. */
202	if (wp != data.data) {
203	    BINC_GOTOW(sp, sp->c_lp, sp->c_blen, wlen);
204	    MEMCPYW(sp->c_lp, wp, wlen);
205	}
206	sp->c_lno = lno;
207	sp->c_len = wlen;
208
209#if defined(DEBUG) && 0
210	vtrace(sp, "retrieve DB line %lu\n", (u_long)lno);
211#endif
212	if (lenp != NULL)
213		*lenp = wlen;
214	if (pp != NULL)
215		*pp = sp->c_lp;
216	return (0);
217}
218
219/*
220 * db_delete --
221 *	Delete a line from the file.
222 *
223 * PUBLIC: int db_delete __P((SCR *, db_recno_t));
224 */
225int
226db_delete(SCR *sp, db_recno_t lno)
227{
228	DBT key;
229	EXF *ep;
230
231#if defined(DEBUG) && 0
232	vtrace(sp, "delete line %lu\n", (u_long)lno);
233#endif
234	/* Check for no underlying file. */
235	if ((ep = sp->ep) == NULL) {
236		ex_emsg(sp, NULL, EXM_NOFILEYET);
237		return (1);
238	}
239	if (ep->l_win && ep->l_win != sp->wp) {
240		ex_emsg(sp, NULL, EXM_LOCKED);
241		return 1;
242	}
243
244	/* Update marks, @ and global commands. */
245	if (line_insdel(sp, LINE_DELETE, lno))
246		return 1;
247
248	/* Log before change. */
249	log_line(sp, lno, LOG_LINE_DELETE_B);
250
251	/* Update file. */
252	memset(&key, 0, sizeof(key));
253	key.data = &lno;
254	key.size = sizeof(lno);
255	if ((sp->db_error = ep->db->del(ep->db, NULL, &key, 0)) != 0) {
256		msgq(sp, M_DBERR, "003|unable to delete line %lu",
257		    (u_long)lno);
258		return (1);
259	}
260
261	/* Flush the cache, update line count, before screen update. */
262	update_cache(sp, LINE_DELETE, lno);
263
264	/* File now modified. */
265	if (F_ISSET(ep, F_FIRSTMODIFY))
266		(void)rcv_init(sp);
267	F_SET(ep, F_MODIFIED);
268
269	/* Log after change. */
270	log_line(sp, lno, LOG_LINE_DELETE_F);
271
272	/* Update screen. */
273	return (scr_update(sp, lno, LINE_DELETE, 1));
274}
275
276/* maybe this could be simpler
277 *
278 * DB3 behaves differently from DB1
279 *
280 * if lno != 0 just go to lno and put the new line after it
281 * if lno == 0 then if there are any record, put in front of the first
282 *		    otherwise just append to the end thus creating the first
283 *				line
284 */
285static int
286append(SCR *sp, db_recno_t lno, const CHAR_T *p, size_t len, lnop_t op, int update)
287{
288	DBT data, key;
289	DBC *dbcp_put;
290	EXF *ep;
291	const char *fp;
292	size_t flen;
293	int rval;
294
295	/* Check for no underlying file. */
296	if ((ep = sp->ep) == NULL) {
297		ex_emsg(sp, NULL, EXM_NOFILEYET);
298		return (1);
299	}
300	if (ep->l_win && ep->l_win != sp->wp) {
301		ex_emsg(sp, NULL, EXM_LOCKED);
302		return 1;
303	}
304
305	/* Log before change. */
306	log_line(sp, lno + 1, LOG_LINE_APPEND_B);
307
308	/* Update file. */
309	memset(&key, 0, sizeof(key));
310	key.data = &lno;
311	key.size = sizeof(lno);
312	memset(&data, 0, sizeof(data));
313
314	if ((sp->db_error = ep->db->cursor(ep->db, NULL, &dbcp_put, 0)) != 0)
315	    return 1;
316
317	INT2FILE(sp, p, len, fp, flen);
318
319	if (lno != 0) {
320	    if ((sp->db_error = dbcp_put->c_get(dbcp_put, &key, &data, DB_SET)) != 0)
321		goto err2;
322
323	    data.data = __UNCONST(fp);
324	    data.size = flen;
325	    if ((sp->db_error = dbcp_put->c_put(dbcp_put, &key, &data, DB_AFTER)) != 0) {
326err2:
327		(void)dbcp_put->c_close(dbcp_put);
328		msgq(sp, M_DBERR,
329			(op == LINE_APPEND)
330			    ? "004|unable to append to line %lu"
331			    : "005|unable to insert at line %lu",
332			(u_long)lno);
333		return (1);
334	    }
335	} else {
336	    if ((sp->db_error = dbcp_put->c_get(dbcp_put, &key, &data, DB_FIRST)) != 0) {
337		if (sp->db_error != DB_NOTFOUND)
338		    goto err2;
339
340		data.data = __UNCONST(fp);
341		data.size = flen;
342		if ((sp->db_error = ep->db->put(ep->db, NULL, &key, &data, DB_APPEND)) != 0) {
343		    goto err2;
344		}
345	    } else {
346		key.data = &lno;
347		key.size = sizeof(lno);
348		data.data = __UNCONST(fp);
349		data.size = flen;
350		if ((sp->db_error = dbcp_put->c_put(dbcp_put, &key, &data, DB_BEFORE)) != 0) {
351		    goto err2;
352		}
353	    }
354	}
355
356	(void)dbcp_put->c_close(dbcp_put);
357
358	/* Flush the cache, update line count, before screen update. */
359	update_cache(sp, LINE_INSERT, lno);
360
361	/* File now dirty. */
362	if (F_ISSET(ep, F_FIRSTMODIFY))
363		(void)rcv_init(sp);
364	F_SET(ep, F_MODIFIED);
365
366	/* Log after change. */
367	log_line(sp, lno + 1, LOG_LINE_APPEND_F);
368
369	/* Update marks, @ and global commands. */
370	rval = line_insdel(sp, LINE_INSERT, lno + 1);
371
372	/*
373	 * Update screen.
374	 *
375	 * comment copied from db_append
376	 * XXX
377	 * Nasty hack.  If multiple lines are input by the user, they aren't
378	 * committed until an <ESC> is entered.  The problem is the screen was
379	 * updated/scrolled as each line was entered.  So, when this routine
380	 * is called to copy the new lines from the cut buffer into the file,
381	 * it has to know not to update the screen again.
382	 */
383	return (scr_update(sp, lno + 1, LINE_INSERT, update) || rval);
384}
385
386/*
387 * db_append --
388 *	Append a line into the file.
389 *
390 * PUBLIC: int db_append __P((SCR *, int, db_recno_t, const CHAR_T *, size_t));
391 */
392int
393db_append(SCR *sp, int update, db_recno_t lno, const CHAR_T *p, size_t len)
394{
395#if defined(DEBUG) && 0
396	vtrace(sp, "append to %lu: len %u {%.*s}\n", lno, len, MIN(len, 20), p);
397#endif
398
399	/* Update file. */
400	return append(sp, lno, p, len, LINE_APPEND, update);
401}
402
403/*
404 * db_insert --
405 *	Insert a line into the file.
406 *
407 * PUBLIC: int db_insert __P((SCR *, db_recno_t, CHAR_T *, size_t));
408 */
409int
410db_insert(SCR *sp, db_recno_t lno, CHAR_T *p, size_t len)
411{
412#if defined(DEBUG) && 0
413	vtrace(sp, "insert before %lu: len %lu {%.*s}\n",
414	    (u_long)lno, (u_long)len, MIN(len, 20), p);
415#endif
416	return append(sp, lno - 1, p, len, LINE_INSERT, 1);
417}
418
419/*
420 * db_set --
421 *	Store a line in the file.
422 *
423 * PUBLIC: int db_set __P((SCR *, db_recno_t, CHAR_T *, size_t));
424 */
425int
426db_set(SCR *sp, db_recno_t lno, CHAR_T *p, size_t len)
427{
428	DBT data, key;
429	EXF *ep;
430	const char *fp;
431	size_t flen;
432
433#if defined(DEBUG) && 0
434	vtrace(sp, "replace line %lu: len %lu {%.*s}\n",
435	    (u_long)lno, (u_long)len, MIN(len, 20), p);
436#endif
437	/* Check for no underlying file. */
438	if ((ep = sp->ep) == NULL) {
439		ex_emsg(sp, NULL, EXM_NOFILEYET);
440		return (1);
441	}
442	if (ep->l_win && ep->l_win != sp->wp) {
443		ex_emsg(sp, NULL, EXM_LOCKED);
444		return 1;
445	}
446
447	/* Log before change. */
448	log_line(sp, lno, LOG_LINE_RESET_B);
449
450	INT2FILE(sp, p, len, fp, flen);
451
452	/* Update file. */
453	memset(&key, 0, sizeof(key));
454	key.data = &lno;
455	key.size = sizeof(lno);
456	memset(&data, 0, sizeof(data));
457	data.data = __UNCONST(fp);
458	data.size = flen;
459	if ((sp->db_error = ep->db->put(ep->db, NULL, &key, &data, 0)) != 0) {
460		msgq(sp, M_DBERR, "006|unable to store line %lu", (u_long)lno);
461		return (1);
462	}
463
464	/* Flush the cache, update line count, before screen update. */
465	update_cache(sp, LINE_RESET, lno);
466
467	/* File now dirty. */
468	if (F_ISSET(ep, F_FIRSTMODIFY))
469		(void)rcv_init(sp);
470	F_SET(ep, F_MODIFIED);
471
472	/* Log after change. */
473	log_line(sp, lno, LOG_LINE_RESET_F);
474
475	/* Update screen. */
476	return (scr_update(sp, lno, LINE_RESET, 1));
477}
478
479/*
480 * db_exist --
481 *	Return if a line exists.
482 *
483 * PUBLIC: int db_exist __P((SCR *, db_recno_t));
484 */
485int
486db_exist(SCR *sp, db_recno_t lno)
487{
488	EXF *ep;
489
490	/* Check for no underlying file. */
491	if ((ep = sp->ep) == NULL) {
492		ex_emsg(sp, NULL, EXM_NOFILEYET);
493		return (1);
494	}
495
496	if (lno == OOBLNO)
497		return (0);
498
499	/*
500	 * Check the last-line number cache.  Adjust the cached line
501	 * number for the lines used by the text input buffers.
502	 */
503	if (ep->c_nlines != OOBLNO)
504		return (lno <= (F_ISSET(sp, SC_TINPUT) ?
505		    ep->c_nlines + TAILQ_LAST(&sp->tiq, _texth)->lno -
506		    TAILQ_FIRST(&sp->tiq)->lno : ep->c_nlines));
507
508	/* Go get the line. */
509	return (!db_get(sp, lno, 0, NULL, NULL));
510}
511
512/*
513 * db_last --
514 *	Return the number of lines in the file.
515 *
516 * PUBLIC: int db_last __P((SCR *, db_recno_t *));
517 */
518int
519db_last(SCR *sp, db_recno_t *lnop)
520{
521	DBT data, key;
522	DBC *dbcp;
523	EXF *ep;
524	db_recno_t lno;
525	const CHAR_T *wp;
526	size_t wlen;
527
528	/* Check for no underlying file. */
529	if ((ep = sp->ep) == NULL) {
530		ex_emsg(sp, NULL, EXM_NOFILEYET);
531		return (1);
532	}
533
534	/*
535	 * Check the last-line number cache.  Adjust the cached line
536	 * number for the lines used by the text input buffers.
537	 */
538	if (ep->c_nlines != OOBLNO) {
539		*lnop = ep->c_nlines;
540		if (F_ISSET(sp, SC_TINPUT))
541			*lnop += TAILQ_LAST(&sp->tiq, _texth)->lno -
542			    TAILQ_FIRST(&sp->tiq)->lno;
543		return (0);
544	}
545
546	memset(&key, 0, sizeof(key));
547	key.data = &lno;
548	key.size = sizeof(lno);
549	memset(&data, 0, sizeof(data));
550
551	if ((sp->db_error = ep->db->cursor(ep->db, NULL, &dbcp, 0)) != 0)
552	    goto err1;
553	switch (sp->db_error = dbcp->c_get(dbcp, &key, &data, DB_LAST)) {
554        case DB_NOTFOUND:
555		*lnop = 0;
556		return (0);
557	default:
558		(void)dbcp->c_close(dbcp);
559alloc_err:
560err1:
561		msgq(sp, M_DBERR, "007|unable to get last line");
562		*lnop = 0;
563		return (1);
564        case 0:
565		;
566	}
567
568	memcpy(&lno, key.data, sizeof(lno));
569
570	if (lno != sp->c_lno) {
571	    FILE2INT(sp, data.data, data.size, wp, wlen);
572
573	    /* Fill the cache. */
574	    BINC_GOTOW(sp, sp->c_lp, sp->c_blen, wlen);
575	    MEMCPYW(sp->c_lp, wp, wlen);
576	    sp->c_lno = lno;
577	    sp->c_len = wlen;
578	}
579	ep->c_nlines = lno;
580
581	(void)dbcp->c_close(dbcp);
582
583	/* Return the value. */
584	*lnop = (F_ISSET(sp, SC_TINPUT) &&
585	    TAILQ_LAST(&sp->tiq, _texth)->lno > lno ?
586	    TAILQ_LAST(&sp->tiq, _texth)->lno : lno);
587	return (0);
588}
589
590/*
591 * db_err --
592 *	Report a line error.
593 *
594 * PUBLIC: void db_err __P((SCR *, db_recno_t));
595 */
596void
597db_err(SCR *sp, db_recno_t lno)
598{
599	msgq(sp, M_ERR,
600	    "008|Error: unable to retrieve line %lu", (u_long)lno);
601}
602
603/*
604 * scr_update --
605 *	Update all of the screens that are backed by the file that
606 *	just changed.
607 *
608 * PUBLIC: int scr_update __P((SCR *sp, db_recno_t lno,
609 * PUBLIC: 			lnop_t op, int current));
610 */
611int
612scr_update(SCR *sp, db_recno_t lno, lnop_t op, int current)
613{
614	EXF *ep;
615	SCR *tsp;
616	WIN *wp;
617
618	if (F_ISSET(sp, SC_EX))
619		return (0);
620
621	/* XXXX goes outside of window */
622	ep = sp->ep;
623	if (ep->refcnt != 1)
624		TAILQ_FOREACH(wp, &sp->gp->dq, q)
625			TAILQ_FOREACH(tsp, &wp->scrq, q)
626				if (sp != tsp && tsp->ep == ep)
627					if (vs_change(tsp, lno, op))
628						return (1);
629	return (current ? vs_change(sp, lno, op) : 0);
630}
631
632/*
633 * PUBLIC: void update_cache __P((SCR *sp, lnop_t op, db_recno_t lno));
634 */
635void
636update_cache(SCR *sp, lnop_t op, db_recno_t lno)
637{
638	SCR* scrp;
639	EXF *ep;
640
641	ep = sp->ep;
642
643	/* Flush the cache, update line count, before screen update. */
644	/* The flushing is probably not needed, since it was incorrect
645	 * for db_insert.  It might be better to adjust it, like
646	 * marks, @ and global
647	 */
648	TAILQ_FOREACH(scrp, &ep->scrq, eq)
649		switch (op) {
650		case LINE_INSERT:
651		case LINE_DELETE:
652			if (lno <= scrp->c_lno)
653				scrp->c_lno = OOBLNO;
654			break;
655		case LINE_RESET:
656			if (lno == scrp->c_lno)
657				scrp->c_lno = OOBLNO;
658			break;
659		case LINE_APPEND:
660			break;
661		}
662
663	if (ep->c_nlines != OOBLNO)
664		switch (op) {
665		case LINE_INSERT:
666			++ep->c_nlines;
667			break;
668		case LINE_DELETE:
669			--ep->c_nlines;
670			break;
671		case LINE_APPEND:
672		case LINE_RESET:
673			break;
674		}
675}
676
677/*
678 * PUBLIC: int line_insdel __P((SCR *sp, lnop_t op, db_recno_t lno));
679 */
680int
681line_insdel(SCR *sp, lnop_t op, db_recno_t lno)
682{
683	int rval;
684
685	/* Update marks, @ and global commands. */
686	rval = 0;
687	if (mark_insdel(sp, op, lno))
688		rval = 1;
689	if (ex_g_insdel(sp, op, lno))
690		rval = 1;
691
692	return rval;
693}
694
695#ifdef USE_DB4_LOGGING
696#define VI_DB_INIT_LOG	DB_INIT_LOG
697#else
698#define VI_DB_INIT_LOG	0
699#endif
700
701/*
702 * PUBLIC: int db_setup __P((SCR *, EXF *));
703 */
704int
705db_setup(SCR *sp, EXF *ep)
706{
707	char path[MAXPATHLEN];
708	int fd;
709	DB_ENV	*env;
710
711	(void)snprintf(path, sizeof(path), "%s/vi.XXXXXX", O_STR(sp, O_RECDIR));
712	if ((fd = mkstemp(path)) == -1) {
713		msgq(sp, M_SYSERR, "%s", path);
714		goto err;
715	}
716	(void)close(fd);
717	(void)unlink(path);
718	if (mkdir(path, S_IRWXU)) {
719		msgq(sp, M_SYSERR, "%s", path);
720		goto err;
721	}
722	if (db_env_create(&env, 0)) {
723		msgq(sp, M_ERR, "env_create");
724		goto err;
725	}
726#ifdef USE_DB4_LOGGING
727	if ((sp->db_error = vi_db_init_recover(env))) {
728		msgq(sp, M_DBERR, "init_recover");
729		goto err;
730	}
731	if ((sp->db_error = __vi_init_recover(env))) {
732		msgq(sp, M_DBERR, "init_recover");
733		goto err;
734	}
735#endif
736	if ((sp->db_error = db_env_open(env, path,
737	    DB_PRIVATE | DB_CREATE | DB_INIT_MPOOL | VI_DB_THREAD
738	    | VI_DB_INIT_LOG, 0)) != 0) {
739		msgq(sp, M_DBERR, "env->open");
740		goto err;
741	}
742
743	if ((ep->env_path = strdup(path)) == NULL) {
744		msgq(sp, M_SYSERR, NULL);
745		(void)rmdir(path);
746		goto err;
747	}
748	ep->env = env;
749	return 0;
750err:
751	return 1;
752}
753
754/* Round up v to the nearest power of 2 */
755static size_t round_up(size_t v)
756{
757	ssize_t old_v = v;
758
759	while (v) {
760		old_v = v;
761		v ^= v & -v;
762	}
763	return old_v << 1;
764}
765
766/*
767 * PUBLIC: int db_msg_open __P((SCR *, const char *, DB **));
768 */
769int db_msg_open(SCR *sp, const char *file, DB **dbp)
770{
771	return  (sp->db_error = db_create(dbp, 0, 0)) != 0 ||
772		(sp->db_error = (*dbp)->set_re_source(*dbp, file)) != 0 ||
773		(sp->db_error = db_open(*dbp, NULL, DB_RECNO, 0, 0)) != 0;
774}
775
776/*
777 * PUBLIC: int db_init __P((SCR *, EXF *, char *, char *, size_t, int *));
778 */
779int
780db_init(SCR *sp, EXF *ep, char *rcv_name, char *oname, size_t psize, int *open_err)
781{
782	if (db_setup(sp, ep))
783		return 1;
784
785	/* Open a db structure. */
786	if ((sp->db_error = db_create(&ep->db, 0, 0)) != 0) {
787		msgq(sp, M_DBERR, "db_create");
788		return 1;
789	}
790
791	ep->db->set_re_delim(ep->db, '\n');		/* Always set. */
792	ep->db->set_pagesize(ep->db, round_up(psize));
793	ep->db->set_flags(ep->db, DB_RENUMBER | DB_SNAPSHOT);
794	if (rcv_name == NULL)
795		ep->db->set_re_source(ep->db, oname);
796
797/*
798 * Don't let db use mmap when using fcntl for locking
799 */
800#ifdef HAVE_LOCK_FCNTL
801#define NOMMAPIFFCNTL DB_NOMMAP
802#else
803#define NOMMAPIFFCNTL 0
804#endif
805
806#define _DB_OPEN_MODE	S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH
807
808	if ((sp->db_error = db_open(ep->db, ep->rcv_path, DB_RECNO,
809	    ((rcv_name == 0) ? DB_TRUNCATE : 0) | VI_DB_THREAD | NOMMAPIFFCNTL,
810	    _DB_OPEN_MODE)) != 0) {
811		msgq_str(sp,
812		    M_DBERR, rcv_name == NULL ? oname : rcv_name, "%s");
813		/*
814		 * !!!
815		 * Historically, vi permitted users to edit files that couldn't
816		 * be read.  This isn't useful for single files from a command
817		 * line, but it's quite useful for "vi *.c", since you can skip
818		 * past files that you can't read.
819		 */
820		ep->db = NULL; /* Don't close it; it wasn't opened */
821
822		*open_err = 1;
823		return 1;
824	}
825
826	/* re_source is loaded into the database.
827	 * Close it and reopen it in the environment.
828	 */
829	if ((sp->db_error = ep->db->close(ep->db, 0))) {
830		msgq(sp, M_DBERR, "close");
831		return 1;
832	}
833	if ((sp->db_error = db_create(&ep->db, ep->env, 0)) != 0) {
834		msgq(sp, M_DBERR, "db_create 2");
835		return 1;
836	}
837	if ((sp->db_error = db_open(ep->db, ep->rcv_path, DB_RECNO,
838	    VI_DB_THREAD | NOMMAPIFFCNTL, _DB_OPEN_MODE)) != 0) {
839		msgq_str(sp,
840		    M_DBERR, ep->rcv_path, "%s");
841		return 1;
842	}
843
844	return 0;
845}
846