]> andersk Git - moira.git/blame - gdb/gdb_ugd.mss
Case-insensitive stuff.
[moira.git] / gdb / gdb_ugd.mss
CommitLineData
5580185e 1@device(PostScript)
2@make(Manual)
3@style(FontFamily "Helvetica", Size 11)
4@style(hyphenation on)
5@style(indent 0)
6@style(leftmargin +4cm)
7@style(footnotes "")
8@modify(example,Size 10, below 1cm, above 1cm, leftmargin +3, rightmargin +0)
9@define(F, FaceCode F, Size 11, TabExport)
10@modify(HD1, Below .75cm, Above 1cm, indent -1cm)
11@modify(HD1A, Below .75cm, Above 1cm)
12@modify(HD2, Below .6cm, Above 1cm, indent -1cm)
13@modify(HD3, Below .6cm, Above 1cm)
14@modify(itemize, Below .5cm, Above .6cm)
15@modify(example, Below .5cm, Above .6cm)
16@modify(float, Below .5cm, Above .6cm)
17@begin(titlepage)
18@begin(titlebox)
19@majorheading(A Guide to Using GDB)
20@heading(Noah Mendelsohn)
21
22@end(titlebox)
23Document Version: 0.4 (DRAFT)
24For use with GDB Release: 0.4
25This draft printed on: @value(Date)
26@copyrightnotice(MIT Project Athena)
27@end(titlepage)
28@Counter(ProgramNumber, Numbered <@1>, Referenced <@1>)
29@set(ProgramNumber=1)
30@Chapter(Introduction)
31
32Many of the most important computer applications involve sharing
33information among the users of a computer system.
34These applications may be simple to create if all users do their
35work on a single timesharing system, but the job is much harder in
36a @i[distributed] system, where each user has his or her own workstation.
37The purpose of GDB Global Database system is to simplify the creation
38of distributed applications in which information sharing is important.
39
40This guide is intended for prospective users of GDB who want to know
41what GDB can do for them and need a general guide to doing the
42job right.
43A complete description of GDB services and interfaces is provided in
44another document titled: "GDB C Library Reference Manual".
45Both guides are intended for readers with a good working knowledge
46of C and Unix@+[TM]@foot(@+[TM]Unix is a trademark of
47AT&T Bell Laboratories) programming.
48A short note titled: "GDB Global Databases for Project Athena" provides
49a general introduction to GDB
50for non-programmers.
51The sections below are intended to answer some of the most basic
52questions about GDB and using this guide.
53@section(What can GDB do?)
54Here is a brief list of the programming tasks that GDB facilitates:
55@begin(itemize)
56@begin(multiple)
57@b[Sharing a relational database through a network]
58
59GDB includes everything needed for a program running on one machine
60in a Berkeley Unix network to create, alter, and query the relations
61in an RTI Ingres database stored on some other machine in the network.
62Programs running on several machines may access the same data simultaneously,
63and a single program may use more than one database at a time.
64The programs may easily be ported across machine architectures, RT/PC
65to Vax for example, and programs running on different machine types
66may share a common database.
67@end(multiple)
68
69@begin(multiple)
70@b[Writing network servers and their clients]
71
72GDB handles most of the bookkeeping and error recovery needed to build
73servers and clients in a Berkeley Unix environment. A completely
74functional demonstration server capable of supporting multiple clients
75with reasonable error detection has been written in about 20 lines
76of C code using the services of GDB (page @pageref[tfsr]).
77Clients running on various types of machine may easily access common
78servers, with GDB handling the necessary data conversions automatically.
79@end(multiple)
80
81@begin(multiple)
82@b[Single Process Unix Servers]
83
84It is customary when writing servers under Unix to fork a separate
85server process to handle each client.
86In addition to this traditional model, GDB provides a rich set
87of asynchronous communication services which facilitate the
88creation of servers in which a single process supports all clients.
89This model is particularly appropriate to the implementation
90of such high performance applications as network games.
91@end(multiple)
92
93@begin(multiple)
94@b[Peer-to-peer communication]
95
96Some communicating applications, like the Berkeley Unix @f[talk] program,
97@index(talk)
98don't fit naturally into a server/client model. GDB also provides
99services for managing connections between @i[peer] programs, of which
100neither is viewed as master or slave.
101@end(multiple)
102@end(itemize)
103
104@section(Which Chapters in this Guide Should I Read?)
105@Index(Chapters, guide to)
106
107Although GDB has a rich set of features for elaborate
108asynchronous programming, many useful applications can be built
109with just the simplest GDB tools. This guide is intended to be read
110selectively. The following are some hints on what to read, depending
111on the job you are trying to do:
112
113@begin(itemize)
114Everyone who uses GDB should read the rest of this "Introduction",
115and the chapter titled "Managing Structured Data".
116
117If you wish to use GDB to access a remote Ingres database, then the
118only other chapter you have to read is "Creating and Using Relational
119Databases with GDB". If you're interested in doing database accesses
120@i[asynchronously], allowing you to overlap your access to several
121databases or to keep control of the local terminal while a query is
122executing, then you should also read the chapter titled "Synchronous
123and Asynchronous Operations".
124
125If you are planning to write your own servers, clients, or other
126communicating programs, then you can skip the chapter on relational
127databases, but you should read instead the chapter "Creating
128Servers, Clients, and Other Communicating Programs". This gives
129all the information you need to use the basic communication capabilities
130of GDB, which will be adequate for the majority of applications.
131Asynchronous communication techniques are described in the chapter
132"Synchronous and Asynchronous Operations".
133@end(itemize)
134
135Three other chapters provide additional material which may be useful on
136occasion. "Hints and Tricks" has some suggestions which may be helpful
137if you can't figure out how to make GDB do exactly what you want.
138"Bugs" lists some of the known shortcomings in current implementations.
139If you're having trouble, this is one of the places to look.
140"How GDB Works" gives a general overview of GDB's internal
141structure, information which should not be needed in writing an
142application, but which may be of interest to serious users. The
143sample programs in the appendices are referenced in the appropriate
144chapters.
145
146@section(What is needed to run GDB?)
147The services of GDB are accessed through a C library.
148You will have to insure that the appropriate C include files are available
149on your system, and that the gdb library is available when you link your
150application. Your system administrator can take care of these things
151for you.
152@i[Note to early users: You may receive the pieces of GDB in slightly
153different form. Documentation supplied with the distribution should
154explain what to do.]
155
156@begin(group)
157@blankspace(1 line)
158Every C main program
159that uses GDB should include the following:
160
161@begin(example)
162#include <stdio.h>
163#include "gdb.h"
164
165int
166main()
167{
168 gdb_init();
169 /*
170 * Once gdb_init has been called, the services of gdb are
171 * available. gdb_init may be called only once.
172 */
173}
174@end(example)
175@end(group)
176
177Other source files should @f[#include "gdb.h"], but should @i[not]
178@index(gdb.h)
179invoke @f[gdb_init].
180@index(gdb_init)
181
182If you are using GDB to access an Ingres database, then there are
183several other things you must do:
184
185@begin(itemize)
186@begin(multiple)
187Make sure RTI Ingres is installed at the server site where the data
188@index(RTI Ingres)
189@index(Ingres)
190is to be stored.
191@end(multiple)
192
193@begin(multiple)
194Make sure that there is an entry in the file named @f[/etc/services]
195@index(/etc/services)
196at both server and client sites for the service named gdb_db@index(gdb_db).
197The entries at the server and client should be identical.
198Talk to your system administrator if this is not the case.
199@i[Note: as of this writing, GDB does not check @f[/etc/services] when
200accessing Ingres, but soon it will!]
201@end(multiple)
202
203@begin(multiple)
204Make sure that the @f[dbserv] program supplied with GDB
205@index(dbserv)
206is started at the server site.
207@end(multiple)
208
209@end(itemize)
210
211Once these steps have been followed, the full services of the Ingres
212database are available to GDB clients throughout the network. In
213future releases of GDB, the Kerberos Authentication
214Service@index(Kerberos) will be used to verify the identity of clients
215and to provide some options for access control. In the meantime, keep
216in mind that any GDB user on the internet@index(Internet, access
217rights from)
218effectively inherits the access rights of the userid under which the
219database server is running.
220
221@Chapter(Managing Structured Data)
222@label(structure)
223
224This chapter presents a brief overview of the services that GDB
225provides for managing structured data.
226Although the discussion in this chapter uses relational database
227examples, the same GDB features are used to implement servers and
228clients of all kinds.
229
230When Ingres is used to retrieve data from a relational database, the
231result of the query is known as a @i[relation]@index(relation). Each
232relation consists of 0 or more @i[tuples]@index(tuple), and the tuples
233themselves consist of @i[fields]@index(field). Informally, one may
234think of the relation as a table containing one row for each "match"
235found in the database. The rows are called tuples, and each such
236tuple contains the fields which were requested in the query. For
237example, a query to a database containing information on military
238personnel might be:
239
240@begin(example)
241@center[Get the name, rank, and serial number of all personal with over
2425 years of service]
243@end(example)
244
245If there were two such people, then the resulting relation would contain
246two tuples, each with three fields. For example:
247
248@begin(example)
249 Name Rank Serial
250 ----------------------
251 Mary 123 876543
252 John 121 875432
253@end(example)
254
255When GDB is used to perform a query, then some standard
256representation must be used to hold the resulting relation.
257Furthermore, GDB must know quite a bit about the @i[types] of the
258fields, whether they are @i[integer] or @i[real] for example, so that
259it can do necessary conversions when transmitting between
260incompatible machines. Since C itself provides no convenient
261way of doing this, GDB uses the following conventions:
262
263GDB has its own notion of @i[data object]@index(Data object, GDB),
264which is slightly different from a C variable or structure. A GDB
265data object may be as simple as a single integer or as complex as an
266entire relation. Each GDB object has a @i[type]@Index(Typing of GDB
267objects), which tells GDB what kind of object it is. Though some of
268the types supported by GDB are similar to those provided by the C
269language, GDB has its own typing mechanism which is intended to
270support the transmission and data conversion services that GDB must
271provide.
272
273Every GDB object has one of the following types:
274
275@begin(itemize)
276@begin(multiple)
277INTEGER_T
278@index[INTEGER_T]
279
280Usually the same as a @i[long] in C.
281@end(multiple)
282
283@begin(multiple)
284REAL_T
285@index[REAL_T]
286
287Usually the same as a @i[double] in C.
288@end(multiple)
289
290@begin(multiple)
291STRING_T
292@index[STRING_T]
293
294For various reasons, GDB uses counted byte strings. The actual implementation
295of a STRING_T is:
296
297@begin(example)
298 struct {
299 char *ptr; /* pointer to first*/
300 /* byte of data, or*/
301 /* NULL if none */
302 int length; /* number of bytes */
303 /* allocated */
304 }
305@end(example)
306
307Though these strings are commonly used to hold C language null
308terminated strings, that is not required. Any null(s) must be
309included in the length. GDB includes library services for creating
310and manipulating STRING_T data (page @pageref[string_data_in_gdb]).
311Future releases of GDB may include a C_STRING_T type, which would
312correspond directly to a C null terminated string. @end(multiple)
313
314@begin(multiple)
315DATE_T
316@index[DATE_T]
317
318Used to contain a date field retrieved from Ingres. This is implemented
319as a 25 byte character array. See Ingres documentation for conventions.
320@end(multiple)
321
322@begin(multiple)
323TUPLE_DESCRIPTOR_T
324@index[TUPLE_DESCRIPTOR_T]
325
326Every tuple and relation is described by a tuple descriptor. The tuple
327descriptor contains the names of the fields, their position in the tuple,
328and the types of the fields. Tuple descriptors are themselves GDB objects.
329@end(multiple)
330
331@begin(multiple)
332TUPLE_T
333@index[TUPLE_T]
334
335Refers to an entire tuple, including its descriptor. An item of
336type TUPLE_T is self-describing. GDB can tell by inspection what
337its structure is, as well as the names, types and contents of its fields.
338@end(multiple)
339
340@begin(multiple)
341RELATION_T
342@index[RELATION_T]
343
344Refers to an entire relation, all its tuples and their descriptors. An item of
345
346type RELATION_T is also self-describing.
347@end(multiple)
348
349@begin(multiple)
350TUPLE_DATA_T
351@index[TUPLE_DATA_T]
352
353This is for internal use of GDB. It refers to just the data part of
354a tuple, when the description can be inferred.
355@end(multiple)
356
357@begin(multiple)
358User Defined Types
359@Index[User defined types]
360
361GDB allows users to define their own types. This can be useful for
362sophisticated applications which want GDB to take care of transmission
363and data conversion for unusual data structures. Few applications
364will actually require this flexibility, which is explained briefly under
365"Hints and Tricks".
366@end(multiple)
367@end(itemize)
368
369Why go to all this trouble, and what does it mean to say that things
370as simple as INTEGER_T and as complex as RELATION_T are both just types?
371As it turns out, this convention is the basis of a very powerful scheme
372for transmitting structured data from one computer to another. GDB
373includes a service called @f[send_object] which is used to transmit
374@index(send_object)
375information through a network, and a matching service called
376@f[receive_object].
377@index(receive_object)
378Because of the uniform typing scheme outlined above, the same routine
379used to send a single integer may be used to send an entire relation.
380Furthermore, the typing information is just what GDB needs to do efficient
381data conversions when two incompatible machines are communicating.
382
383There is one more point of confusion which should be clarified. As
384@Index(Types, GDB vs. C)
385shown above, the system supplied GDB types have names like INTEGER_T,
386STRING_T, and so on.
387The confusion arises because these are @i[not] C language typedefs,
388they are preprocessor constants used as indices into GDB's type
389tables. For each GDB type there is usually a corresponding C language
390type. For example, INTEGER_T is GDB's term for what C calls a
391@f[long]. Table @ref[GDBTypes] shows the correspondence between GDB types
392and C types:
393
394@begin(table)
395@caption(GDB Types and C Types)
396@tag[GDBTypes]
397@tabset(.75in, 3.5in)
398
399@u[@\GDB Type@\C Language Type]
400
401@\INTEGER_T@\long
402
403@\REAL_T@\double
404
405@\STRING_T@\STRING
406
407@\DATE_T@\char xx[25]
408
409@\TUPLE_DESCRIPTOR_T@\TUPLE_DESCRIPTOR
410
411@\TUPLE_T@\TUPLE
412
413@\RELATION_T@\RELATION
414
415@\TUPLE_DATA@\TUPLE->
416@\@\(i.e. a de-referenced tuple)
417@end(table)
418
419All of the GDB type identifiers, as well as the C language types with
420uppercase names are defined for you in @f[gdb.h].
421@index(gdb.h)
422
423When should you use the GDB type and when should you use the C type?
424In general, the C type is used whenever you are declaring a variable
425to C, or casting @index[casting pointers] a pointer to a new type.
426For example:
427
428@begin(example)
429int
430main()
431{
432 TUPLE t; /* C declaration */
433 /* for a TUPLE */
434 RELATION r; /* C declaration */
435 /* for a RELATION */
436 STRING s; /* C declaration */
437 /* for a counted */
438 /* byte string */
439
440 string_alloc(&s,25); /* allocate a 25 */
441 /* character string */
442}
443@end(example)
444
445The GDB types are used when you are telling @i[GDB] about the type
446of data it's going to manipulate:
447
448@begin(example)
449int
450main()
451{
452 STRING s; /* C declaration */
453 /* for a counted */
454 /* byte string */
455 CONNECTION c;
456
457 /*
458 * send the data in STRING s on connection c. The
459 * STRING_T indication below tells GDB what kind of
460 * object is being sent.
461 */
462 send_object(c, &s, STRING_T);
463}
464@end(example)
465
466@section(Building and Using Relations)
467
468@index[Relations, creating] Each time you do an Ingres query, the
469results are added to the local relation that you supply. That means
470that you will usually want to create an empty relation before doing a
471query, then pass that to the @f[db_query] routine @index(db_query)
472@index(querying Ingres databases)
473which will fill it in with the results of the query. Creating the
474relation is done in two steps: (1) you create a
475TUPLE_DESCRIPTOR@index[tuple descriptor]@index[TUPLE_DESCRIPTOR]
476which contains information about the names and types of the fields
477which will be in the tuples of the relation and (2) using the
478descriptor, you create the empty relation. Note that the same
479descriptor may be used repeatedly to create many relations. Here is
480an example with one descriptor and two relations:
481
482@begin(example)
483int
484main()
485{
486 char *fld_names[] = {"name", "rank", "serial"};
487 FIELD_TYPE fld_types[] = {STRING_T, INTEGER_T, INTEGER_T};
488
489 TUPLE_DESCRIPTOR desc;
490 RELATION old_timers;
491 RELATION new_recruits;
492
493 desc = create_tuple_descriptor(3, fld_names, fld_types);
494
495 old_timers = create_relation(desc);
496 new_recruits = create_relation(desc);
497
498}
499@end(example)
500
501GDB provides many macros and procedures for manipulating relations,
502tuples, and fields. Let's assume that the program goes on to do two
503successful queries, one for old_timers and one for new_recruits. The
504declarations and code in Program #@ref(ProgramNumber) might be added
505to the example to print the results of the new recruits query.
506
507@begin(float)
508@index(Fields, accessing)
509@index(Relations, tuples in)
510@index(Tuples in relations)
511
512@center(PROGRAM #@ref(ProgramNumber))
513@set(ProgramNumber=+1)
514@begin(example)
515TUPLE t;
516STRING *name;
517int *rank;
518int *serial;
519/*
520 * Define symbolic names for the positions of the fields
521 * in the tuples. There are other ways to do this,
522 * but this does work:
523 */
524#define NAME 0
525#define RANK 1
526#define SERIAL 2
527/*
528 * the following code would go after the query
529 *
530 * the loop is executed once for each new
531 * recruit returned by the query
532 */
533 for(t=FIRST_TUPLE_IN_RELATION(new_recruits);
534 t != NULL;
535 t = NEXT_TUPLE_IN_RELATION(new_recruits, t)) {
536 /*
537 * Get a pointer to each field in the tuple
538 */
539 name = (STRING *)FIELD_FROM_TUPLE(t, NAME);
540 rank = (int *)FIELD_FROM_TUPLE(t, RANK);
541 serial = (int *)FIELD_FROM_TUPLE(t, SERIAL);
542 /*
543 * print the fields
544 */
545 printf("name=%s rank=%d serial=%d\n",
546 STRING_DATA(*name), *rank, *serial);
547 }
548/*
549 * return the memory used to hold the new_recruits relation
550 */
551delete_relation(new_recruits);
552@end(example)
553@end(float)
554
555The example illustrates several important points. Variables
556representing structured objects
557like TUPLE, TUPLE_DESCRIPTOR and RELATION are actually pointers.
558@index(Relations, pointer representation of)
559@index(Tuples, pointer representation of)
560@index(Relations, tuples in)
561@index(Tuples in relations)
562Because TUPLE is a pointer type, TUPLE variables may be used
563as cursors in a relation. For example, you might declare a TUPLE
564variable called @f[ranking_recruit] and set it in the loop above to
565the tuple of the recruit with the highest rank.
566Lots of TUPLE variables may point into
567the same relation, or even to the same tuple, but like any other
568pointers, they become invalid if the corresponding structures are
569deleted. The C value NULL is used to represent non-existent TUPLES,
570RELATIONS, and descriptors.
571
572As shown in the program, the @f[FIELD_FROM_TUPLE] macro is used to find
573@index(Fields, accessing)
574@index(FIELD_FROM_TUPLE)
575a field within a tuple. @f[FIELD_FROM_TUPLE] returns a
576@i[pointer] to the requested field, and it is up to you to cast the
577pointer according to the type of field being retrieved. In the
578program, @f(name) is of type STRING_T, so the
579cast @f[(STRING *)] is used. Pointer casting is a feature of
580the C language which is explained in Kernighan and Ritchie and other C
581programming guides.
582
583Note that @f[FIELD_FROM_TUPLE] refers to fields by their
584position in the tuple, not by name. This was done for efficiency, as
585@f[FIELD_FROM_TUPLE] is likely to be called frequently by GDB
586applications. The argument supplied may be a variable,
587but it is your responsibility to correctly interpret the type of
588the resulting pointer. GDB can also help you find fields by symbolic
589name, but that takes longer. The @f[field_index]
590@Index(Fields, finding by name)
591function takes
592as its argument a tuple descriptor (@i[not] a tuple) and the string
593name of a field; it returns the field number of the named field. If
594you want to pull fields by name from several similar tuples, the
595efficient way is to find the index once using @f[field_index],
596then use that repeatedly in calls to @f[FIELD_FROM_TUPLE].
597
598A brief guide to the functions and macros provided for manipulating structured
599data is provided in Appendix I.
600
601@section(STRING Data in GDB)
602@label(string_data_in_gdb)
603
604@index(string)
605@index(STRING_T)
606As noted previously, GDB represents string data as counted fields of
607bytes. If you create a tuple with a field of type STRING_T, then the
608space actually allocated in the tuple is just that needed to hold the
609location and length of the string data, not the space for the data
610itself. @f[gdb.h] @index[gdb.h] contains the following definition,
611which may be used when referring to STRING fields, or to create your
612own variables of type STRING.
613
614@begin(example)
615@index[FIELD_FROM_TUPLE]
616@index[string_alloc]
617@index[MAX_STRING_SIZE]
618@index[STRING_DATA]
619 typedef struct str_dat {
620 char *ptr; /* pointer to first */
621 /* byte of data, or */
622 /* NULL if none */
623 int length; /* number of bytes of*/
624 /* data allocated */
625 } STRING;
626@end(example)
627
628If you have such a tuple and wish to initialize the string field to have
629space for up to 100 bytes of data, then the code in Program
630#@ref(ProgramNumber) might be used.
631
632@begin(float)
633
634@center(PROGRAM #@ref(ProgramNumber))
635@set(ProgramNumber=+1)
636@begin(example)
637 TUPLE t;
638 #define STRFIELD 3 /* index of the string*/
639 /* field in the tuple */
640 STRING *sp; /* pointer to the field*/
641
642 /*
643 * Get a pointer to the string field in the tuple
644 */
645 sp = (STRING *)FIELD_FROM_TUPLE(t,STRFIELD);
646@index[FIELD_FROM_TUPLE]
647 /*
648 * Allocate space for 100 bytes
649 */
650 string_alloc(sp, 100);
651@index[string_alloc]
652 /*
653 * Copy some text into the new buffer
654 */
655 strcpy(STRING_DATA(*sp), "Hi there");
656@index[STRING_DATA]
657 /*
658 * Note, at this point:
659 *
660 * MAX_STRING_SIZE(*sp) == 100
661 *
662 * strlen(STRING_DATA(*sp)) == 9
663 */
664@end(example)
665@end(float)
666
667A call to @f[string_free] would free all 100 bytes of data. Note that
668@index(string_free)
669a routine named @f[null_tuple_strings] frees all the strings in a given
670@index(null_tuple_strings)
671tuple.
672
673If you're writing your own servers and clients, then STRING variables
674are a convenient way of sending uninterpreted byte strings from one
675machine to another, as shown in Program #@ref(ProgramNumber).
676
677@begin(float)
678
679@center(PROGRAM #@ref(ProgramNumber))
680@set(ProgramNumber=+1)
681@begin(example)
682 CONNECTION con;
683 char buffer[500];
684 STRING s;
685
686 /*
687 * Set up string descriptor s as required by gdb
688 */
689
690 STRING_DATA(s) = buffer; /* copy the pointer*/
691
692 /*
693 * For demonstration purposes, put some data into the
694 * buffer.
695 */
696
697 strcpy(buffer, "Some string");
698 MAX_STRING_SIZE(s) = strlen(buffer)+1;
699 /* include space for */
700 /* the null */
701
702 /*
703 * send the object through the connection.
704 * we assume that the connection is already
705 * started
706 */
707 send_object(con, &s, STRING_T);
708@end(example)
709@end(float)
710
711As of this writing, the STRING_T type is the only means GDB provides
712for manipulating byte strings. Future releases may also support a
713C_STRING_T, which would more closely match C's convention of null
714terminated strings. The current implementation was chosen for its
715generality and efficiency. STRING_T may be used to hold any array of
716bytes, including those with embedded null characters, and for long
717strings, STRING_T avoids the overhead of searching the string to
718compute its length.
719
720@Chapter(Creating and Using Relational Databases with GDB)
721
722@index[Relational databases]
723GDB may be used to obtain the full services of an RTI Ingres
724@index[RTI Ingres]
725@index[Ingres]
726relational database from a program running at any node in a Berkeley
727Unix network. In addition to most of the services provided by RTI
728Ingres version 3, GDB supports:
729
730@begin(itemize)
731Remote access from any machine in a network.
732
733Parallel access to multiple databases, possibly but not necessarily at
734multiple sites.
735
736Transparent access from incompatible machines (e.g. RT/PC to VAX.)
737@end(itemize)
738
739In fact, GDB is designed to be used with a variety of database
740products, but RTI Ingres is the only one for which an implementation
741exists at present. Nevertheless, every attempt has been made to
742isolate the Ingres dependencies in GDB.
743GDB's current support of relational databases is based on the Ingres QUEL
744query language, which is documented in the appropriate manuals from
745RTI. It is @i[essential] that you familiarize yourself with QUEL
746before attempting to use GDB to manipulate relational databases. A
747knowledge of QUEL is presumed in the sections which follow.
748
749@section(Accessing Databases)
750
751The general procedure for using relational databases in GDB is:
752
753@begin(itemize)
754Use @f[access_db] to initiate access to the database(s) you want to
755@index(access_db)
756use. You specify the name of the database and the host in the network
757which stores it, and GDB sets up the appropriate connection to the
758database server.
759
760Use @f[perform_db_operation] and @f[db_query] to manipulate or query
761@index(db_query)
762@index(perform_db_operation)
763the databases.
764
765Use @f[terminate_db] to sever the connection to the database server.
766@index(terminate_db)
767It is also acceptable for your program to exit without terminating its
768databases, as
769the server will notice that the connection has been severed.
770@end(itemize)
771
772Because some programs require access to several databases at once, GDB
773uses DATABASE@index[DATABASE] variables to keep track of the various
774databases which are being used:
775
776@begin(example)
777int
778main()
779{
780 DATABASE personnel, inventory;
781
782 personnel = access_db("people_data@@host1");
783 inventory = access_db("stuff_data@@host2")
784 /*
785 * Both databases are now available. Either one
786 * may be queried or manipulated, or both may be used
787 * in parallel.
788 */
789}
790@end(example)
791
792Once an attempt is made to access a database, the status of the
793corresponding database connection may be checked by using the
794DB_STATUS@index[DB_STATUS] macro. The values of DB_STATUS are shown in
795table
796@ref(DB_STATUS).
797
798@begin(table)
799@caption(Database Status Values)
800@tag(DB_STATUS)
801@tabset(.75in, 2.5in)
802
803@\DB_OPEN@index[DB_OPEN]@\The connection to the database
804@\@\appears to be intact. Operations
805@\@\on the database may be attempted.
806
807@\DB_CLOSED@index[DB_CLOSED]@\The connection to the database
808@\@\has been lost. @f[terminate_db] is the
809@index(terminate_db)
810@\@\only operation which will be accepted.
811@end(table)
812
813There is a distinction between a database which is @f[DB_CLOSED] and
814@index(DB_CLOSED) one which has been explicitly terminated.
815@f[terminate_db] allows GDB @index(terminate_db) to clean up the data
816structures which had been used to control access to the database. It
817sets the supplied database variable to NULL. @f[DB_STATUS] should not
818be used on a database which has been @index(DB_STATUS) explicitly
819terminated; it is intended for checking the status of a database which
820is believed to be accessible. @section(Performing Operations on
821Databases) With the exception of queries, all Ingres QUEL@index[QUEL]
822operations may be performed using the GDB @f[perform_db_operation]
823function. @index(perform_db_operation) Program #@ref(ProgramNumber)
824accesses the database named @f[personnel_data] at site @f[host1],
825creates an empty table named @f[new_recruits], and puts three entries
826in the new table.
827
828@begin(float)
829
830@center(PROGRAM #@ref(ProgramNumber))
831@set(ProgramNumber=+1)
832@begin(example)
833int
834main()
835{
836 DATABASE personnel;
837 char *quel_command;
838 int retcode;
839 /*
840 * Access the database and check for errors
841 */
842 access_db("personnel@@host1", &personnel);
843 if (DB_STATUS(personnel) != DB_OPEN) {
844 fprintf(stderr,"Could not access database\n");
845 exit(4);
846 }
847 /*
848 * Create the new table by sending the appropriate QUEL
849 * command.
850 */
851 quel_command=
852 "create recruits (name=c8, rank = i4, serial=i4)");
853 retcode = perform_db_operation(personnel,quel_command);
854 if (retcode != OP_SUCCESS) {
855 fprintf(stderr,"Could not create table.\n");
856 exit(4);
857 }
858 /*
859 * Add three rows to the table
860 */
861 quel_command=
862"append to recruits (name=\"Mary\", rank = 123, serial=876543)";
863 retcode = perform_db_operation(personnel,quel_command);
864 if (retcode != OP_SUCCESS) {
865 fprintf(stderr,"Could not append\n");
866 exit(8);
867 }
868 quel_command=
869"append to recruits (name=\"John\", rank = 121, serial=875432)";
870 retcode = perform_db_operation(personnel,quel_command);
871 if (retcode != OP_SUCCESS) {
872 fprintf(stderr,"Could not append\n");
873 exit(8);
874 }
875 quel_command=
876"append to recruits (name=\"Noah\", rank = 1, serial=123)";
877 retcode = perform_db_operation(personnel,quel_command);
878 if (retcode != OP_SUCCESS) {
879 fprintf(stderr,"Could not append\n");
880 exit(8);
881 }
882 /*
883 * Sever the connection to the database. This is
884 * optional.
885 */
886 terminate_db(&personnel);
887}
888@end(example)
889@end(float)
890
891It is a complete example, with all necessary error recovery. The
892return code provided by @f[perform_db_operation] is the Ingres error
893@index(perform_db_operation)
894@index(Ingres error)
895@index(Error, Ingres)
896number for the operation attempted, or else the special reserved value
897@f[OP_CANCELLED]. The latter indicates that GDB lost its connection
898@index(OP_CANCELLED)
899to the server either just before or just after the operation was
900attempted. There is no way to tell whether the operation took effect
901before the connection was lost. Subsequent operations on the database
902are unlikely to work unless another @f[access_db] is done.
903@index(access_db)
904
905Note that @i[any] QUEL@index[QUEL commands] command, with the
906exception of a retrieve, may be done using @f[perform_db_operation].
907All clients are considered to @index(perform_db_operation) have the
908same access and update rights as the userid under which the @f[dbserv]
909program is running. @index(dbserv)@index(Internet, access
910rights from)@Index(Access rights)
911
912Hint: the @f[sprintf] function is a very useful means of putting
913@index(sprintf)
914variable information into command strings. Just use @f[sprintf] to
915format the QUEL command in a C character array, then pass that to
916@f[perform_db_operation] for execution. @f[sprintf] is found in
917the standard Unix C library. Try @f[man sprintf] if you don't know
918how to use it.
919@section(Performing Database Queries)
920
921@index[Retrieval from relational database]
922@index[Querying relational databases]
923Retrieves are different from most other QUEL commands because they
924return query result data in addition to the usual return code. For this
925reason, GDB provides a special @f[db_query] function which is used to
926@index(db_query)
927do information retrieval from an Ingres database into a GDB relation.
928Techniques for building an empty relation and for getting at the
929fields of a result were discussed in Chapter @ref(structure). All
930that remains is to explain how the query itself is formulated and sent
931to the server.
932
933@begin(multiple) The format of a GDB retrieve request is exactly the
934same as the corresponding QUEL@index[QUEL] retrieve @i[except that the
935target of each retrieve is specified differently]. In QUEL, the
936command:
937
938@begin(example)
939retrieve (name=recruits.name, rank=recruits.rank,
940 serial=recruits.serial)
941 where recruits.rank >10
942@end(example)
943
944would result in a table with three columns named @f[name, rank] and
945@f[serial]. If we assume that a null GDB relation @f[result] has been created
946with fields named @f[name, rank] and
947@f[serial], then the following call to @f[db_query] would accomplish a
948similar query:
949
950@begin(example)
951db_query(personnel, result,
952 "(>*name*<=recruits.name, >*rank*<=recruits.rank,
953 >*serial*<=recruits.serial)
954 where recruits.rank >10");
955@end(example)
956
957Here are the general rules for converting a QUEL query into a GDB
958query:
959@end(multiple)
960
961@begin(itemize)
962Create a GDB relation with fields suitable for holding the result.
963The types of the fields must match the data to be retrieved.
964Extra fields are OK, they will be set to null values in the retrieved
965tuples. You may find the extra fields useful for various purposes in
966your program.
967
968Prepare a C character string which specifying the query to be
969performed. The string has exactly the same form as the
970arguments to a QUEL retrieve, except that @i[each target will be the
971name of a field in the relation, bracketed by >*...*<]. All the usual
972syntactic rules governing QUEL retrieves apply. In particular,
973remember the parenthesis which are required around the target list.
974The verb @i[retrieve] should @i[not] be specified at the beginning of
975the string.
976
977Use @f[db_query] to perform the query.
978@index(db_query)
979@end(itemize)
980
981GDB sends the query request to the remote host and executes the query
982there. Return codes are handled in the same manner as for
983@index(Return codes, Ingres)
984@index(Ingres error)
985@index(Error, Ingres)
986@f[perform_db_operation]. In the case where no errors are found,
987tuples resulting from the query are appended to the supplied relation.
988If the server is running on a different type of machine than your
989client program, GDB does any necessary data conversions to local
990representation for you.
991It is quite possible to get a return code of OP_SUCCESS with no tuples
992added to the relation. This indicates that Ingres had no trouble
993executing the query, but found no data matching your retrieval
994criteria.
995
996You may use @f[perform_db_operation] to establish range names which
997@index(perform_db_operation)
998may then be used in your query. Range names are private to each user
999of the database, and to each connection to the database.
1000
1001Program #@ref(ProgramNumber) is a copy of the sample program from
1002Chapter @ref(structure), fleshed out to show the actual retrieval.
1003For brevity, no error checking is done in this example. In practice,
1004the return code from each GDB function should be checked.
1005
1006@begin(float)
1007
1008@center(PROGRAM #@ref(ProgramNumber))
1009@set(ProgramNumber=+1)
1010@begin(example)
1011int
1012main()
1013{
1014 DATABASE personnel;
1015
1016 char *fld_names[] = {"name", "rank", "serial"};
1017 FIELD_TYPE fld_types[] = {STRING_T, INTEGER_T, INTEGER_T};
1018#define NAME 0
1019#define RANK 1
1020#define SERIAL 2
1021
1022 TUPLE_DESCRIPTOR desc;
1023 RELATION new_recruits;
1024 TUPLE t;
1025 STRING *name;
1026 int *rank;
1027 int *serial;
1028
1029 /*
1030 * Access the database
1031 */
1032 access_db("personnel@@host1", &personnel);
1033
1034 /*
1035 * Create a null relation to hold the results
1036 */
1037 desc = create_tuple_descriptor(3, fld_names, fld_types);
1038 new_recruits = create_relation(desc);
1039
1040 /*
1041 * Do the query
1042 */
1043 db_query(personnel, new_recruits,
1044 "(>*name*<=recruits.name, >*rank*<=recruits.rank,
1045 >*serial*<=recruits.serial)
1046 where recruits.rank >10");
1047 /*
1048 * print the results
1049 */
1050 for(t=FIRST_TUPLE_IN_RELATION(new_recruits);
1051 t != NULL;
1052 t = NEXT_TUPLE_IN_RELATION(new_recruits, t)) {
1053 /*
1054 * Get a pointer to each field in the tuple
1055 */
1056 name = (STRING *)FIELD_FROM_TUPLE(t, NAME);
1057 rank = (int *)FIELD_FROM_TUPLE(t, RANK);
1058 serial = (int *)FIELD_FROM_TUPLE(t, SERIAL);
1059 /*
1060 * print the fields
1061 */
1062 printf("name=%s rank=%d serial=%d\n",
1063 STRING_DATA(*name), *rank, *serial);
1064 }
1065}
1066@end(example)
1067@end(float)
1068
1069
1070@Chapter(Creating Servers, Clients, and Other Communicating Programs)
1071@Index(Communicating programs, writing)
1072
1073One of the main purposes of GDB is to facilitate the programming of
1074servers, clients, and other communicating programs. Many useful
1075programs can be created in just a few lines of code, but GDB also
1076allows you to write very complex asynchronous servers which support
1077many clients from a single Unix process. This chapter outlines the various
1078techniques which may be used for writing communicating programs in
1079GDB.
1080
1081@section(Connections)
1082
1083All communication in GDB is done using connections. The state of
1084each connection is kept in a variable of type @f[CONNECTION], or more
1085@index(CONNECTION)
1086specifically, in a structure to which the connection variable points.
1087GDB has several functions for initiating and terminating connections.
1088They are implemented using Berkeley Unix socket facilities, but
1089are intended to be much easier to use. There are several different
1090ways to start connections, depending mainly on whether you are writing
1091a server, a client, or sets of peers. These are described in sections
1092below. Once successfully started, all
1093connections are full duplex, reliable, ordered data paths on which GDB
1094objects may be sent and received.
1095
1096Once it is started, each connection has a status which may be
1097determined using the @f[connection_status] macro. Values of concern
1098@index(connection_status)
1099to users are shown in table @ref(ConnectionStatus).
1100
1101@begin(table)
1102@caption(Connection Status Values)
1103@tag(ConnectionStatus)
1104@tabset(.75in, 2.5in)
1105
1106@\CON_UP@index[CON_UP]@\Connection is operational.
1107@\@\Data transmission may be attempted.
1108
1109@\CON_STOPPING@index[CON_STOPPING]@\Connection has failed.
1110
1111@\@\User may check the @f[connection_errno]
1112@\@\@index[connection_errno] for cause, or may call
1113@\@\@f[connection_perror]@index[connection_perror] to print
1114@\@\message. In any case, user must issue a @f[sever_connection]@index[sever_connection]
1115@\@\in order for the connection to be re-used by gdb.
1116
1117@\CON_STOPPED@index[CON_STOPPED]@\Connection has been
1118@\@\severed by the user.
1119@end(table)
1120
1121Note that the routines which start connections may return NULL values
1122in case of failure or they may return a connection descriptor in the
1123CON_STOPPING state.
1124When a connection enters the CON_STOPPING state, the only operations which
1125users may perform are to check the @f[connection_status] and the @f[connection_errno], or to sever the connection.
1126
1127If any connection, including a listening connection, fails due to an
1128error reported by Unix on a system call, GDB records the corresponding
1129Unix @f[errno]@index[errno] in the connection descriptor, and puts the
1130connection in the CON_STOPPING state. All pending operations on the
1131connection are cancelled. This errno value may be queried with the
1132@f[connection_errno] macro.
1133
1134Users may terminate connections at any time from
1135either end by using the @f[sever_connection] function. All operations
1136queued at either @index(sever_connection) end are cancelled and the
1137communication path is closed. Connection @i[variables] which have
1138been severed may be re-used to start other connections. A connection
1139which has entered the @f[CON_STOPPING] @index(CON_STOPPING) state
1140should be severed before its connection variable is re-used.
1141
1142
1143@section(Sending and Receiving Data)
1144
1145GDB provides a @f[send_object] function which may be used to send any
1146@index(send_object)
1147GDB object on a connection, and a matching @f[receive_object]
1148@index(receive_object)
1149function. Objects are sent in order on each connection. Calls to
1150@f[receive_object] should match one for one with calls to
1151@f[send_object], and the types specified on the receives must
1152match those on the sends. @i[Failure to do this will result in
1153unpredictable program failures including segmentation faults, hangs,
1154prematurely severed connections, etc.]
1155
1156Chapter @ref(structure) describes GDB's typing scheme.
1157@f[send_object] is a @i[polymorphic] routine which can transmit any
1158type of GDB object. Each object is automatically converted to the
1159local representation of the receiving machine. Program
1160#@ref(ProgramNumber) is a simple example which starts a connection to
1161a server, sends a single integer to the server, and gets back a
1162relation.
1163
1164@begin(float)
1165
1166@center(PROGRAM #@ref(ProgramNumber))
1167@set(ProgramNumber=+1)
1168@begin(example)
1169int
1170main{
1171 CONNECTION server;
1172 int i = ???somevalue???;
1173 RELATION result;
1174 int rc;
1175
1176 server = start_server_connection("serverid", "");
1177
1178 if (server == NULL) {
1179 fprintf(stderr, "Failed to connect to server\n")
1180 exit(4);
1181 }
1182
1183 rc = send_object(server, &i, INTEGER_T);
1184 if (rc == OP_CANCELLED) {
1185 fprintf(stderr, "Could not send to server.\n")
1186 exit(4);
1187 }
1188
1189 rc = receive_object(server, &result, RELATION_T);
1190 if (rc == OP_CANCELLED) {
1191 fprintf(stderr, "Could not receive from server.\n")
1192 exit(4);
1193 }
1194
1195 sever_connection(server);
1196
1197}
1198@end(example)
1199@end(float)
1200
1201This program is complete, if not particularly useful,
1202and it contains all testing needed to detect
1203communication related errors. Many very useful applications employ GDB
1204in just this simple manner. GDB takes care of locating the server
1205(naming of servers is discussed below), managing the connection,
1206converting data for transmission, and detecting errors.
1207
1208As discussed in chapter @ref(async), many GDB operations have
1209@index[Asynchronous operations]
1210asynchronous equivalents. @f[start_sending_object] and
1211@index(start_sending_object)
1212@f[start_receiving_object] may be used to asynchronously send and
1213@index(start_receiving_object)
1214receive data on GDB connections. GDB maintains a separate operation
1215queue for the inbound and the outbound activity on each connection.
1216If you invoke @f[start_sending_object] several times in rapid
1217succession on the same connection, the requests queue up in
1218order. The same is true for @f[start_receiving_object], but sends
1219and receives are queued independently. In certain cases, it may
1220be more efficient to queue several asynchronous transmissions at once
1221than to do just one at a time. You must not change any
1222variables being sent or received until the operations have completed,
1223otherwise unpredictable results may occur. If an ordinary @f[send_object] or
1224@f[receive_object] is invoked, then the corresponding queue is flushed
1225before the synchronous operation is attempted.
1226
1227@section(Naming Communicating Programs)
1228@Index(Naming communicating programs)
1229
1230A GDB program attempting to connect to a correspondent somewhere else
1231in the network must have some means of addressing its connection
1232request. Network servers awaiting connections from clients must have
1233some means of establishing their own identity to the network. The
1234appropriate form for such addresses may change over time and according
1235to the organization in which GDB is being used. To isolate these
1236concerns in the cleanest possible manner, all GDB routines use an
1237ordinary C character string to encode any desired network or service
1238address. Though the form of the string may change when GDB is
1239re-implemented in new environments, the number and nature of
1240parameters to GDB's functions will not.
1241
1242At present, GDB uses the naming facilities of Berkeley 4.2 or 4.3
1243Unix. Berkeley Unix uses a file called @f[/etc/services] to define
1244@index(/etc/services)
1245the names of network services and to map them to internal addresses
1246known as port numbers. Setting up @f[/etc/services] is a job for your
1247Unix system administrator, but you must ensure that each GDB service name
1248you intend to use has been defined in @f[/etc/services] at all
1249communicating sites to be a @i[tcp port]. Your system administrator
1250should know what that means. Once this has been done, the service
1251name is available for use by GDB. For example, a program intended to
1252act as a server for clients playing chess with each other might be
1253created with the GDB function:
1254
1255@begin(example)
1256 client = create_forking_server("chess", NULL)
1257@end(example)
1258
1259where @f[chess] is a service name defined in @f[/etc/services].
1260@index(/etc/services)
1261(Other considerations in using @f[create_forking_server] are discussed
1262@index(create_forking_server)
1263below. Here we are interested only in the service name @f[chess].)
1264
1265A client desiring a connection to this server would have to specify
1266the host at which the server was running as well as its service name.
1267The client might create the connection with:
1268
1269@begin(example)
1270 server = start_server_connection("hostname:chess", NULL)
1271@end(example)
1272
1273@Index(start_server_connection)
1274where @f[hostname] is the name of the host where the server is
1275running. GDB takes care of finding the host, looking up the service
1276name @f[chess] in @f[/etc/services], and making the appropriate
1277connection.
1278
1279Sometimes its convenient to bypass @f[/etc/services] and specify a
1280port number directly. GDB assumes that any service name beginning
1281with @f[#] is a port number. For example:
1282@Index[# (Port number designator)]
1283@Index(Port numbers)
1284
1285@begin(example)
1286 client = create_forking_server("#9502", NULL)
1287@end(example)
1288
1289creates a server at port 9502. No checking for conflicts with
1290existing services or entries in @f[/etc/services] is done. In
1291general, you should be sure that you and your system administrator
1292agree on any service names or port numbers you are going to use before
1293you try it. Otherwise, you may interfere with other network services
1294at your site.
1295
1296@section(Connecting to A Server)
1297@Index(Connecting to a server)
1298
1299The code fragment:
1300
1301@begin(example)
1302 CONNECTION server;
1303
1304 server = start_server_connection("hostname:chess", NULL)
1305 if (server == NULL)
1306 fprintf(stderr, "Could not start connection.\n");
1307@end(example)
1308@Index(start_server_connection)
1309
1310may be used to start a connection to a service named @f[chess] on the
1311specified host. If the returned connection variable is not NULL, then
1312a GDB connection has been created which may be used for sending and
1313receiving GDB objects. The @f[sever_connection] function may be used
1314@index(sever_connection)
1315to break the connection at any time, or the client program may simply
1316exit. A properly written server will notice that the connection has
1317failed and do the appropriate cleanup.
1318The second parameter to @f[start_server_connection] is an optional
1319parameter string which is made available to the server. Rules for
1320using this string are established by each server.
1321There is no asynchronous form of start_server_connection at the
1322present time. GDB delays until the request either succeeds or
1323encounters an unrecoverable error.
1324
1325@section(Writing Servers)
1326
1327There are several kinds of GDB server, each of which is discussed in a
1328separate section below.
1329
1330@subsection(Forking Servers - the simplest kind)
1331
1332@index[Forking servers]
1333The simplest kind of GDB server, which most programmers will use, is
1334called the @i[forking] server.
1335This is the traditional kind of Unix server in which a new process is
1336forked to deal with each client. GDB does the forking for you, and
1337takes care of most of the Unix bookkeeping required in a forking
1338program.
1339Creation of forking servers is best illustrated by the simple example
1340in Program #@ref(ProgramNumber).
1341
1342@modify(example,Size 9)
1343@begin(float)
1344
1345@center(PROGRAM #@ref(ProgramNumber))
1346@set(ProgramNumber=+1)
1347@begin(example)
1348@label(tfsr)
1349{
1350 CONNECTION client; /* talk on this to client */
1351 int data; /* receive data here */
1352
1353 gdb_init(); /* set up gdb */
1354
1355 client = create_forking_server("echoserver",NULL);
1356 fprintf(stderr,"forked\n");
1357
1358 while (TRUE) {
1359 if (receive_object(client, &data, INTEGER_T) ==
1360 OP_CANCELLED) {
1361 fprintf(stderr,"Client has terminated\n");
1362 exit(4);
1363 }
1364 if (data >= 'a' && data <= 'z')
1365 data += 'A'-'a'; /* upcase the response */
1366 if (send_object(client, &data, INTEGER_T) ==
1367 OP_CANCELLED) {
1368 fprintf(stderr,"send error\n");
1369 exit(4);
1370 }
1371 }
1372}
1373@end(example)
1374@end(float)
1375
1376This is a fully functional server capable of supporting an arbitrary
1377number of clients. It does the trivial work of accepting a stream of
1378characters (stored in integers) converting them to uppercase, and
1379sending the result back to the client. The @f[create_forking_server]
1380@index(create_forking_server)
1381function behaves somewhat like the Unix @f[fork] system call. Each
1382@index(fork)
1383time a new client connects to the server, a fork is done and the
1384variable @f[client] in the child process is set to the new client
1385@index(client)
1386connection. In other words, the code below @f[create_forking_server]
1387is automatically invoked over and over again in a new process each
1388time a connection is received from a client. When the processing for
1389each client is done, an @f[exit] or @f[return] is all that is needed
1390@index(return)
1391@index(exit)
1392to cause the appropriate cleanup in the server. Note that this sample
1393server detects termination of its clients by checking for errors when
1394receiving and sending. This technique is convenient and reliable,
1395since the connection is always severed as soon as the client
1396terminates.
1397
1398@subsection(Single Process Servers)
1399
1400@index[Single process servers]
1401Though forking servers are particularly easy to write, they have the
1402disadvantage of breaking the server into a separate process for each
1403client. In particular, forking servers are unsuited to applications
1404in which data is to be shared among the various clients. A server
1405which implemented a bridge game, for example, might relay the bids
1406played by one client to all of the three others. This kind of program
1407is very difficult to implement in a forking server, so GDB also allows
1408you to write servers in which all clients are handled by a single Unix
1409process. Because so much asynchronous activity has to be coordinated
1410within a single process, these servers are generally much harder to
1411design and debug. Nevertheless, they can be the basis of some of the
1412most exciting, high performance applications which can be written with
1413GDB.
1414
1415Chapter @ref(async) introduces the techniques
1416used to do asynchronous communication with GDB.
1417Read it now, if you have not already done so, before proceeding
1418with this section.
1419Here we show how a
1420single server process may @i[asynchronously] acquire new connections
1421from its clients. In general, a single process server works in the
1422following manner:
1423
1424@begin(itemize)
1425@f[create_listening_connection] is used to create a special connection
1426@index(create_listening_connection)
1427on which connection requests from clients arrive.
1428
1429The asynchronous operation @f[start_accepting_client] is
1430@index(start_accepting_client)
1431queued on the listening connection. This operation completes whenever
1432a new client requests a connection. The server immediately issues a
1433new @f[start_accepting_client] in case another client is
1434trying to connect.
1435
1436The server examines the parameters supplied by the client, and if it
1437decides to accept the client's connection, transmits its decision
1438by using the asynchronous operation @f[start_replying_to_client].
1439@index(start_replying_to_client)
1440When this becomes OP_COMPLETE, the new client is ready for use.
1441
1442@f[start_sending_object] and @f[start_receiving_object] are used in
1443@index(start_receiving_object)
1444@index(start_sending_object)
1445the usual manner to send data to and from the clients.
1446@end(itemize)
1447
1448The typical server must be capable of doing all of these operations
1449simultaneously and in any order. It maintains a LIST_OF_OPERATIONS
1450which includes all of the operations on which completion is awaited,
1451and it drops into an @f[op_select_any] to wait for something to
1452@index(op_select_any)
1453happen. Based on the operation which has completed, it determines the
1454next step to perform. If a client has sent data, it may queue a
1455response or prepare data for transmission to other clients. If a new
1456connection request is received it must queue the appropriate response,
1457and so on.
1458
1459There are many ways to organize such a program. A sample, which
1460performs the same character echoing function as the forking server on
1461page @PageRef(tfsr), is included in Appendix @ref(nonforkingserver).
1462Studying this sample is the best way to learn about creating
1463non-forking servers. The GDB library routines are documented in the
1464Library Reference Manual.
1465
1466@section(Communicating Peers)
1467
1468@index[Peer to peer communication]
1469Sometimes it is useful to write communicating @i[peer] programs which
1470do not fit the client/server model.
1471When two peers communicate, neither may be presumed to start before
1472the other. GDB provides a
1473@f[start_peer_connection]@index[start_peer_connection] function which
1474starts a connection to a peer elsewhere in the network.
1475If necessary, @f[start_peer_connection] delays indefinitely until its
1476peer is started and issues a matching @f[start_peer_connection]. Once
1477started, peer connections are used just like any others.
1478@f[start_peer_connection] is documented in the Library Reference Manual.
1479
1480@Chapter(Synchronous and Asynchronous Operations)
1481@label(async)
1482
1483
1484Most of the GDB programs discussed so far have been completely
1485@i[synchronous], meaning that they only try to do one thing
1486at a time. The @f[perform_db_operation] and @f[db_query] routines
1487@index(db_query)
1488@index(perform_db_operation)
1489retain control until the requested operations have run to completion,
1490which makes it impossible for a program to do several queries in
1491parallel, or to continue with its own execution while a database is
1492being updated. GDB also provides @i[asynchronous] versions of many of
1493@index(Asynchronous operations)
1494its services, allowing execution of the client to proceed while the
1495requested operation is attempted. Asynchronous programming is usually
1496more difficult than synchronous, but it is much more flexible. This
1497chapter describes GDB's facilities for managing asynchronous
1498activities.
1499
1500@section(Operations)
1501@index(Asynchronous operations)
1502@index(OPERATION)
1503
1504An asynchronous program may have several operations running in
1505parallel while its own local execution continues. In order to track
1506the progress of these activities, the program uses an OPERATION
1507@index[OPERATION]
1508variable for each one, as illustrated in Program
1509#@ref(ProgramNumber). This program fragment presumes that DATABASEs
1510@f[personnel] and @f[inventory] have been successfully accessed.
1511Several important points are illustrated by the example. Each
1512operation variable must be initialized with the @f[create_operation]
1513@index(create_operation)
1514function. Like most other data structures in GDB, OPERATIONS are
1515really pointer types; @f[create_operation] allocates and initializes
1516the data structure which GDB actually uses to track the operation.
1517
1518@begin(float)
1519
1520@center(PROGRAM #@ref(ProgramNumber))
1521@set(ProgramNumber=+1)
1522@begin(example)
1523 DATABASE personnel, inventory;
1524 char *quel_command;
1525 RELATION new_recruits;
1526
1527 OPERATION query_op, append_op;
1528
1529 /*
1530 * Each operation must be created before it
1531 * can be used
1532 */
1533 query_op = create_operation();
1534 append_op = create_operation();
1535
1536 /*
1537 * Start an append to the parts database in parallel
1538 * with a query to the personnel database. We assume that
1539 * both DB's are accessed and the relation was created.
1540 */
1541 quel_command=
1542 "append to parts (type=\"resistor\", price = .12, quantity=150)";
1543 retcode = start_performing_db_operation(append_op,
1544 personnel,
1545 quel_command);
1546 start_db_query(query_op, personnel, new_recruits,
1547 "(>*name*<=recruits.name, >*rank*<=recruits.rank,
1548 >*serial*<=recruits.serial)
1549 where recruits.rank >10");
1550
1551 /*
1552 * Wait for both to complete. Order of the following
1553 * two statements does NOT matter!
1554 */
1555 complete_operation(append_op);
1556 complete_operation(query_op);
1557
1558 /*
1559 * Check for errors
1560 */
1561 if(OP_RESULT(append_op) != OP_SUCCESS ||
1562 OP_RESULT(query_op) != OP_SUCCESS)
1563 fprintf(stderr,"Something didn't work\n");
1564@end(example)
1565@end(float)
1566
1567There are many ways to check for progress or await completion of GDB
1568operations.
1569One of the simplest is @f[complete_operation], which is
1570@index(complete_operation)
1571shown in this example. The program hangs in GDB until the specified
1572operation completes. As noted in the program comments, the order of
1573the two calls to @f[complete_operation] is @i[not] significant. This
1574might be surprising, as the calls seem to imply that @f[append_op]
1575must complete before @f[query_op] will proceed. That is not the case.
1576@i[Whenever GDB is given control for any reason, it always makes
1577progress as quickly as possible on all pending operations.] This
1578means that @f[query_op] may progress or even complete while
1579awaiting completion of
1580@f[append_op]. Should @f[query_op] complete before
1581@f[append_op], the second call to @f[complete_operation] will not delay
1582at all.
1583
1584Each operation has two types of status, which may be queried by
1585@f[OP_STATUS] and @f[OP_RESULT] respectively. OP_STATUS is used to
1586@index(OP_RESULT)
1587@index(OP_STATUS)
1588track the progress of an operation while it is executing. It has the
1589values shown in table @ref(OP_STATUS).
1590
1591@begin(table)
1592@caption(OP_STATUS Values)
1593@tag(OP_STATUS)
1594@tabset(.75in, 2.5in)
1595
1596@\OP_NOT_STARTED@\The operation
1597@\@\variable is not in use.
1598
1599@\OP_COMPLETE@\The operation completed
1600@\@\without any transmission
1601@\@\related errors.
1602
1603@\OP_CANCELLED@\GDB was forced to
1604@\@\give up on the operation
1605@\@\prematurely. The likeliest
1606@\@\explanation is failure of
1607@\@\the connection.
1608
1609@\other@\OP_STATUS takes on
1610@\@\several other values while
1611@\@\an operation is queued or
1612@\@\executing. These are not
1613@\@\of concern to users of
1614@\@\the library.
1615@end(table)
1616
1617
1618The operation should be considered running until its status becomes
1619either
1620@f[OP_COMPLETE] or @f[OP_CANCELLED]. The macro @f[OP_DONE] may be
1621@index(OP_DONE)
1622@index(OP_CANCELLED)
1623@index(OP_COMPLETE)
1624@index[Return codes from GDB operations]
1625used to test for both of these. When an operation reaches
1626@f[OP_COMPLETE] status, then the @f[OP_RESULT] macro may be used to
1627get the return code from the operation itself. In the case of an
1628Ingres query, for example, the operation will be considered complete
1629when all results have been returned to the client. @f[OP_STATUS] will be
1630@index(OP_STATUS)
1631@f[OP_COMPLETE] and @f[OP_RESULT] will contain the return code from Ingres.
1632If the connection fails before the query is successfully attempted,
1633@f[OP_STATUS] will be @f[OP_CANCELLED] and @f[OP_RESULT] will be
1634undefined. The result value @f[OP_SUCCESS] is usually used to
1635indicate that an operation completed successfully.
1636
1637@f[OPERATIONS] are created in the state @f[OP_NOT_STARTED]. After
1638@index(OP_NOT_STARTED)
1639use, the state is generally @f[OP_CANCELLED] or @f[OP_COMPLETE]. It is
1640possible to re-use such an @f[OPERATION], which saves the overhead of
1641deleting and re-creating it. You must use @f[reset_operation] to
1642prepare an operation for re-use, returning it to the state
1643@f[OP_NOT_STARTED].
1644
1645Hint: it is often handy to create arrays of operations, or to include
1646@Index(Arrays of operations)
1647operations in other C structures. Make sure to do a
1648@f[create_operation] on each one before it is used.
1649@f[delete_operation] may be used to reclaim the space for operations
1650@index(delete_operation)
1651which have terminated and are no longer needed.
1652
1653@section(op_select_any and op_select_all)
1654
1655In certain programs you may wish to take explicit action when any of a
1656list of pending operations completes, or you may wish to monitor
1657activities on file descriptors not controlled by GDB. Berkeley Unix
1658uses @f[select] to control asynchronous file handling, and GDB
1659@index(select)
1660provides two generalized forms which facilitate control of GDB's
1661operations.
1662
1663@f[op_select_any] has semantics similar to the select system
1664@index(op_select_any)
1665call, but in addition, it allows pending GDB operations to
1666progress. Along with a list of file descriptors, you must give
1667@f[op_select_any] a list of the GDB operations whose completion is of
1668interest. Like @f[select], this routine waits quietly when all
1669descriptors are blocked. Unlike @f[select], @f[op_select_any] allows
1670processing to proceed on all GDB connections, and it returns only when
1671one of the operations specified in the list actually completes. While
1672@f[select] would return whenever any data could be read or written on
1673a connection, @f[op_select_any] returns only when enough progress
1674been made that one of the specified operations actually completes. One
1675may think of @f[op_select_any] as raising the level of abstraction on
1676a connection from single bytes to entire operations. As with
1677@f[select], you may supply your own file descriptors and a timeout,
1678and GDB will treat these in the same manner as @f[select] would.
1679@f[op_select_all] is similar to @f[op_select_any], but it waits for
1680@index(op_select_all)
1681all of the specified operations to complete before returning.
1682
1683Both of these functions take as arguments a @f[LIST_OF_OPERATIONS],
1684@index(LIST_OF_OPERATIONS)
1685which may be created using the @f[create_list_of_operations] function.
1686@index(create_list_of_operations)
1687Since manipulating lists is clumsy, it is sometimes useful to create
1688one long list with all the operations you ever expect to wait for, and
1689just pass that to @f[op_select_any]. Once an operation has completed,
1690you should use @f[reset_operation] to keep it from pre-satisfying the
1691next select call.
1692The program in Appendix @ref(nonforkingserver) illustrates all of these
1693techniques.
1694
1695@chapter(Hints and Tricks)
1696@blankspace(2in)
1697@center(To be supplied.)
1698@chapter(Bugs)
1699@blankspace(2in)
1700@center(To be supplied.)
1701
1702@chapter(How GDB Works)
1703
1704The ultimate authority on this is, of course, the GDB code.
1705@index[source code organization]
1706Most of it is pretty well commented (some would say over-commented,
1707but that is my style), which means that you can usually figure out
1708what's happening IF you know where to look and have some general idea
1709of how things work.
1710This chapter presents the general concepts and implementation
1711techniques which underlie GDB.
1712It is not comprehensive, but I do recommend that you read this before
1713looking at the code.
1714
1715GDB is organized into several interacting sub-components or layers.
1716Some are so trivial as to require little or no explanation.
1717Others, such as the layers which do asynchronous operations and
1718communication,
1719are much more complex.
1720The sections below describe the components of GDB and their
1721relationship to each other.
1722A thorough knowledge of Berkeley Unix, C programming, and creation and
1723manipulation of sockets is presumed.
1724It is also presumed that the reader is familiar with the other
1725chapters in this guide.
1726
1727@section(General Code Layout)
1728
1729GDB is supplied as a suite of .c source files which are compiled to
1730build the libgdb.a library archive. The gdb.h include file is used by
1731all of these, and also by user applications.
1732@index[dbserv, compiling]
1733The @f[dbserv] database server is supplied in a separate @f[dbserv.qc]
1734file, which can @i[only] be compiled on a machine which has RTI Ingres
1735installed and accessible. See RTI's documentation for details.
1736If you are not using dbserv then there is no need to build it. The
1737rest of GDB, including database client applications, may be compiled
1738and used on machines which do not have RTI's products installed.
1739
1740The file named gdb.c contains the routine @f[gdb_init], which is
1741@index[gdb_init]
1742called first by all users of gdb.
1743Initialization of GDB data structures can be tracked by reading this
1744source.
1745This source file also contains a few utility routines.
1746Most of the other source is organized more or less by layer, with some
1747of the larger layers split into several source files.
1748The chapters below give hints, or you can grep for the name
1749of the routine in which you are interested.
1750It is always safe to grep in g*.c; this will get all of the executable
1751GDB source.
1752
1753gdb.h is organized more or less by gdb layer, with a ^L page break
1754@index[gdb.h]
1755between each section.
1756You should always have the corresponding section of gdb.h handy while
1757trying to learn about a piece of GDB. It is essential.
1758
1759@section(Memory Management)
1760
1761@index[Memory management]
1762GDB makes extensive use of dynamically allocated (heap) memory.
1763ALL calls for dynamic memory are done through the two routines
1764@index[db_alloc]
1765@index[db_free]
1766@f[db_alloc] and @f[db_free]. These are actually defines in gdb.h
1767which cause invocation of @f[*gdb_amv] and @f[*gdb_fmv] respectively.
1768@index[gdb_amv]
1769@index[gdb_fmv]
1770@index[gdb_am]
1771@index[gdb_fm]
1772These in turn point, by default, to @f[gdb_am] and @f[gdb_fm], which
1773just call malloc and free.
1774This is all done so an application can easily replace the default
1775memory allocators.
1776The addresses of the new routines should be plugged into the vectors
1777prior to calling @f[gdb_init]. Note that the interfaces are @i[not]
1778quite the same as to malloc and free; check the source for details.
1779
1780Many dynamically allocated GDB objects contain 4 character @f[id]
1781fields. These are just eye catchers for debugging, initialized to
1782"REL" for relations, "TUP" for tuples, and so on.
1783Most parameters passed by users are
1784checked for these fields, which helps catch bad parameters and some
1785memory management errors.
1786
1787@section(GDB Type Management)
1788@index[GDB types]
1789@index[Types]
1790
1791Make sure you understand GDB types from a users point of view (Chapter
1792@ref[structure]) before continuing here.
1793
1794The primary purpose of GDB types is to support the polymorphic
1795@index[Polymorphism]
1796operations @f[start_sending_object] and @f[start_receiving_object].
1797These two operations suffice to send and receive @i[any] GDB object,
1798regardless of its structure or complexity.
1799@index[Type definition]
1800@index[GDB Type definition]
1801Given these limited goals, GDB needs only some very basic information
1802about its types:
1803
1804@begin(itemize)
1805The length of an item as represented locally (may depend on local
1806machine type).
1807
1808Required alignment (e.g. 4 or fullword, 8 for double)
1809
1810A function to return a null value for the type.
1811This is used to initialize newly allocated variables.
1812
1813A function to encode values of this type for transmission.
1814
1815A function to decode data of this type from its transmitted form to the
1816local representation (which is usually machine dependent.)
1817
1818A function to return the length which a value would take when encoded
1819for transmission.
1820GDB calls these functions to decide how much memory to allocate for
1821the transmission buffer before calling the encode routine to fill in
1822the buffer.
1823
1824A format function which is used to format variables of this type for
1825debugging output.
1826
1827A string name for the type. Used only for debugging output.
1828@end(itemize)
1829
1830@index[Properties]
1831@index[FCN_PROPERTY]
1832@index[INT_PROPERTY]
1833@index[STR_PROPERTY]
1834All this information is coded into the array named g_type_table.
1835The macros INT_PROPERTY, FCN_PROPERTY, and STR_PROPERTY are used by
1836the GDB code to index into the type table and pull out any desired
1837property for the given type.
1838For example, INT_PROPERTY(REAL_T, LENGTH_PROPERTY) returns the length
1839of the local representation of a real number.
1840
1841@begin(example)
1842 FCN_PROPERTY(REAL_T, ENCODE_PROPERTY) (....)
1843@end(example)
1844
1845calls the encode routine on a real number, with the supplied (....)
1846arguments. Though the macro expansions look messy, they are designed
1847to be optimizable by a good compiler.
1848
1849The routine @f[gdb_i_stype] is used to initialize the type table,
1850@index[gdb_i_stype]
1851thereby defining types. The typing system is extensible in that new
1852types may be defined by adding entries to the type table at any time.
1853The most difficult aspect of this is writing the encode and decode
1854functions for the new type. Note that the routines for encoding and
1855decoding structured types, like tuples and relations, generally make
1856repeated calls to the encoding routines for components. Thus, the
1857relation encoding routine calls the tuple encoding routine, which
1858calls the routines for the various fields. The end result is a single
1859buffer containing the entire structured datum flattened for
1860transmission.
1861
1862@subsection (The TUPLE_T and RELATION_T Structured Types)
1863
1864@index[TUPLE_T]
1865@index[RELATION_T]
1866The @f[TUPLE_T] and @f[RELATION_T] types are supplied with GDB; they
1867are commonly used to contain the results of a relational database
1868query, but they are also useful for transmitting other types of
1869structured data. For brevity, we will refer simply to tuples and
1870relations.
1871
1872Both tuples and relations are self-describing.
1873Given a tuple or relation, one can determine its complete structure as
1874well as its contents.
1875A tuple is an ordered, non-extensible collection of named, typed,
1876fields, and a relation is an ordered, extensible collection of tuples.
1877Because one program, and certainly one relation, will commonly use
1878many tuples with the same structure (i.e. the same field names and
1879types), the description information for these tuples may be shared in
1880a single @f[TUPLE_DESCRIPTOR].
1881@index[Tuple descriptors]
1882The tuple descriptor is allocated and initialized by
1883@f[create_tuple_descriptor] with the names and types of a set of
1884fields.
1885Internally, the descriptor is also initialized to contain the offset
1886and length of the fields within a tuple.
1887Accessing a field within a tuple is thus extremely fast, as the
1888offsets are pre-computed.
1889Note that the offsets and lengths of the fields are local properties
1890which may vary from one machine type to another. Also, this structure
1891supports retrieval of a field whose index or name (and thus its type)
1892is variable at execution time.
1893
1894A single tuple descriptor may be shared by an arbitrary number of
1895tuples, some of which may be members of relations.
1896Also, GDB may implicitly allocate tuple descriptors for tuples and
1897relations received through the network.
1898To facilitate management of these descriptors GDB uses reference
1899counting. Each time a descriptor is used in a tuple or
1900relation, its reference count is incremented. Each time such a tuple
1901or relation is deleted, the reference count is decremented.
1902When the reference count goes to 0, the descriptor itself is
1903reclaimed.
1904@i[As a general rule, users should explicitly de-allocate the
1905descriptors, tuples, and relations that they create, and they should
1906de-allocate objects that they explicitly receive from the network.
1907Implicitly created descriptors will be reclaimed automatically by the
1908system.]
1909
1910@index[TUPLE]
1911@index[TUPLE_DESCRIPTOR]
1912@index[RELATION]
1913The names @F[TUPLE, TUPLE_DESCRIPTOR] and @f[RELATION] supplied in
1914gdb.h are actually pointers and may be manipulated as such (e.g.
1915copied, passed as arguments to functions, etc.) The create functions
1916dynamically allocate memory and fill in the pointers.
1917
1918A tuple descriptor consists of a fixed header, an array containing
1919descriptive information for each field, and then a contiguous list of
1920null terminated strings, which are the text names of the fields.
1921
1922A TUPLE is a pointer to a single contiguous chunk of memory
1923containing a header followed by the data for the tuple fields.
1924The header includes chain pointers, which are used @i[only] when the
1925tuple is contained in a relation, and a pointer to the corresponding
1926tuple descriptor. The data follows immediately, at the offsets listed
1927in the tuple descriptor.
1928Offsets are relative to the start of the first field, not the tuple
1929header.
1930
1931Relations consist of a header structure circularly double linked to a
1932(possibly null) list of tuples.
1933The last tuple points to the relation header, as does the back pointer
1934from the first tuple.
1935A null relation has forward and back pointers to itself.
1936The queue manipulation macros like ADD_TUPLE_TO_RELATION depend on the
1937@index[ADD_TUPLE_TO_RELATION]
1938fact that the next and prev fields are at the same offset in both the
1939tuple and relation header data structures; this may not actually be
1940true on machines which allocate structures backwards, and as much, it
1941represents a non-portability.
1942
1943@section(Communications and Asynchronous Operations)
1944
1945@index[Communication services]
1946@index[Asynchronous operations]
1947This layer of GDB provides management for connections between programs
1948on separate hosts, and for asynchronous transmission of typed data
1949between those hosts. It relies on the memory management and data
1950typing layers discussed above. Due primarily to the extensive support
1951for asynchronous, non-blocking communication on multiple connections,
1952this is by far the most complicated layer of GDB. Rather than trying
1953to discuss every detail, I will emphasize the most important general
1954concepts, and give warnings about implementation features which may be
1955difficult to follow in the code.
1956
1957@subsection(Connections)
1958
1959@index[Connections]
1960A @f[connection] is an abstraction for an asynchronous, reliable,
1961full-duplex path on which GDB can transmit and receive its typed data.
1962The current implementation uses Berkeley TCP stream sockets for
1963transport.
1964
1965Unlike most GDB data structures, all connection descriptors are
1966@index[gdb_cons]
1967statically allocated in the @f[gdb_cons] array. When a new connection is
1968started, the first available slot in the array is returned as the
1969corresponding connection descriptor. NOTE: the actual state of each
1970connection descriptor is contained in its status field. @f[gdb_mcons]
1971is a high water mark variable indicating the highest numbered
1972connection which has ever been used; it provides an optimization for
1973the common case of a process which only uses one or two connections.
1974Below the water mark, the status fields must be checked to determine
1975whether a connection descriptor is actually in use.
1976@index[GDB_MAX_CONNECTIONS]
1977GDB_MAX_CONNECTIONS determines the size of the array, and hence limits
1978the number of simultaneous connections which may be controlled by a
1979single process. The GDB library may be rebuilt with a larger value if
1980desired.
1981
1982Each connection actually consists of two half connections, one for
1983each direction. In the current implementation, they use the same
1984file descriptor, but this could be changed for other networking
1985environments. There is also some stray code which refers to
1986out-of-band connections. This was intended to be used for out of band
1987signalling, primarily to cancel ongoing operations. It was never
1988implemented.
1989
1990@subsection(Operations and Half Connections)
1991
1992@index[Operations]
1993@index[Half connections]
1994Each transmission operation which GDB supports on a half connection is
1995fundamentally asynchronous, meaning that the application program can
1996continue to execute while the operation proceeds.
1997GDB is @i[not] signal driven; it uses non-blocking I/O to make as
1998much progress as possible whenever it gets control, leaving
1999@index[SIGIO]
2000SIGIO available to
2001the application
2002programmer. GDB does set a handler for SIGPIPE.
2003@index[SIGPIPE]
2004Though
2005synchronous versions are provided for most operations, these usually
2006are implemented by invoking the asynchronous version and then
2007immediately waiting for it to complete.
2008
2009Each pending operation is represented by a data structure of type
2010OPERATION (actually, OPERATION is the pointer to the data structure)
2011@i[which is queued on the corresponding half connection.] It is thus
2012a fundamental limitation of the current version of GDB that
2013asynchronous activities exist @i[only] in the context of a connection.
2014The only reason that such an operation may ever block is due to lack
2015of progress in data transmission on the corresponding path. GDB does
2016not provide for any more general kind of multiplexing or lightweight
2017process management.
2018
2019The operation data structure contains the complete state of the
2020pending operation. This is summarized in a status field, which
2021indicates that the operation is either OP_QUEUED (waiting behind
2022others in a queue), OP_RUNNING (at the head of the queue and
2023proceeding as fast a data transmission will allow), OP_COMPLETE
2024(completed without GDB detected error) or OP_CANCELLED (abandoned
2025before completion, usually due to loss of the corresponding
2026connection.) There is also a result field, which becomes valid
2027@i[only] when and if the operation reaches the OP_COMPLETE state. It
2028is effectively the final return code, with legal values depending on the
2029operation being attempted. In addition to these state fields, the
2030operation structure contains a pointer to a function which is to be
2031invoked the next time progress can be made (i.e. the next time the
2032communication path unblocks) and the @f[arg] field, which points to a
2033dynamically allocated structure used by the functions to contain their
2034own ongoing state.
2035
2036The operation actually running on each half connection is the one at
2037the head of the queue. The only reason such an operation may be
2038blocked is because it has tried to send or receive data which the
2039@f[gdb_move_data] routine was unable to move immediately. The pending state of
2040this partially
2041completed
2042@index[next_byte]
2043@index[remaining]
2044transmission is summarized by the @f[next_byte] and @f[remaining]
2045fields of the half_connection structure. If an operation seems not to
2046be progressing, and the @f[remaining] field is non-zero, it may be
2047that the socket is not making progress.
2048
2049The heart of GDB's transport layer is a routine called
2050@index[gdb_progress]
2051@f[gdb_progress], which has the effect of making all possible progress
2052on all pending operations regardless of the connections involved.
2053This routine never blocks.
2054Instead, it cycles through the connections, trying repeatedly to make
2055progress, and returning when no further progress can be made.
2056The actual work is done by
2057@index[gdb_hcon_progress]
2058@f[gdb_hcon_progress], which is one of the
2059most important (and deceptively complicated) in GDB.
2060If the operation at the head of the queue has never been run before,
2061then its initialization function (@f[*init] from the operation
2062structure) is called to start it off.
2063If the operation has been run before, then it @i[must] be blocked
2064waiting for data to be transmitted. In this case,
2065@index[gdb_move_data]
2066@f[gdb_move_data]
2067is called to move the data.
2068If that still results in blockage, then no further progress can be
2069made;
2070otherwise, the operation's continuation function (@f[*cont] from the operation
2071structure) is called to process the data or proceed in some other
2072manner.
2073
2074Most of the subtlety in this area comes from the interplay between
2075multiple connections and operations.
2076If connection 1 blocks, connection 2 may be able to proceed. By the
2077time 2 finishes, 1 may be able to progress after all. For this
2078reason, @f[gdb_hcon_progress] is called over and over again until a
2079full sweep is made through all active connections without a report of
2080any progress at all. Furthermore, it is sometimes the case that an
2081ongoing operation will actually create and queue new operations on
2082either the same or a different connection, which may result in a
2083recursive invocation of @f[gdb_progress]. The
2084@index[HCON_BUSY]
2085@f[HCON_BUSY] flag is
2086used to avoid recursive processing of the same half connection.
2087Another subtle flag is
2088@index[HCON_PROGRESS]
2089@f[HCON_PROGRESS], which is used by
2090@f[gdb_move_data] to indicate whether progress was made on a given half
2091connection. It looks to me in hindsight like this should have been
2092passed as a parameter, perhaps there was a good reason why not. In
2093any case, it is effectively a value returned from @f[gdb_move_data].
2094A final complication arises because an operation is allowed to
2095re-queue itself from one half connection to another. This effectively
2096puts it back from OP_RUNNING to OP_QUEUED state, to be caught by a
2097subsequent sweep of @f[gdb_hcon_progress].
2098
2099@subsection(GDB Select Features)
2100
2101@index[Select operations]
2102In a Berkeley Unix system, the customary means of waiting for I/O to
2103progress is to hang in the @f[select] system call.
2104One of the purposes of GDB is to hide byte level communication from
2105applications, which are interested only in the progress of their higher
2106level requests to GDB. For this reason, GDB provides the new
2107selection operations @f[op_select_any] and @f[op_select_all]. The
2108former is also known by the historical name @f[op_select], which will
2109be used here for brevity. It is also the more interesting of the
2110two, since @f[op_select_all] is built trivially from @f[op_select].
2111
2112@f[op_select] is given a list of queued and/or completed GDB
2113operations, a list of file descriptors not controlled by GDB, and a
2114timeout value in the same form as for Berkeley select. @f[op_select]
2115returns as soon as (1) one of the operations supplied is completed or
2116cancelled (2) a select call indicates that progress can be made on one
2117of the other file descriptors or (3) the timeout is satisfied.
2118Actually, the current version of the system has a bug which
2119effectively resets the time every time any connection makes progress.
2120
2121@index[con_select]
2122The real work here is done in the routine named @f[con_select]. This
2123routine contains the @i[only] significant @f[select] call in the
2124entire GDB system. There are a few others, but those never block.
2125@f[con_select] is similar to a real select except that: (1) it
2126implicitly selects all file descriptors controlled by connections, as
2127well as those explicitly specified (2) it allows transmission and
2128receipt to progress on all connections and (3) it considers a
2129connection to be selected if and only if a transmission operation
2130which had been pending becomes complete. One may consider that
2131@f[con_select] turns the fd's controlled by sockets into operation
2132streams rather than byte streams. Note also that this operation
2133differs from a traditional select and op_select in that it is not
2134robust against waiting for connections with pre-completed activity.
2135This could be added, but since it's an internal routine anyway, it
2136seems not to be worthwhile. Also, this routine presumes that all
2137possible progress has been made before con_select is invoked.
2138
2139Con_select does not know about the specific list of operations for
2140which completion is awaited. Op_select and the other selection
2141routines call con_select repeatedly until the termination criteria are
2142satisfied.
2143
2144@index[complete_operation]
2145Many simple applications use @f[complete_operation] rather
2146than the more complex selection operations to await completion of
2147asynchronous activities. This routine merely calls con_select
2148repeatedly until the desired operation completes. NOTE: even though
2149the user is waiting for activity on a particular operation, all
2150connections and all operations progress. This tends to make it easier
2151for the programmer to avoid deadlocks, and it means that the order in
2152which complete_operation requests are issued is frequently
2153unimportant.
2154
2155@subsection(Connection Error Handling)
2156
2157@index[Error handling]
2158For reasons beyond the control of GDB, connections may fail at any
2159time, and GDB must be prepared for this.
2160In general, all queued operations on the connection are cancelled.
2161Note that the application must still sever the connection, to indicate
2162that it is no longer using its pointers to the connection descriptor.
2163
2164GDB operations are responsible for implementing their own error
2165recovery.
2166None of the existing operations do anything elaborate, and many of
2167them cannot be cancelled at all. It would be very difficult to
2168provide on the fly cancellation of complex operations like database
2169queries, given the asynchronous, full duplex nature of their
2170operation.
2171Right now, the only way to prematurely terminate such an operation is
2172to sever the corresponding connection and restart it.
2173This is always safe, if not convenient.
2174
2175@section(Server/Client Management)
2176
2177@index[Server/client management]
2178GDB supports two general styles of communicating programs:
2179peer-to-peer, and server client.
2180Within the framework of the server/client model, GDB supports both
2181forking and non-forking servers. The interfaces to the two server
2182types are identical, so a given client need not be aware of the style
2183of its server.
2184
2185@subsection(Non-forking servers)
2186
2187@index[Non-forking servers]
2188@index[Servers, non-forking]
2189GDB's asynchronous communication primitives support the creation of
2190non-forking servers, in which multiple clients are serviced by a
2191single Unix server process. The maximum number of clients
2192which can be served by a single non-forking server process is
2193GDB_MAX_CONNECTIONS-1 (one connection is used for the "listening
2194connection", described below.) In addition to
2195@f[start_sending_object] and @f[start_receiving_object] discussed
2196above, @f[start_accepting_client] provides a service for
2197@i[asynchronously] acquiring connections from new clients.
2198Start_accepting_client connection is an asynchronous GDB operation,
2199which may be queued @i[only] on special connections created with the
2200@f[create_listening_connection] primitive.
2201Create_listening_connection allocates a connection descriptor, creates
2202a listening Berkeley Unix Internet Stream socket, and binds a supplied
2203port address to it. Only the inbound half connection of the
2204connection descriptor is significant.
2205
2206The structure of start_accepting_client is subtle, and it
2207serves as a good example of some of the complex ways in which GDB
2208operations can be created. At the time it is issued @i[two] operations
2209are queued on the listening connection. The first one merely does the
2210accept of a new connection, but without filling in any of the
2211connection data structures. The second one is the one which uses the
2212operation descriptor passed by the caller. Its init routine is
2213g_iacc, which therefore runs @i[after] the connection has been
2214acquired from the kernel. This routine proceeds to fill in the new
2215connection descriptor so that communication may be done on the new
2216stream using GDB's services. It also calls g_ver_iprotocol to insure
2217that both sides are running compatible versions of GDB.
2218
2219At this point, the new connection exists, but we still have to acquire
2220the client's parameters. This too must be done asynchronously. On
2221the new connection, a @f[start_receiving_object] is queued, and then
2222the @f[start_accepting_client] re-queues itself onto the data
2223connection. Success of the start_accepting_client now depends on
2224completion of activity on the newly created data connection, not the
2225listening connection. When the start_receiving_object for the client
2226data finally completes, the original start_accepting_client operation,
2227now requeued behind it, takes control again, this time in the routine
2228g_i2acc. This merely checks to insure that the receive completed
2229successfully. It's final status, returned to the caller as OP_STATUS,
2230is the same as that of the receive. The net result of all this is a
2231newly allocated connection for which the accept and the acquisition of
2232the initial parameters were all done without blocking.
2233
2234At this point a tentative connection exists, but the server still has
2235three options in dealing with the new client. These are (1) accept
2236the new client (2) refuse the client or (3) bounce the client to
2237another server. To indicate the disposition, the server application
2238must issue the @f[start_replying_to_client] asynchronous operation,
2239indicating either @f[GDB_ACCEPTED, GDB_REFUSED,] or @f[GDB_FORWARDED].
2240@f[start_replying_to_client] creates a tuple containing the response
2241parameters to be sent to the client. It then queues a
2242@f[start_sending_object] for that tuple on the client connection, and
2243queues itself behind that. By the time @f[start_replying_to_client]
2244receives control again, the send of the tuple has completed. The
2245tuple and other dynamically allocated data is freed, and the return
2246code passed back to the application.
2247
2248@subsection(Forking Servers)
2249
2250@index[Forking servers]
2251@index[Servers, forking]
2252GDB provides a @f[create_forking_server] routine which does most of
2253the bookkeeping required for a single server program to support an
2254arbitrary number of clients, forking once each time a new client
2255connects. The number of simultaneous clients supported is limited
2256only by the number of processes Unix allows the server to create.
2257A GDB forking server has a single parent process, which hangs forever
2258in the @f[create_forking_server] routine, and one child for each
2259active client. @f[create_forking_server] returns in each child the
2260connection descriptor for the corresponding client. The usual GDB
2261communication services may then be used to communicate with the
2262client. The supplied @f[dbserv.qc] database server is an example of a
2263forking server.
2264
2265Internally, create_forking_server begins in the parent by setting up
2266@f[gdb_reaper] as the handler for @f[SIGCHLD]. GDB thus reaps dying
2267children automatically for the application.
2268
2269In the parent, @f[create_forking_server] issues an ordinary
2270@f[create_listening_connection] to establish its own server address.
2271It then loops forever using @f[start_accepting_client] to acquire
2272sockets for new clients.
2273The application may supply a validation routine which is used to
2274determine whether a given client is to be accepted by the server. If
2275the validation routine returns FALSE, then the
2276@f[start_replying_to_client] is used to refuse the connection.
2277Otherwise, the server forks the and the child issues a
2278@f[start_replying_to_client] to accept the connection. In the
2279parent, the client connection is severed (to prevent file and
2280connection descriptor leakage) and the listening operation is reset
2281so that it may be used again. @f[create_forking_server] thus
2282hides the complexity of dynamically acquiring connections, forking,
2283replying to clients, and reaping 'dead' children.
2284
2285The @f[gdb_debug] routine may be used to set a flag called
2286@f[GDB_NOFORK]. When this flag is set, @f[create_forking_server]
2287semantics are changed so that no fork is done when the first client
2288connects. Instead, the single client is served directly by the
2289parent. This flag is useful when using debuggers like dbx, which are
2290incapable of debugging forking programs.
2291
2292@section(Peer-to-peer Communication)
2293
2294@index[Peer-to-peer communication]
2295@f[start_peer_connection] is used by programs wishing to do
2296symmetrical communication, in which neither is the server or the
2297client.
2298The current implementation tries first to connect to the other side,
2299and if that fails, it hangs in an accept. There is a race condition
2300in which the programs may hang if both are started at the same time;
2301each tries a connect, which fails, and then each side hangs in an
2302accept. The only solutions I know to this problem involve either (1)
2303unconditionally creating multiple connections between the two sides,
2304or (2) running randomized delay loops to re-try the connects
2305periodically. Even option (2) will sometimes result in multiple
2306connections. Either of these implementations is a possibility for the
2307future. In the meantime, @f[start_peer_connection] merely fills in a
2308connection descriptor, and does connects and accepts as described
2309above.
2310A check is also made to insure that both partners are running
2311compatible versions of GDB (see g_ver_iprotocol and g_ver_oprotocol.)
2312
2313@section(Database Management)
2314
2315@index[Database management]
2316GDB's database services are cleanly layered on top of the GDB
2317facilities described above. The supplied @f[dbserv.qc] is a forking
2318server implementing a fairly complete set of database access protocols
2319for remote clients. Client functions are provided which encapsulate
2320most of the low level GDB transmission services used for accessing the
2321server.
2322
2323Database clients use operations like @f[start_db_query] and
2324@f[perform_db_operation] to manipulate the database.
2325These functions make extensive use of GDB's
2326asynchronous communication capabilities to maximize the overlap
2327between server and client processing, and to achieve pipelining of
2328data transfers for retrievals returning large quantities of data.
2329Application programmers are given asynchronous versions of most
2330database functions, allowing them to overlap their own execution with
2331GDB's access to the database. A single application may have
2332simultaneous connections to multiple databases at multiple sites, and
2333may have parallel operations in progress to the several databases
2334simultaneously. The current implementation allows a single client to
2335have multiple connections to a single database, with (simulated)
2336parallel activity.
2337
2338@subsection(Database Client Operations)
2339
2340@f[start_accessing_database] returns a pointer of type DATABASE to a
2341dynamically allocated structure used as a handle for subsequent access
2342to that database. Stored within the structure is a pointer of type
2343CONNECTION, which is used for data transmission to and from the
2344server. In reviewing the code I am embarrassed to note that the
2345@f[terminate_db] function described in the library reference manual
2346was never implemented. It's function should be to sever the
2347corresponding connection and de-allocate the database descriptor. In
2348fact, the client may safely terminate or sever the connection at
2349anytime if desired. The server will detect the loss of the connection
2350and do the appropriate cleanup.
2351
2352The application uses @f[start_performing_db_operation] and
2353@f[start_db_query] and their synchronous equivalents to perform
2354operations against the database. @f[start_performing_db_operation] is
2355suitable for any Ingres QUEL operation which is expressible as a
2356single string, and which returns only an integer return code. This is
2357in fact true of almost all QUEL statements except for retrieve, which
2358returns a relation as well as a return code. @f[start_db_query] is
2359used for retrieval.
2360
2361Both of these database access operations are asynchronous and full
2362duplex. This means that an application can stream multiple requests
2363to the server, mixing regular operations in with retrievals. The requests are transmitted
2364to the server as fast as possible, and the responses are received
2365asynchronously, but in order, as they become available.
2366
2367@f[start_performing_db_operation] takes the string containing the QUEL
2368statement, converts it to the GDB type STRING_T, and queues an
2369ordinary @f[start_sending_object] for the string on the outbound half
2370connection. It then queues a @f[start_receiving_object] of an
2371INTEGER_T on the inbound connection to receive the corresponding
2372return code, and queues itself behind that on the @i[inbound]
2373half connection. By the time this operation takes control again,
2374the return code has been received, and cleanup can be done. Note that
2375all phases of this activity are fully asynchronous. In particular,
2376the outbound and inbound activities are completely independent as seen
2377at the client. Of course, the server does not generate the return
2378code until after it has inspected the request, but the client side is
2379fully asynchronous. If another request is issued by the application,
2380then the outbound
2381data is queued for transmission immediately, regardless of how far the
2382first operation has progressed, and the operations to receive the
2383return code are queued behind those from the first request.
2384For example, applications commonly queue in immediate succession the
2385operations to begin a transaction, do several updates, and commit
2386the transaction, waiting for completion only on the commit. These
2387activities proceed much more rapidly than they would if each piece
2388were implemented synchronously.
2389
2390@f[start_db_query] is similar in spirit, but it must also handle the
2391receipt of the retrieved relation.
2392In addition to sending the query string itself, the client sends a
2393copy of the tuple descriptor for the relation to be created. This
2394allows the server to properly format tuples for transmission back to
2395the client, and it also provides type information for each field.
2396As above, a receive operation is queued for a return code, and then
2397the query operation itself is queued on the inbound half connection.
2398It receives control in function g_idbq once the return code has been
2399received. If the return code indicates failure, then the
2400operation is complete. If success is indicated, then the resulting
2401(possibly null) relation must be received from the server.
2402
2403There is no way to tell at this point how many tuples must be
2404received. The server therefore prefaces each tuple transmission with
2405a YES/NO flag, indicating whether another tuple is to follow. The
2406client repeatedly receives these flags, and each time a YES is
2407received, it prepares to receive another TUPLE. These tuples are then
2408inserted into the application's relation. The @f[g_cdbq] routine, which gets
2409control each time a flag or tuple is received, runs in the
2410context of the OPERATION supplied by the application. Each time it
2411receives control, it preempts itself by issuing
2412@f[preempt_and_start_receiving_object], effectively sticking a receive
2413operation ahead of itself on the inbound half connection. This
2414continues until all of the flags and tuple data have been received.
2415
2416Note that @f[start_db_query] and the corresponding server could have
2417been written to move the entire relation as a single GDB object.
2418Though the code for this is much simpler, it means that the entire
2419relation must be prepared at the server before any transmission can
2420begin. The current implementation provides pipelining; each tuple is
2421sent on its way as soon as it is retrieved from Ingres. Transmission
2422time tends to be hidden by the overhead of the Ingres retrieval loop.
2423
2424@subsection(The dbserv.qc Database Server)
2425
2426@index[dbserv]
2427As noted above, the supplied Ingres server is an ordinary GDB forking
2428server whose purpose is to receive database requests from clients and
2429pass them on to Ingres.
2430Most of its operation is straightforward, with transmission of query
2431results being a notable exception.
2432
2433When dbserv receives a query, it first parses the query string to
2434determine which tuple fields will be assigned by the retrieval.
2435The array named @f[offs] in the routine @f[do_query] is
2436filled in with the offset that each retrieved field occupies in the
2437tuple.
2438A query buffer is prepared containing the text of the query in the
2439form required by Ingres. The Ingres type indicators (e.g. %i4 for
2440integer) are placed into the queries in place of the GDB field name
2441indicators.
2442
2443Text fields are handled specially, because their lengths cannot be
2444determined until after retrieval. do_query has a large local array of
2445character strings, into which the actual Ingres retrieval is done.
2446The routine named @f[fix_strings] is then used to copy the resulting
2447text into GDB STRING_T variables, which are assigned to the tuple
2448fields. Copies are needed because the large text buffers may be
2449re-used for subsequent retrieves before the earlier tuples have been
2450transmitted.
2451
2452The main retrieval loop in @f[do_query] repeatedly retrieves
2453information from Ingres into a dummy tuple. This is promptly copied
2454to buffer it for transmission, and @f[fix_strings] is called, as noted
2455above.
2456
2457do_query may have several transmissions outstanding at once, the maximum
2458being determined by the constant @f[OVERLAP]. The @f[pending]
2459structure array, which contains the state of each outstanding
2460transmission is used circularly. This has the effect of insuring that
2461that the server never hangs in a @f[complete_operation] unless more
2462than @f[OVERLAP] transmissions are outstanding at a time. At the time
2463of this writing, @f[OVERLAP] is defined as 10. For each tuple, the
2464server sends the YES/NO flag described above, followed by the data.
2465Note that the data is sent as type TUPLE_DATA_T, rather than TUPLE_T,
2466to eliminate redundant transmissions of the tuple descriptor.
2467
2468@appendix(Functions and Macros for Manipulating Structured Data)
2469
2470Here is a partial list of the GDB functions and macros which may be
2471used to manipulate structured data. This list is intended as a quick
2472reference guide. All user callable GDB routines are documented in the
2473Library Reference Manual.
2474
2475@begin(description)
2476@f[descriptor_from_tuple]@\returns the tuple descriptor of the supplied tuple.
2477@index(descriptor_from_tuple)
2478
2479@f[descriptor_from_relation]@\returns the tuple descriptor of the supplied
2480@index(descriptor_from_relation)
2481relation.
2482
2483@f[create_tuple_descriptor]@\allocates a tuple descriptor.
2484@index(create_tuple_descriptor)
2485
2486@f[delete_tuple_descriptor]@\destroys a tuple descriptor, deallocating the
2487@index(delete_tuple_descriptor)
2488memory which had been used to hold it.
2489
2490@f[create_tuple]@\allocates a tuple.
2491@index(create_tuple)
2492
2493@f[null_tuple_strings]@\If a tuple contains fields of type STRING_T, then
2494@index(null_tuple_strings)
2495the memory for these is allocated separately from that used for other
2496fields in the tuple. This routine releases the memory used for all
2497string fields in the tuple. It should usually be called just before
2498invoking @f[delete_tuple].
2499
2500@f[delete_tuple]@\destroys a tuple, deallocating the
2501@index(delete_tuple)
2502memory which had been used to hold it.
2503
2504@f[string_alloc]@\allocates space for a STRING, filling in the pointer and
2505@index(string_alloc)
2506length fields of the string descriptor.
2507
2508@f[string_free]@\returns the memory used for a STRING.
2509@index(string_free)
2510
2511@f[db_alloc]@\Allocate memory using GDB's memory allocator. In most
2512@index(db_alloc)
2513implementations this just calls Unix @f[malloc], but GDB's memory allocators
2514@index(malloc)
2515can be replaced by users running in unusual environments.
2516
2517@f[db_free]@\Return memory allocated by db_alloc.
2518@index(db_free)
2519
2520@f[STRING_DATA]@\Given an argument of type STRING, returns a @f[(char *)]
2521@index(STRING_DATA)
2522pointer to the string data. This is a macro which may appear as the
2523target of an assignment statement; you can construct your own STRING
2524by setting the STRING_DATA and MAX_STRING_SIZE.
2525
2526@f[MAX_STRING_SIZE]@\Given an argument of type STRING, returns an integer equal
2527
2528@index(MAX_STRING_SIZE)
2529to the size of the allocated string data. If the STRING is used to
2530hold a null terminated C character string, then @f[strlen] of that string
2531@index(strlen)
2532must be @f[<= MAX_STRING_SIZE].
2533
2534@f[ADD_TUPLE_TO_RELATION]@\a macro which inserts a new tuple after all the
2535@index(ADD_TUPLE_TO_RELATION)
2536others in a relation. The tuple must share the same descriptor as the
2537relation itself.
2538
2539@f[ADD_TUPLE_AFTER_TUPLE]@\inserts a tuple into the middle of a relation.
2540@index(ADD_TUPLE_AFTER_TUPLE)
2541
2542@f[REMOVE_TUPLE_FROM_RELATION]@\the specified tuple is removed from the
2543@index(REMOVE_TUPLE_FROM_RELATION)
2544relation, but not de-allocated. It may subsequently be inserted in
2545another relation if desired. Each tuple may be in at most one
2546relation at a time.
2547
2548@f[FIRST_TUPLE_IN_RELATION]@\Finds the first tuple in a relation. Returns
2549@index(FIRST_TUPLE_IN_RELATION)
2550NULL if the relation is empty.
2551
2552@f[NEXT_TUPLE_IN_RELATION]@\Given a relation and a tuple which is presumed
2553@index(NEXT_TUPLE_IN_RELATION)
2554to be in that relation, return the tuple which follows the one
2555supplied. NULL is returned if the tuple supplied is the last one in
2556the relation.
2557
2558@f[PREV_TUPLE_IN_RELATION]@\Given a relation and a tuple which is presumed
2559@index(PREV_TUPLE_IN_RELATION)
2560to be in that relation, return the tuple which preceeds the one
2561supplied. NULL is returned if the tuple supplied is the first one in
2562the relation.
2563
2564@f[DESCRIPTOR_FROM_TUPLE]@\Given a tuple, get back its tuple descriptor.
2565@index(DESCRIPTOR_FROM_TUPLE)
2566
2567@f[DESCRIPTOR_FROM_RELATION]@\Given a relation, get back its tuple descriptor.
2568@index(DESCRIPTOR_FROM_RELATION)
2569
2570@f[FIELD_FROM_TUPLE]@\Given a tuple and a field index, return a pointer to the
2571@index(FIELD_FROM_TUPLE)
2572field. The results of this macro must be cast properly by the caller.
2573
2574@f[FIELD_TYPE_IN_TUPLE]@\Given a tuple descriptor (@i[not] a tuple) and
2575@index(FIELD_TYPE_IN_TUPLE)
2576the index (@i[not] the name) of a field, return the type code of the
2577field. Symbolic names for type codes, such as @f[STRING_T] and
2578@Index(STRING_T)
2579@f(INTEGER_T) are defined in gdb.h; they may be stored in
2580@Index(INTEGER_T)
2581variables of type @f[FIELD_TYPE].
2582@index(FIELD_TYPE)
2583
2584@f[field_index]@\Given a tuple descriptor and the name of a field, return the
2585@index(field_index)
2586index of that field.
2587
2588@end(description)
2589
2590The following routines are often useful for debugging GDB
2591applications. @b[Important note: each of these routines takes two
2592arguments, the first is an i.d. string, the second is the object to be printed!]
2593
2594@begin(description)
2595@f[print_tuple]@\Prints a tuple on the gdb_log file (which defaults to
2596@index(print_tuple)
2597stderr.) All fields are correctly labeled and formatted according to
2598their type.
2599
2600@f[print_relation]@\Prints an entire relation, with all of its tuples, on gdb_log.
2601@index(print_relation)
2602@end(description)
2603@appendix(Sample Non-Forking Server)
2604@label(nonforkingserver)
2605@modify(example,Size 8)
2606@begin(example)
2607/************************************************************************/
2608/*
2609/* tsr (test server)
2610/* -----------------
2611/*
2612/* Author: Noah Mendelsohn (IBM T.J. Watson Research and MIT Project
2613/* Athena)
2614/*
2615/* Copyright: 1986 MIT Project Athena
2616/*
2617/************************************************************************/
2618/*
2619/* PURPOSE
2620/* -------
2621/*
2622/* A GDB server program demonstrating techniques for asynchronously
2623/* communicating with an arbitrary number of clients from a single
2624/* Unix server process. This server accepts GDB connections from
2625/* clients as requests come in (up to the arbitrary maximum
2626/* MAXCLIENTS.) On each connection, it receives a stream of integers,
2627/* which it interprets as ASCII characters. The characters are
2628/* converted to uppercase, and then sent back to the client from
2629/* which they came.
2630/*
2631/* All of this is done completely asynchronously. No client is
2632/* locked out while characters are being echoed to another, and
2633/* new connections are accepted at any time.
2634/*
2635/* NOTES
2636/* -----
2637/*
2638/* 1) The complete state of each client is kept in the array
2639/* named client. The client[i].state variable indicates whether
2640/* client i is active, and if so, the client[i].action variable
2641/* indicates what kind of asynchronous activity the client is
2642/* engaged in. Note that these are local conventions, having
2643/* nothing to do with GDB or its interfaces.
2644/*
2645/* 2) Communication to each client is done over its connection,
2646/* named client[i].con.
2647/*
2648/* 3) There is at most one asynchronous activity pending to
2649/* each client at any given time, and its state is tracked
2650/* in the variable named client[i].pending_op. The operation
2651/* may be a send, a receive, or an accept, depending on
2652/* the contents of client[i].action. These operations are
2653/* allocated when the server starts up, and then re-used
2654/* repeatedly. They are the GDB analog of a lightweight process,
2655/* which is activated when queued on a connection.
2656/*
2657/* 4) A special form of connection and a special listening operation
2658/* are used for asynchronously listening for new connection
2659/* requests. These are 'listencon' and 'listenop' respectively.
2660/*
2661/* 5) GDB includes a special form of select which waits for
2662/* completion of operations as well as for activity on user
2663/* specified file descriptors. The list of operations to be
2664/* monitored is stored in the variable
2665/* named op_list. The call to op_select_any hangs until one
2666/* or more of these operations complete, then terminates.
2667/*
2668/* 6) The main server loop acts on any new connection requests,
2669/* processes any newly completed activity on the active
2670/* clients, then drops into op_select_any to allow asynchronous
2671/* activities to progress.
2672/*
2673/*
2674/************************************************************************/
2675@end(example)
2676@begin(example)
2677#include <stdio.h>
2678#include "gdb.h"
2679
2680/************************************************************************/
2681/*
2682/* DECLARATIONS
2683/*
2684/************************************************************************/
2685
2686#define MAXCLIENTS 10
2687
2688 /*----------------------------------------------------------*/
2689 /*
2690 /* State of each possible client
2691 /*
2692 /*----------------------------------------------------------*/
2693
2694struct client {
2695 int state; /* state of this client */
2696 /* descriptor */
2697#define CL_DEAD 1 /* client not started */
2698#define CL_STARTING 2 /* accepted, reply ongoing */
2699#define CL_UP 3 /* ready to go */
2700 int action; /* what are we doing now */
2701#define CL_RECEIVE 4 /* waiting for a packet */
2702#define CL_SEND 5 /* sending a packet */
2703#define CL_ACCEPT 6 /* sending a reply */
2704 CONNECTION con; /* connection to this */
2705 /* client, if any */
2706 OPERATION pending_op; /* pending operation */
2707 /* on this connection, */
2708 /* if any */
2709 int data; /* the character to echo */
2710 /* goes here, expressed as */
2711 /* an int */
2712};
2713
2714struct client client[MAXCLIENTS];
2715
2716 /*----------------------------------------------------------*/
2717 /*
2718 /* Connections and operations for listening for
2719 /* new clients.
2720 /*
2721 /*----------------------------------------------------------*/
2722
2723CONNECTION listencon; /* listen on this */
2724 /* connection */
2725OPERATION listenop; /* this operation is used */
2726 /* repeatedly for listening */
2727 /* for new clients */
2728
2729int nextcl = 0; /* index of the next client */
2730 /* we'll accept */
2731
2732 /*----------------------------------------------------------*/
2733 /*
2734 /* Miscellaneous variables used in acquiring connections.
2735 /* These are ignored in a simple server like this; a
2736 /* more sophisticated server might want to validate the
2737 /* names of its clients before accepting connections.
2738 /*
2739 /*----------------------------------------------------------*/
2740
2741TUPLE client_tuple; /* client request goes */
2742 /* here */
2743char otherside[100];
2744int othersize;
2745@end(example)
2746@begin(example)
2747/************************************************************************/
2748/*
2749/* MAIN
2750/*
2751/************************************************************************/
2752
2753int
2754main(argc, argv)
2755int argc;
2756char *argv[];
2757{
2758 /*----------------------------------------------------------*/
2759 /*
2760 /* LOCAL VARIABLES
2761 /*
2762 /*----------------------------------------------------------*/
2763
2764 register int i; /* loop index */
2765 LIST_OF_OPERATIONS op_list; /* for op_select_any */
2766
2767 /*----------------------------------------------------------*/
2768 /*
2769 /* Check parameters
2770 /*
2771 /*----------------------------------------------------------*/
2772
2773 if (argc != 2) {
2774 fprintf(stderr,"Correct form is %s <servicename>\n",
2775 argv[0]);
2776 exit(4);
2777 }
2778
2779 /*----------------------------------------------------------*/
2780 /*
2781 /* Initialize
2782 /*
2783 /*----------------------------------------------------------*/
2784
2785 gdb_init(); /* set up gdb */
2786 init_clients(); /* null the client states */
2787 do_listen(argv[1]); /* start the listening */
2788 /* connection and queue */
2789 /* a listening operation */
2790 make_oplist(&op_list); /* create wait list */
2791
2792 /*----------------------------------------------------------*/
2793 /*
2794 /* Loop forever taking care of business.
2795 /*
2796 /* 1) If any new connection requests have come in,
2797 /* accept them.
2798 /*
2799 /* 2) For each client on which some activity is newly
2800 /* completed, take care of it.
2801 /*
2802 /*----------------------------------------------------------*/
2803
2804 while (TRUE) {
2805 if (OP_DONE(listenop))
2806 new_connection();
2807 for (i=0; i<MAXCLIENTS; i++) {
2808 if (OP_DONE(client[i].pending_op))
2809 do_client(i);
2810 }
2811 op_select_any(op_list, 0, NULL, NULL, NULL, NULL);
2812 }
2813}
2814@end(example)
2815@begin(example)
2816/************************************************************************/
2817/*
2818/* do_client
2819/*
2820/* An operation has completed on the specified client.
2821/*
2822/************************************************************************/
2823
2824int
2825do_client(id)
2826int id;
2827{
2828 register struct client *cp = &(client[id]);
2829
2830 /*
2831 * If there has been an error, shutdown the client.
2832 */
2833 if (OP_STATUS(cp->pending_op) == OP_CANCELLED) {
2834 sever_connection(cp->con);
2835 reset_operation(cp->pending_op);
2836 cp->state = CL_DEAD;
2837 cp->action = 0;
2838 return;
2839 }
2840 /*
2841 * The operation completed successfully. Figure out what it was
2842 * and do the right thing.
2843 */
2844 switch (cp->action) {
2845 case CL_ACCEPT:
2846 case CL_SEND:
2847 start_receiving_object(cp->pending_op, cp->con,
2848 (char *)&cp->data,
2849 INTEGER_T);
2850 cp->action = CL_RECEIVE;
2851 break;
2852 case CL_RECEIVE:
2853 if (cp->data >= 'a' && cp->data <= 'z')
2854 cp->data += 'A'-'a'; /* upcase the response */
2855 start_sending_object(cp->pending_op, cp->con,
2856 (char *)&cp->data,
2857 INTEGER_T);
2858 cp->action = CL_SEND;
2859 }
2860}
2861@newpage
2862/************************************************************************/
2863/*
2864/* init_clients
2865/*
2866/************************************************************************/
2867
2868int
2869init_clients()
2870{
2871 register struct client *c;
2872
2873 for (c=client; c<client+MAXCLIENTS; c++){
2874 c->state = CL_DEAD;
2875 c->action = 0;
2876 c->con = NULL;
2877 c->pending_op = create_operation();
2878 reset_operation(c->pending_op);
2879 }
2880}
2881
2882
2883@end(example)
2884@begin(example)
2885/************************************************************************/
2886/*
2887/* make_oplist
2888/*
2889/************************************************************************/
2890
2891int
2892make_oplist(oplp)
2893LIST_OF_OPERATIONS *oplp;
2894{
2895 /*
2896 * ugh! we've got to fix create_list_of_operations to be
2897 * more flexible!!
2898 */
2899
2900 *oplp = create_list_of_operations(MAXCLIENTS+1, listenop,
2901 client[0].pending_op,
2902 client[1].pending_op,
2903 client[2].pending_op,
2904 client[3].pending_op,
2905 client[4].pending_op,
2906 client[5].pending_op,
2907 client[6].pending_op,
2908 client[7].pending_op,
2909 client[8].pending_op,
2910 client[9].pending_op);
2911}
2912@end(example)
2913@begin(example)
2914/************************************************************************/
2915/*
2916/* do_listen
2917/*
2918/* Do the one time setup for listening for clients, and
2919/* also start a listen for an actual client.
2920/*
2921/************************************************************************/
2922
2923int
2924do_listen(service)
2925char *service;
2926{
2927
2928 /*----------------------------------------------------------*/
2929 /*
2930 /* Make a listening connection
2931 /*
2932 /*----------------------------------------------------------*/
2933
2934 fprintf(stderr, "Server creating listening connection\n");
2935 listencon = create_listening_connection(service);
2936
2937 if (listencon == NULL) {
2938 fprintf(stderr,"tsr: could not create listening connection\n");
2939 exit (4);
2940 }
2941
2942 /*----------------------------------------------------------*/
2943 /*
2944 /* On that connection, put up an operation to listen
2945 /* for our first client.
2946 /*
2947 /*----------------------------------------------------------*/
2948
2949 listenop = create_operation();
2950
2951 othersize = sizeof(otherside);
2952
2953 start_accepting_client(listencon, listenop, &(client[nextcl].con),
2954 (char *)otherside,
2955 &othersize, &client_tuple);
2956
2957}
2958@end(example)
2959@begin(example)
2960/************************************************************************/
2961/*
2962/* new_connection
2963/*
2964/* We have just gotten a connection for client nextcl.
2965/*
2966/************************************************************************/
2967
2968int
2969new_connection()
2970{
2971 register struct client *cp = &client[nextcl];
2972 /*
2973 * Make sure there's been no error
2974 */
2975 if(OP_STATUS(listenop) != OP_COMPLETE ||
2976 cp->con == NULL) {
2977 fprintf(stderr,"Error on listening operation\n");
2978 exit(8);
2979 }
2980 /*
2981 * Set up the new connection and reply to the client
2982 */
2983 cp->state = CL_STARTING;
2984 cp->action = CL_ACCEPT;
2985 start_replying_to_client(cp->pending_op, cp->con, GDB_ACCEPTED,
2986 "", "");
2987
2988 /*
2989 * Find a new free connection descriptor. Blow up if we've used the
2990 * last one
2991 */
2992 for (nextcl=0; nextcl<MAXCLIENTS; nextcl++)
2993 if (client[nextcl].state == CL_DEAD)
2994 break;
2995
2996 if (nextcl == MAXCLIENTS) {
2997 fprintf(stderr,"Too many clients, giving up\n");
2998 exit(8);
2999 }
3000 /*
3001 * Start listening again
3002 */
3003 reset_operation(listenop);
3004 othersize = sizeof(otherside);
3005
3006 start_accepting_client(listencon, listenop, &(client[nextcl].con),
3007 (char *)otherside,
3008 &othersize, &client_tuple);
3009
3010
3011}
3012@end(example)
3013
3014@begin(comment)
3015
3016@Chapter(Hints and Tricks)
3017select variants
3018
3019redefining GDB_GIVEUP
3020
3021replacing storage allocators
3022
3023print_relation, tuple, etc.
3024
3025tuples as analogs for structures.
3026
3027Using procedures to keep tuples up to date.
3028
3029Creating your own types
3030
3031Debug switch and the log
3032
3033Output from dbserv
3034
3035Reference counting of tuple descriptors.
3036
3037@Chapter(Bugs)
3038Macros which require no ; after invocation
3039
3040/etc/services entries for database server
3041
3042Only one database server per site.
3043@Chapter(How GDB Works)
3044
3045@end(comment)
This page took 0.468095 seconds and 5 git commands to generate.