summaryrefslogtreecommitdiffstats
path: root/src/main.c
blob: d19f7e0f9d1de01681f2d097befc8b03bb56a049 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
/* 
 * Copyright (C) 2015 "IoT.bzh"
 * Author "Fulup Ar Foll"
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/* 
 * File:   main.c
 * Author: "Fulup Ar Foll"
 *
 * Created on 05 December 2015, 15:38
 */

#include "local-def.h"

#include <syslog.h>
#include <setjmp.h>
#include <signal.h>
#include <getopt.h>
#include <pwd.h>

#define AFB_VERSION    "0.1"

static sigjmp_buf exitPoint; // context save for set/longjmp

/*----------------------------------------------------------
 | printversion
 |   print version and copyright
 +--------------------------------------------------------- */
 static void printVersion (void) {

   fprintf (stderr,"\n----------------------------------------- \n");
   fprintf (stderr,"|  AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
   fprintf (stderr,"----------------------------------------- \n");
   fprintf (stderr,"|  Copyright(C) 2015 Fulup Ar Foll /IoT.bzh [fulup -at- iot.bzh]\n");
   fprintf (stderr,"|  AFB comes with ABSOLUTELY NO WARRANTY.\n");
   fprintf (stderr,"|  Licence [what ever makes you happy] until you fix bugs by yourself :)\n\n");
   exit (0);
 } // end printVersion


// Define command line option
#define SET_VERBOSE        101
#define SET_BACKGROUND     105
#define SET_FORGROUND      106
#define KILL_PREV_EXIT     107
#define KILL_PREV_REST     108
#define SET_FAKE_MOD       109

#define SET_TCP_PORT       120
#define SET_ROOT_DIR       121
#define SET_ROOT_BASE      122
#define SET_ROOT_API       123
#define SET_ROOT_ALIAS     124

#define SET_CACHE_TO       130
#define SET_USERID         131
#define SET_PID_FILE       132
#define SET_SESSION_DIR    133
#define SET_CONFIG_FILE    134
#define SET_CONFIG_SAVE    135
#define SET_CONFIG_EXIT    138

#define SET_AUTH_TOKEN     141
#define SET_LDPATH         142
#define SET_APITIMEOUT     143
#define SET_CNTXTIMEOUT    144

#define DISPLAY_VERSION    150
#define DISPLAY_HELP       151

#define SET_MODE           160
#define SET_READYFD        161

// Command line structure hold cli --command + help text
typedef struct {
  int  val;        // command number within application
  int  has_arg;    // command number within application
  char *name;      // command as used in --xxxx cli
  char *help;      // help text
} AFB_options;


// Supported option
static  AFB_options cliOptions [] = {
  {SET_VERBOSE      ,0,"verbose"         , "Verbose Mode"},

  {SET_FORGROUND    ,0,"foreground"      , "Get all in foreground mode"},
  {SET_BACKGROUND   ,0,"daemon"          , "Get all in background mode"},
  {KILL_PREV_EXIT   ,0,"kill"            , "Kill active process if any and exit"},
  {KILL_PREV_REST   ,0,"restart"         , "Kill active process if any and restart"},

  {SET_TCP_PORT     ,1,"port"            , "HTTP listening TCP port  [default 1234]"},
  {SET_ROOT_DIR     ,1,"rootdir"         , "HTTP Root Directory [default $HOME/.AFB]"},
  {SET_ROOT_BASE    ,1,"rootbase"        , "Angular Base Root URL [default /opa]"},
  {SET_ROOT_API     ,1,"rootapi"         , "HTML Root API URL [default /api]"},
  {SET_ROOT_ALIAS   ,1,"alias"           , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
  
  {SET_APITIMEOUT   ,1,"apitimeout"      , "Plugin API timeout in seconds [default 10]"},
  {SET_CNTXTIMEOUT  ,1,"cntxtimeout"     , "Client Session Context Timeout [default 900]"},
  {SET_CACHE_TO     ,1,"cache-eol"       , "Client cache end of live [default 3600s]"},
  
  {SET_USERID       ,1,"setuid"          , "Change user id [default don't change]"},
  {SET_PID_FILE     ,1,"pidfile"         , "PID file path [default none]"},
  {SET_SESSION_DIR  ,1,"sessiondir"      , "Sessions file path [default rootdir/sessions]"},
  {SET_CONFIG_FILE  ,1,"config"          , "Config Filename [default rootdir/sessions/configs/default.AFB]"},

  {SET_LDPATH       ,1,"ldpaths"         , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
  {SET_AUTH_TOKEN   ,1,"token"           , "Initial Secret [default=no-session, --token="" for session without authentication]"},
  
  {DISPLAY_VERSION  ,0,"version"         , "Display version and copyright"},
  {DISPLAY_HELP     ,0,"help"            , "Display this help"},

  {SET_MODE         ,1,"mode"            , "set the mode: either local, remote or global"},
  {SET_READYFD      ,1,"readyfd"         , "set the #fd to signal when ready"},
  {0, 0, NULL, NULL}
 };

static AFB_aliasdir aliasdir[MAX_ALIAS];
static int aliascount=0;

/*----------------------------------------------------------
 | timeout signalQuit
 |
 +--------------------------------------------------------- */
void signalQuit (int signum) {

  sigset_t sigset;

  // unlock timeout signal to allow a new signal to come
  sigemptyset (&sigset);
  sigaddset   (&sigset, SIGABRT);
  sigprocmask (SIG_UNBLOCK, &sigset, 0);

  fprintf (stderr, "%s ERR:Received signal quit\n",configTime());
  syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
  longjmp (exitPoint, signum);
}


/*----------------------------------------------------------
 | printHelp
 |   print information from long option array
 +--------------------------------------------------------- */

 static void printHelp(char *name) {
    int ind;
    char command[20];

    fprintf (stderr,"%s:\nallowed options\n", name);
    for (ind=0; cliOptions [ind].name != NULL;ind++)
    {
      // display options
      if (cliOptions [ind].has_arg == 0 )
      {
	     fprintf (stderr,"  --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
      } else {
         sprintf(command,"%s=xxxx", cliOptions [ind].name);
         fprintf (stderr,"  --%-15s %s\n", command, cliOptions[ind].help);
      }
    }
    fprintf (stderr,"Example:\n  %s\\\n  --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
} // end printHelp

/*----------------------------------------------------------
 | writePidFile
 |   write a file in /var/run/AFB with pid
 +--------------------------------------------------------- */
static int writePidFile (AFB_config *config, int pid) {
  FILE *file;

  // if no pid file configure just return
  if (config->pidfile == NULL) return 0;

  // open pid file in write mode
  file = fopen(config->pidfile,"w");
  if (file == NULL) {
    fprintf (stderr,"%s ERR:writePidFile fail to open [%s]\n",configTime(), config->pidfile);
    return -1;
  }

  // write pid in file and close
  fprintf (file, "%d\n", pid);
  fclose  (file);
  return 0;
}

/*----------------------------------------------------------
 | readPidFile
 |   read file in /var/run/AFB with pid
 +--------------------------------------------------------- */
static int readPidFile (AFB_config *config) {
  int  pid;
  FILE *file;
  int  status;

  if (config->pidfile == NULL) return -1;

  // open pid file in write mode
  file = fopen(config->pidfile,"r");
  if (file == NULL) {
    fprintf (stderr,"%s ERR:readPidFile fail to open [%s]\n",configTime(), config->pidfile);
    return -1;
  }

  // write pid in file and close
  status = fscanf  (file, "%d\n", &pid);
  fclose  (file);

  // never kill pid 0
  if (status != 1) return -1;

  return (pid);
}

/*----------------------------------------------------------
 | closeSession
 |   try to close everything before leaving
 +--------------------------------------------------------- */
static void closeSession (AFB_session *session) {


}

/*----------------------------------------------------------
 | listenLoop
 |   Main listening HTTP loop
 +--------------------------------------------------------- */
static void listenLoop (AFB_session *session) {
  AFB_error  err;

  if (signal (SIGABRT, signalQuit) == SIG_ERR) {
        fprintf (stderr, "%s ERR: main fail to install Signal handler\n", configTime());
        return;
  }

  // ------ Start httpd server
  if (session->config->httpdPort > 0) {

        err = httpdStart (session);
        if (err != AFB_SUCCESS) return;

	if (session->readyfd != 0) {
		static const char readystr[] = "READY=1";
		write(session->readyfd, readystr, sizeof(readystr) - 1);
		close(session->readyfd);
	}

        // infinite loop
        httpdLoop(session);

        fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
  }
}
  
/*---------------------------------------------------------
 | main
 |   Parse option and launch action
 +--------------------------------------------------------- */

static void parse_arguments(int argc, char *argv[], AFB_session *session)
{
  char*          programName = argv [0];
  int            optionIndex = 0;
  int            optc, ind;
  int            nbcmd;
  struct option *gnuOptions;
  AFB_config     cliconfig; // temp structure to store CLI option before file config upload

  // ------------- Build session handler & init config -------
  memset(&cliconfig,0,sizeof(cliconfig));
  memset(&aliasdir  ,0,sizeof(aliasdir));
  cliconfig.aliasdir = aliasdir;

  // ------------------ Process Command Line -----------------------

  // if no argument print help and return
  if (argc < 2) {
       printHelp(programName);
       exit(1);
  }

  // build GNU getopt info from cliOptions
  nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
  gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
  for (ind=0; ind < nbcmd;ind++) {
    gnuOptions [ind].name    = cliOptions[ind].name;
    gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
    gnuOptions [ind].flag    = 0;
    gnuOptions [ind].val     = cliOptions[ind].val;
  }

  // get all options from command line
  while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
        != EOF)
  {
    switch (optc)
    {
     case SET_VERBOSE:
       verbose = 1;
       break;

    case SET_TCP_PORT:
       if (optarg == 0) goto needValueForOption;
       if (!sscanf (optarg, "%d", &cliconfig.httpdPort)) goto notAnInteger;
       break;
       
    case SET_APITIMEOUT:
       if (optarg == 0) goto needValueForOption;
       if (!sscanf (optarg, "%d", &cliconfig.apiTimeout)) goto notAnInteger;
       break;

    case SET_CNTXTIMEOUT:
       if (optarg == 0) goto needValueForOption;
       if (!sscanf (optarg, "%d", &cliconfig.cntxTimeout)) goto notAnInteger;
       break;

    case SET_ROOT_DIR:
       if (optarg == 0) goto needValueForOption;
       cliconfig.rootdir   = optarg;
       if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",cliconfig.rootdir);
       break;       
       
    case SET_ROOT_BASE:
       if (optarg == 0) goto needValueForOption;
       cliconfig.rootbase   = optarg;
       if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",cliconfig.rootbase);
       break;

    case SET_ROOT_API:
       if (optarg == 0) goto needValueForOption;
       cliconfig.rootapi   = optarg;
       if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",cliconfig.rootapi);
       break;
       
    case SET_ROOT_ALIAS:
       if (optarg == 0) goto needValueForOption;
       if (aliascount < MAX_ALIAS) {
            aliasdir[aliascount].url  = strsep(&optarg,":");
            if (optarg == NULL) {
              fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
            } else {
              aliasdir[aliascount].path = optarg;
              aliasdir[aliascount].len  = strlen(aliasdir[aliascount].url);
              if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
              aliascount++;
            }
       } else {
           fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
       }     
       break;
       
    case SET_AUTH_TOKEN:
       if (optarg == 0) goto needValueForOption;
       cliconfig.token   = optarg;
       break;

    case SET_LDPATH:
       if (optarg == 0) goto needValueForOption;
       cliconfig.ldpaths = optarg;
       break;

    case SET_PID_FILE:
       if (optarg == 0) goto needValueForOption;
       cliconfig.pidfile   = optarg;
       break;

    case SET_SESSION_DIR:
       if (optarg == 0) goto needValueForOption;
       cliconfig.sessiondir   = optarg;
       break;

    case  SET_CONFIG_FILE:
       if (optarg == 0) goto needValueForOption;
       cliconfig.configfile   = optarg;
       break;

    case  SET_CACHE_TO:
       if (optarg == 0) goto needValueForOption;
       if (!sscanf (optarg, "%d", &cliconfig.cacheTimeout)) goto notAnInteger;
       break;

    case SET_USERID:
       if (optarg == 0) goto needValueForOption;
       cliconfig.setuid = optarg;
       break;

    case SET_FAKE_MOD:
       if (optarg != 0) goto noValueForOption;
       session->fakemod  = 1;
       break;

    case SET_FORGROUND:
       if (optarg != 0) goto noValueForOption;
       session->foreground  = 1;
       break;

    case SET_BACKGROUND:
       if (optarg != 0) goto noValueForOption;
       session->background  = 1;
       break;

     case KILL_PREV_REST:
       if (optarg != 0) goto noValueForOption;
       session->killPrevious  = 1;
       break;

     case KILL_PREV_EXIT:
       if (optarg != 0) goto noValueForOption;
       session->killPrevious  = 2;
       break;

    case SET_MODE:
       if (optarg == 0) goto needValueForOption;
       if (!strcmp(optarg, "local")) cliconfig.mode = AFB_MODE_LOCAL;
       else if (!strcmp(optarg, "remote")) cliconfig.mode = AFB_MODE_REMOTE;
       else if (!strcmp(optarg, "global")) cliconfig.mode = AFB_MODE_GLOBAL;
       else goto badMode;
       break;

    case SET_READYFD:
       if (optarg == 0) goto needValueForOption;
       if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
       break;

    case DISPLAY_VERSION:
       if (optarg != 0) goto noValueForOption;
       printVersion();
       exit(0);

    case DISPLAY_HELP:
     default:
       printHelp(programName);
       exit(0);
    }
  }
  free(gnuOptions);
 
  // if exist merge config file with CLI arguments
  configLoadFile  (session, &cliconfig);
  return;


needValueForOption:
  fprintf (stderr,"\nERR:AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
          ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
  exit (1);

notAnInteger:
  fprintf (stderr,"\nERR:AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
          ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
  exit (1);

noValueForOption:
  fprintf (stderr,"\nERR:AFB-daemon option [--%s] don't take value\n\n"
          ,gnuOptions[optionIndex].name);
  exit (1);

badMode:
  fprintf (stderr,"\nERR:AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
          ,gnuOptions[optionIndex].name);
  exit (1);
}

/*---------------------------------------------------------
 | main
 |   Parse option and launch action
 +--------------------------------------------------------- */

int main(int argc, char *argv[])  {
  AFB_session    *session;
  char*          programName = argv [0];
  int            consoleFD;
  int            pid, status;

  // ------------- Build session handler & init config -------
  session = configInit ();
  parse_arguments(argc, argv, session);
  initPlugins(session);

  // ------------------ sanity check ----------------------------------------
  if  ((session->background) && (session->foreground)) {
    fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
     exit (1);
  }

  // ------------------ Some useful default values -------------------------
  if  ((session->background == 0) && (session->foreground == 0)) session->foreground=1;

  // open syslog if ever needed
  openlog("AFB-log", 0, LOG_DAEMON);

  // -------------- Try to kill any previous process if asked ---------------------
  if (session->killPrevious) {
    pid = readPidFile (session->config);  // enforce commandline option
    switch (pid) {
    case -1:
      fprintf (stderr, "%s ERR:main --kill ignored no PID file [%s]\n",configTime(), session->config->pidfile);
      break;
    case 0:
      fprintf (stderr, "%s ERR:main --kill ignored no active AFB process\n",configTime());
      break;
    default:
      status = kill (pid,SIGINT );
      if (status == 0) {
	     if (verbose) printf ("%s INF:main signal INTR sent to pid:%d \n", configTime(), pid);
      } else {
         // try kill -9
         status = kill (pid,9);
         if (status != 0)  fprintf (stderr, "%s ERR:main failled to killed pid=%d \n",configTime(), pid);
      }
    } // end switch pid

    if (session->killPrevious >= 2) goto normalExit;
  } // end killPrevious


  // ------------------ clean exit on CTR-C signal ------------------------
  if (signal (SIGINT, signalQuit) == SIG_ERR) {
    fprintf (stderr, "%s Quit Signal received.",configTime());
    return 1;
  }

  // save exitPoint context when returning from longjmp closeSession and exit
  status = setjmp (exitPoint); // return !+ when coming from longjmp
  if (status != 0) {
    if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
    closeSession (session);
    goto exitOnSignal;
  }

  // let's run this program with a low priority
  status=nice (20);

  // ------------------ Finaly Process Commands -----------------------------
   // if --save then store config on disk upfront
    if (session->config->setuid) {
        int err;
        struct passwd *passwd;
        passwd=getpwnam(session->config->setuid);
        
        if (passwd == NULL) goto errorSetuid;
        
        err = setuid(passwd->pw_uid);
        if (err) goto errorSetuid;
    }

    // let's not take the risk to run as ROOT
    //if (getuid() == 0)  goto errorNoRoot;

    // check session dir and create if it does not exist
    if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
    if (verbose) fprintf (stderr, "AFB:notice Init config done\n");



    // ---- run in foreground mode --------------------
    if (session->foreground) {

        if (verbose) fprintf (stderr,"AFB:notice Foreground mode\n");

        // write a pid file for --kill-previous and --raise-debug option
        status = writePidFile (session->config, getpid());
        if (status == -1) goto errorPidFile;

        // enter listening loop in foreground
        listenLoop(session);
        goto exitInitLoop;
  } // end foreground


  // --------- run in background mode -----------
  if (session->background) {

       // if (status != 0) goto errorCommand;
      if (verbose) printf ("AFB: Entering background mode\n");

      // open /dev/console to redirect output messAFBes
      consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
      if (consoleFD < 0) goto errConsole;

      // fork process when running background mode
      pid = fork ();

      // son process get all data in standalone mode
      if (pid == 0) {

 	     printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
 	     if (verbose) printf ("AFB:info use '%s --restart --rootdir=%s # [--pidfile=%s] to restart daemon\n", programName,session->config->rootdir, session->config->pidfile);

         // redirect default I/O on console
         close (2); status=dup(consoleFD);  // redirect stderr
         close (1); status=dup(consoleFD);  // redirect stdout
         close (0);           // no need for stdin
         close (consoleFD);

    	 setsid();   // allow father process to fully exit
	     sleep (2);  // allow main to leave and release port

         fprintf (stderr, "----------------------------\n");
         fprintf (stderr, "%s INF:main background pid=%d\n", configTime(), getpid());
         fflush  (stderr);

         // if everything look OK then look forever
         syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");

         // should normally never return from this loop
         listenLoop(session);
         syslog (LOG_ERR, "AFB:FAIL background infinite loop exited check [%s]\n", session->config->console);

         goto exitInitLoop;
      }

      // if fail nothing much to do
      if (pid == -1) goto errorFork;

      // fork worked and we are in father process
      status = writePidFile (session->config, pid);
      if (status == -1) goto errorPidFile;

      // we are in father process, we don't need this one
      _exit (0);

  } // end background-foreground

normalExit:
  closeSession (session);   // try to close everything before leaving
  if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
  exit(0);

// ------------- Fatal ERROR display error and quit  -------------
errorSetuid:
  fprintf (stderr,"\nERR:AFB-daemon Failed to change UID to username=[%s]\n\n", session->config->setuid);
  exit (1);
  
//errorNoRoot:
//  fprintf (stderr,"\nERR:AFB-daemon Not allow to run as root [use --seteuid=username option]\n\n");
//  exit (1);

errorPidFile:
  fprintf (stderr,"\nERR:AFB-daemon Failed to write pid file [%s]\n\n", session->config->pidfile);
  exit (1);

errorFork:
  fprintf (stderr,"\nERR:AFB-daemon Failed to fork son process\n\n");
  exit (1);

exitOnSignal:
  fprintf (stderr,"\n%s INF:AFB-daemon pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
                 ,configTime(), getpid());
  exit (1);

errConsole:
  fprintf (stderr,"\nERR:AFB-daemon cannot open /dev/console (use --foreground)\n\n");
  exit (1);

errSessiondir:
  fprintf (stderr,"\nERR:AFB-daemon cannot read/write session dir\n\n");
  exit (1);

exitInitLoop:
  // try to unlink pid file if any
  if (session->background && session->config->pidfile != NULL)  unlink (session->config->pidfile);
  exit (1);

}
ip the duplicated mode. // break; } } if (ValidIndex == ValidCount) { NewModeBuffer[ValidCount].Columns = ModeBuffer[Index].Columns; NewModeBuffer[ValidCount].Rows = ModeBuffer[Index].Rows; NewModeBuffer[ValidCount].GopWidth = HorizontalResolution; NewModeBuffer[ValidCount].GopHeight = VerticalResolution; NewModeBuffer[ValidCount].GopModeNumber = GopModeNumber; NewModeBuffer[ValidCount].DeltaX = (HorizontalResolution - (NewModeBuffer[ValidCount].Columns * EFI_GLYPH_WIDTH)) >> 1; NewModeBuffer[ValidCount].DeltaY = (VerticalResolution - (NewModeBuffer[ValidCount].Rows * EFI_GLYPH_HEIGHT)) >> 1; ValidCount++; } } DEBUG_CODE ( for (Index = 0; Index < ValidCount; Index++) { DEBUG ((EFI_D_INFO, "Graphics - Mode %d, Column = %d, Row = %d\n", Index, NewModeBuffer[Index].Columns, NewModeBuffer[Index].Rows)); } ); // // Return valid mode count and mode information buffer. // *TextModeCount = ValidCount; *TextModeData = NewModeBuffer; return EFI_SUCCESS; } /** Start this driver on Controller by opening Graphics Output protocol or UGA Draw protocol, and installing Simple Text Out protocol on Controller. (UGA Draw protocol could be skipped if PcdUgaConsumeSupport is set to FALSE.) @param This Protocol instance pointer. @param Controller Handle of device to bind driver to @param RemainingDevicePath Optional parameter use to pick a specific child device to start. @retval EFI_SUCCESS This driver is added to Controller. @retval other This driver does not support this device. **/ EFI_STATUS EFIAPI GraphicsConsoleControllerDriverStart ( IN EFI_DRIVER_BINDING_PROTOCOL *This, IN EFI_HANDLE Controller, IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { EFI_STATUS Status; GRAPHICS_CONSOLE_DEV *Private; UINT32 HorizontalResolution; UINT32 VerticalResolution; UINT32 ColorDepth; UINT32 RefreshRate; UINT32 ModeIndex; UINTN MaxMode; UINT32 ModeNumber; EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE *Mode; UINTN SizeOfInfo; EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info; INT32 PreferMode; INT32 Index; UINTN Column; UINTN Row; UINTN DefaultColumn; UINTN DefaultRow; ModeNumber = 0; // // Initialize the Graphics Console device instance // Private = AllocateCopyPool ( sizeof (GRAPHICS_CONSOLE_DEV), &mGraphicsConsoleDevTemplate ); if (Private == NULL) { return EFI_OUT_OF_RESOURCES; } Private->SimpleTextOutput.Mode = &(Private->SimpleTextOutputMode); Status = gBS->OpenProtocol ( Controller, &gEfiGraphicsOutputProtocolGuid, (VOID **) &Private->GraphicsOutput, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER ); if (EFI_ERROR(Status) && FeaturePcdGet (PcdUgaConsumeSupport)) { Status = gBS->OpenProtocol ( Controller, &gEfiUgaDrawProtocolGuid, (VOID **) &Private->UgaDraw, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER ); } if (EFI_ERROR (Status)) { goto Error; } HorizontalResolution = PcdGet32 (PcdVideoHorizontalResolution); VerticalResolution = PcdGet32 (PcdVideoVerticalResolution); if (Private->GraphicsOutput != NULL) { // // The console is build on top of Graphics Output Protocol, find the mode number // for the user-defined mode; if there are multiple video devices, // graphic console driver will set all the video devices to the same mode. // if ((HorizontalResolution == 0x0) || (VerticalResolution == 0x0)) { // // Find the highest resolution which GOP supports. // MaxMode = Private->GraphicsOutput->Mode->MaxMode; for (ModeIndex = 0; ModeIndex < MaxMode; ModeIndex++) { Status = Private->GraphicsOutput->QueryMode ( Private->GraphicsOutput, ModeIndex, &SizeOfInfo, &Info ); if (!EFI_ERROR (Status)) { if ((Info->HorizontalResolution > HorizontalResolution) || ((Info->HorizontalResolution == HorizontalResolution) && (Info->VerticalResolution > VerticalResolution))) { HorizontalResolution = Info->HorizontalResolution; VerticalResolution = Info->VerticalResolution; ModeNumber = ModeIndex; } FreePool (Info); } } if ((HorizontalResolution == 0x0) || (VerticalResolution == 0x0)) { Status = EFI_UNSUPPORTED; goto Error; } } else { // // Use user-defined resolution // Status = CheckModeSupported ( Private->GraphicsOutput, HorizontalResolution, VerticalResolution, &ModeNumber ); if (EFI_ERROR (Status)) { // // if not supporting current mode, try 800x600 which is required by UEFI/EFI spec // HorizontalResolution = 800; VerticalResolution = 600; Status = CheckModeSupported ( Private->GraphicsOutput, HorizontalResolution, VerticalResolution, &ModeNumber ); Mode = Private->GraphicsOutput->Mode; if (EFI_ERROR (Status) && Mode->MaxMode != 0) { // // Set default mode failed or device don't support default mode, then get the current mode information // HorizontalResolution = Mode->Info->HorizontalResolution; VerticalResolution = Mode->Info->VerticalResolution; ModeNumber = Mode->Mode; } } } if (ModeNumber != Private->GraphicsOutput->Mode->Mode) { // // Current graphics mode is not set or is not set to the mode which we has found, // set the new graphic mode. // Status = Private->GraphicsOutput->SetMode (Private->GraphicsOutput, ModeNumber); if (EFI_ERROR (Status)) { // // The mode set operation failed // goto Error; } } } else if (FeaturePcdGet (PcdUgaConsumeSupport)) { // // At first try to set user-defined resolution // ColorDepth = 32; RefreshRate = 60; Status = Private->UgaDraw->SetMode ( Private->UgaDraw, HorizontalResolution, VerticalResolution, ColorDepth, RefreshRate ); if (EFI_ERROR (Status)) { // // Try to set 800*600 which is required by UEFI/EFI spec // Status = Private->UgaDraw->SetMode ( Private->UgaDraw, 800, 600, ColorDepth, RefreshRate ); if (EFI_ERROR (Status)) { Status = Private->UgaDraw->GetMode ( Private->UgaDraw, &HorizontalResolution, &VerticalResolution, &ColorDepth, &RefreshRate ); if (EFI_ERROR (Status)) { goto Error; } } } } DEBUG ((EFI_D_INFO, "GraphicsConsole video resolution %d x %d\n", HorizontalResolution, VerticalResolution)); // // Initialize the mode which GraphicsConsole supports. // Status = InitializeGraphicsConsoleTextMode ( HorizontalResolution, VerticalResolution, ModeNumber, &MaxMode, &Private->ModeData ); if (EFI_ERROR (Status)) { goto Error; } // // Update the maximum number of modes // Private->SimpleTextOutputMode.MaxMode = (INT32) MaxMode; // // Initialize the Mode of graphics console devices // PreferMode = -1; DefaultColumn = PcdGet32 (PcdConOutColumn); DefaultRow = PcdGet32 (PcdConOutRow); Column = 0; Row = 0; for (Index = 0; Index < (INT32)MaxMode; Index++) { if (DefaultColumn != 0 && DefaultRow != 0) { if ((Private->ModeData[Index].Columns == DefaultColumn) && (Private->ModeData[Index].Rows == DefaultRow)) { PreferMode = Index; break; } } else { if ((Private->ModeData[Index].Columns > Column) && (Private->ModeData[Index].Rows > Row)) { Column = Private->ModeData[Index].Columns; Row = Private->ModeData[Index].Rows; PreferMode = Index; } } } Private->SimpleTextOutput.Mode->Mode = (INT32)PreferMode; DEBUG ((DEBUG_INFO, "Graphics Console Started, Mode: %d\n", PreferMode)); // // Install protocol interfaces for the Graphics Console device. // Status = gBS->InstallMultipleProtocolInterfaces ( &Controller, &gEfiSimpleTextOutProtocolGuid, &Private->SimpleTextOutput, NULL ); Error: if (EFI_ERROR (Status)) { // // Close the GOP and UGA Draw Protocol // if (Private->GraphicsOutput != NULL) { gBS->CloseProtocol ( Controller, &gEfiGraphicsOutputProtocolGuid, This->DriverBindingHandle, Controller ); } else if (FeaturePcdGet (PcdUgaConsumeSupport)) { gBS->CloseProtocol ( Controller, &gEfiUgaDrawProtocolGuid, This->DriverBindingHandle, Controller ); } if (Private->LineBuffer != NULL) { FreePool (Private->LineBuffer); } if (Private->ModeData != NULL) { FreePool (Private->ModeData); } // // Free private data // FreePool (Private); } return Status; } /** Stop this driver on Controller by removing Simple Text Out protocol and closing the Graphics Output Protocol or UGA Draw protocol on Controller. (UGA Draw protocol could be skipped if PcdUgaConsumeSupport is set to FALSE.) @param This Protocol instance pointer. @param Controller Handle of device to stop driver on @param NumberOfChildren Number of Handles in ChildHandleBuffer. If number of children is zero stop the entire bus driver. @param ChildHandleBuffer List of Child Handles to Stop. @retval EFI_SUCCESS This driver is removed Controller. @retval EFI_NOT_STARTED Simple Text Out protocol could not be found the Controller. @retval other This driver was not removed from this device. **/ EFI_STATUS EFIAPI GraphicsConsoleControllerDriverStop ( IN EFI_DRIVER_BINDING_PROTOCOL *This, IN EFI_HANDLE Controller, IN UINTN NumberOfChildren, IN EFI_HANDLE *ChildHandleBuffer ) { EFI_STATUS Status; EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *SimpleTextOutput; GRAPHICS_CONSOLE_DEV *Private; Status = gBS->OpenProtocol ( Controller, &gEfiSimpleTextOutProtocolGuid, (VOID **) &SimpleTextOutput, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL ); if (EFI_ERROR (Status)) { return EFI_NOT_STARTED; } Private = GRAPHICS_CONSOLE_CON_OUT_DEV_FROM_THIS (SimpleTextOutput); Status = gBS->UninstallProtocolInterface ( Controller, &gEfiSimpleTextOutProtocolGuid, &Private->SimpleTextOutput ); if (!EFI_ERROR (Status)) { // // Close the GOP or UGA IO Protocol // if (Private->GraphicsOutput != NULL) { gBS->CloseProtocol ( Controller, &gEfiGraphicsOutputProtocolGuid, This->DriverBindingHandle, Controller ); } else if (FeaturePcdGet (PcdUgaConsumeSupport)) { gBS->CloseProtocol ( Controller, &gEfiUgaDrawProtocolGuid, This->DriverBindingHandle, Controller ); } if (Private->LineBuffer != NULL) { FreePool (Private->LineBuffer); } if (Private->ModeData != NULL) { FreePool (Private->ModeData); } // // Free our instance data // FreePool (Private); } return Status; } /** Check if the current specific mode supported the user defined resolution for the Graphics Console device based on Graphics Output Protocol. If yes, set the graphic devcice's current mode to this specific mode. @param GraphicsOutput Graphics Output Protocol instance pointer. @param HorizontalResolution User defined horizontal resolution @param VerticalResolution User defined vertical resolution. @param CurrentModeNumber Current specific mode to be check. @retval EFI_SUCCESS The mode is supported. @retval EFI_UNSUPPORTED The specific mode is out of range of graphics device supported. @retval other The specific mode does not support user defined resolution or failed to set the current mode to the specific mode on graphics device. **/ EFI_STATUS CheckModeSupported ( EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput, IN UINT32 HorizontalResolution, IN UINT32 VerticalResolution, OUT UINT32 *CurrentModeNumber ) { UINT32 ModeNumber; EFI_STATUS Status; UINTN SizeOfInfo; EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info; UINT32 MaxMode; Status = EFI_SUCCESS; MaxMode = GraphicsOutput->Mode->MaxMode; for (ModeNumber = 0; ModeNumber < MaxMode; ModeNumber++) { Status = GraphicsOutput->QueryMode ( GraphicsOutput, ModeNumber, &SizeOfInfo, &Info ); if (!EFI_ERROR (Status)) { if ((Info->HorizontalResolution == HorizontalResolution) && (Info->VerticalResolution == VerticalResolution)) { if ((GraphicsOutput->Mode->Info->HorizontalResolution == HorizontalResolution) && (GraphicsOutput->Mode->Info->VerticalResolution == VerticalResolution)) { // // If video device has been set to this mode, we do not need to SetMode again // FreePool (Info); break; } else { Status = GraphicsOutput->SetMode (GraphicsOutput, ModeNumber); if (!EFI_ERROR (Status)) { FreePool (Info); break; } } } FreePool (Info); } } if (ModeNumber == GraphicsOutput->Mode->MaxMode) { Status = EFI_UNSUPPORTED; } *CurrentModeNumber = ModeNumber; return Status; } /** Locate HII Database protocol and HII Font protocol. @retval EFI_SUCCESS HII Database protocol and HII Font protocol are located successfully. @return other Failed to locate HII Database protocol or HII Font protocol. **/ EFI_STATUS EfiLocateHiiProtocol ( VOID ) { EFI_STATUS Status; Status = gBS->LocateProtocol (&gEfiHiiDatabaseProtocolGuid, NULL, (VOID **) &mHiiDatabase); if (EFI_ERROR (Status)) { return Status; } Status = gBS->LocateProtocol (&gEfiHiiFontProtocolGuid, NULL, (VOID **) &mHiiFont); return Status; } // // Body of the STO functions // /** Reset the text output device hardware and optionally run diagnostics. Implements SIMPLE_TEXT_OUTPUT.Reset(). If ExtendeVerification is TRUE, then perform dependent Graphics Console device reset, and set display mode to mode 0. If ExtendedVerification is FALSE, only set display mode to mode 0. @param This Protocol instance pointer. @param ExtendedVerification Indicates that the driver may perform a more exhaustive verification operation of the device during reset. @retval EFI_SUCCESS The text output device was reset. @retval EFI_DEVICE_ERROR The text output device is not functioning correctly and could not be reset. **/ EFI_STATUS EFIAPI GraphicsConsoleConOutReset ( IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This, IN BOOLEAN ExtendedVerification ) { EFI_STATUS Status; Status = This->SetMode (This, 0); if (EFI_ERROR (Status)) { return Status; } Status = This->SetAttribute (This, EFI_TEXT_ATTR (This->Mode->Attribute & 0x0F, EFI_BACKGROUND_BLACK)); return Status; } /** Write a Unicode string to the output device. Implements SIMPLE_TEXT_OUTPUT.OutputString(). The Unicode string will be converted to Glyphs and will be sent to the Graphics Console. @param This Protocol instance pointer. @param WString The NULL-terminated Unicode string to be displayed on the output device(s). All output devices must also support the Unicode drawing defined in this file. @retval EFI_SUCCESS The string was output to the device. @retval EFI_DEVICE_ERROR The device reported an error while attempting to output the text. @retval EFI_UNSUPPORTED The output device's mode is not currently in a defined text mode. @retval EFI_WARN_UNKNOWN_GLYPH This warning code indicates that some of the characters in the Unicode string could not be rendered and were skipped. **/ EFI_STATUS EFIAPI GraphicsConsoleConOutOutputString ( IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This, IN CHAR16 *WString ) { GRAPHICS_CONSOLE_DEV *Private; EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; EFI_UGA_DRAW_PROTOCOL *UgaDraw; INTN Mode; UINTN MaxColumn; UINTN MaxRow; UINTN Width; UINTN Height; UINTN Delta; EFI_STATUS Status; BOOLEAN Warning; EFI_GRAPHICS_OUTPUT_BLT_PIXEL Foreground; EFI_GRAPHICS_OUTPUT_BLT_PIXEL Background; UINTN DeltaX; UINTN DeltaY; UINTN Count; UINTN Index; INT32 OriginAttribute; EFI_TPL OldTpl; if (This->Mode->Mode == -1) { // // If current mode is not valid, return error. // return EFI_UNSUPPORTED; } Status = EFI_SUCCESS; OldTpl = gBS->RaiseTPL (TPL_NOTIFY); // // Current mode // Mode = This->Mode->Mode; Private = GRAPHICS_CONSOLE_CON_OUT_DEV_FROM_THIS (This); GraphicsOutput = Private->GraphicsOutput; UgaDraw = Private->UgaDraw; MaxColumn = Private->ModeData[Mode].Columns; MaxRow = Private->ModeData[Mode].Rows; DeltaX = (UINTN) Private->ModeData[Mode].DeltaX; DeltaY = (UINTN) Private->ModeData[Mode].DeltaY; Width = MaxColumn * EFI_GLYPH_WIDTH; Height = (MaxRow - 1) * EFI_GLYPH_HEIGHT; Delta = Width * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL); // // The Attributes won't change when during the time OutputString is called // GetTextColors (This, &Foreground, &Background); FlushCursor (This); Warning = FALSE; // // Backup attribute // OriginAttribute = This->Mode->Attribute; while (*WString != L'\0') { if (*WString == CHAR_BACKSPACE) { // // If the cursor is at the left edge of the display, then move the cursor // one row up. // if (This->Mode->CursorColumn == 0 && This->Mode->CursorRow > 0) { This->Mode->CursorRow--; This->Mode->CursorColumn = (INT32) (MaxColumn - 1); This->OutputString (This, SpaceStr); FlushCursor (This); This->Mode->CursorRow--; This->Mode->CursorColumn = (INT32) (MaxColumn - 1); } else if (This->Mode->CursorColumn > 0) { // // If the cursor is not at the left edge of the display, then move the cursor // left one column. // This->Mode->CursorColumn--; This->OutputString (This, SpaceStr); FlushCursor (This); This->Mode->CursorColumn--; } WString++; } else if (*WString == CHAR_LINEFEED) { // // If the cursor is at the bottom of the display, then scroll the display one // row, and do not update the cursor position. Otherwise, move the cursor // down one row. // if (This->Mode->CursorRow == (INT32) (MaxRow - 1)) { if (GraphicsOutput != NULL) { // // Scroll Screen Up One Row // GraphicsOutput->Blt ( GraphicsOutput, NULL, EfiBltVideoToVideo, DeltaX, DeltaY + EFI_GLYPH_HEIGHT, DeltaX, DeltaY, Width, Height, Delta ); // // Print Blank Line at last line // GraphicsOutput->Blt ( GraphicsOutput, &Background, EfiBltVideoFill, 0, 0, DeltaX, DeltaY + Height, Width, EFI_GLYPH_HEIGHT, Delta ); } else if (FeaturePcdGet (PcdUgaConsumeSupport)) { // // Scroll Screen Up One Row // UgaDraw->Blt ( UgaDraw, NULL, EfiUgaVideoToVideo, DeltaX, DeltaY + EFI_GLYPH_HEIGHT, DeltaX, DeltaY, Width, Height, Delta ); // // Print Blank Line at last line // UgaDraw->Blt ( UgaDraw, (EFI_UGA_PIXEL *) (UINTN) &Background, EfiUgaVideoFill, 0, 0, DeltaX, DeltaY + Height, Width, EFI_GLYPH_HEIGHT, Delta ); } } else { This->Mode->CursorRow++; } WString++; } else if (*WString == CHAR_CARRIAGE_RETURN) { // // Move the cursor to the beginning of the current row. // This->Mode->CursorColumn = 0; WString++; } else if (*WString == WIDE_CHAR) { This->Mode->Attribute |= EFI_WIDE_ATTRIBUTE; WString++; } else if (*WString == NARROW_CHAR) { This->Mode->Attribute &= (~ (UINT32) EFI_WIDE_ATTRIBUTE); WString++; } else { // // Print the character at the current cursor position and move the cursor // right one column. If this moves the cursor past the right edge of the // display, then the line should wrap to the beginning of the next line. This // is equivalent to inserting a CR and an LF. Note that if the cursor is at the // bottom of the display, and the line wraps, then the display will be scrolled // one line. // If wide char is going to be displayed, need to display one character at a time // Or, need to know the display length of a certain string. // // Index is used to determine how many character width units (wide = 2, narrow = 1) // Count is used to determine how many characters are used regardless of their attributes // for (Count = 0, Index = 0; (This->Mode->CursorColumn + Index) < MaxColumn; Count++, Index++) { if (WString[Count] == CHAR_NULL || WString[Count] == CHAR_BACKSPACE || WString[Count] == CHAR_LINEFEED || WString[Count] == CHAR_CARRIAGE_RETURN || WString[Count] == WIDE_CHAR || WString[Count] == NARROW_CHAR) { break; } // // Is the wide attribute on? // if ((This->Mode->Attribute & EFI_WIDE_ATTRIBUTE) != 0) { // // If wide, add one more width unit than normal since we are going to increment at the end of the for loop // Index++; // // This is the end-case where if we are at column 79 and about to print a wide character // We should prevent this from happening because we will wrap inappropriately. We should // not print this character until the next line. // if ((This->Mode->CursorColumn + Index + 1) > MaxColumn) { Index++; break; } } } Status = DrawUnicodeWeightAtCursorN (This, WString, Count); if (EFI_ERROR (Status)) { Warning = TRUE; } // // At the end of line, output carriage return and line feed // WString += Count; This->Mode->CursorColumn += (INT32) Index; if (This->Mode->CursorColumn > (INT32) MaxColumn) { This->Mode->CursorColumn -= 2; This->OutputString (This, SpaceStr); } if (This->Mode->CursorColumn >= (INT32) MaxColumn) { FlushCursor (This); This->OutputString (This, mCrLfString); FlushCursor (This); } } } This->Mode->Attribute = OriginAttribute; FlushCursor (This); if (Warning) { Status = EFI_WARN_UNKNOWN_GLYPH; } gBS->RestoreTPL (OldTpl); return Status; } /** Verifies that all characters in a Unicode string can be output to the target device. Implements SIMPLE_TEXT_OUTPUT.TestString(). If one of the characters in the *Wstring is neither valid valid Unicode drawing characters, not ASCII code, then this function will return EFI_UNSUPPORTED @param This Protocol instance pointer. @param WString The NULL-terminated Unicode string to be examined for the output device(s). @retval EFI_SUCCESS The device(s) are capable of rendering the output string. @retval EFI_UNSUPPORTED Some of the characters in the Unicode string cannot be rendered by one or more of the output devices mapped by the EFI handle. **/ EFI_STATUS EFIAPI GraphicsConsoleConOutTestString ( IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This, IN CHAR16 *WString ) { EFI_STATUS Status; UINT16 Count; EFI_IMAGE_OUTPUT *Blt; Blt = NULL; Count = 0; while (WString[Count] != 0) { Status = mHiiFont->GetGlyph ( mHiiFont, WString[Count], NULL, &Blt, NULL ); if (Blt != NULL) { FreePool (Blt); Blt = NULL; } Count++; if (EFI_ERROR (Status)) { return EFI_UNSUPPORTED; } } return EFI_SUCCESS; } /** Returns information for an available text mode that the output device(s) supports Implements SIMPLE_TEXT_OUTPUT.QueryMode(). It returnes information for an available text mode that the Graphics Console supports. In this driver,we only support text mode 80x25, which is defined as mode 0. @param This Protocol instance pointer. @param ModeNumber The mode number to return information on. @param Columns The returned columns of the requested mode. @param Rows The returned rows of the requested mode. @retval EFI_SUCCESS The requested mode information is returned. @retval EFI_UNSUPPORTED The mode number is not valid. **/ EFI_STATUS EFIAPI GraphicsConsoleConOutQueryMode ( IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This, IN UINTN ModeNumber, OUT UINTN *Columns, OUT UINTN *Rows ) { GRAPHICS_CONSOLE_DEV *Private; EFI_STATUS Status; EFI_TPL OldTpl; if (ModeNumber >= (UINTN) This->Mode->MaxMode) { return EFI_UNSUPPORTED; } OldTpl = gBS->RaiseTPL (TPL_NOTIFY); Status = EFI_SUCCESS; Private = GRAPHICS_CONSOLE_CON_OUT_DEV_FROM_THIS (This); *Columns = Private->ModeData[ModeNumber].Columns; *Rows = Private->ModeData[ModeNumber].Rows; if (*Columns <= 0 || *Rows <= 0) { Status = EFI_UNSUPPORTED; goto Done; } Done: gBS->RestoreTPL (OldTpl); return Status; } /** Sets the output device(s) to a specified mode. Implements SIMPLE_TEXT_OUTPUT.SetMode(). Set the Graphics Console to a specified mode. In this driver, we only support mode 0. @param This Protocol instance pointer. @param ModeNumber The text mode to set. @retval EFI_SUCCESS The requested text mode is set. @retval EFI_DEVICE_ERROR The requested text mode cannot be set because of Graphics Console device error. @retval EFI_UNSUPPORTED The text mode number is not valid. **/ EFI_STATUS EFIAPI GraphicsConsoleConOutSetMode ( IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This, IN UINTN ModeNumber ) { EFI_STATUS Status; GRAPHICS_CONSOLE_DEV *Private; GRAPHICS_CONSOLE_MODE_DATA *ModeData; EFI_GRAPHICS_OUTPUT_BLT_PIXEL *NewLineBuffer; UINT32 HorizontalResolution; UINT32 VerticalResolution; EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; EFI_UGA_DRAW_PROTOCOL *UgaDraw; UINT32 ColorDepth; UINT32 RefreshRate; EFI_TPL OldTpl; OldTpl = gBS->RaiseTPL (TPL_NOTIFY); Private = GRAPHICS_CONSOLE_CON_OUT_DEV_FROM_THIS (This); GraphicsOutput = Private->GraphicsOutput; UgaDraw = Private->UgaDraw; // // Make sure the requested mode number is supported // if (ModeNumber >= (UINTN) This->Mode->MaxMode) { Status = EFI_UNSUPPORTED; goto Done; } ModeData = &(Private->ModeData[ModeNumber]); if (ModeData->Columns <= 0 && ModeData->Rows <= 0) { Status = EFI_UNSUPPORTED; goto Done; } // // If the mode has been set at least one other time, then LineBuffer will not be NULL // if (Private->LineBuffer != NULL) { // // If the new mode is the same as the old mode, then just return EFI_SUCCESS // if ((INT32) ModeNumber == This->Mode->Mode) { // // Clear the current text window on the current graphics console // This->ClearScreen (This); Status = EFI_SUCCESS; goto Done; } // // Otherwise, the size of the text console and/or the GOP/UGA mode will be changed, // so erase the cursor, and free the LineBuffer for the current mode // FlushCursor (This); FreePool (Private->LineBuffer); } // // Attempt to allocate a line buffer for the requested mode number // NewLineBuffer = AllocatePool (sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL) * ModeData->Columns * EFI_GLYPH_WIDTH * EFI_GLYPH_HEIGHT); if (NewLineBuffer == NULL) { // // The new line buffer could not be allocated, so return an error. // No changes to the state of the current console have been made, so the current console is still valid // Status = EFI_OUT_OF_RESOURCES; goto Done; } // // Assign the current line buffer to the newly allocated line buffer // Private->LineBuffer = NewLineBuffer; if (GraphicsOutput != NULL) { if (ModeData->GopModeNumber != GraphicsOutput->Mode->Mode) { // // Either no graphics mode is currently set, or it is set to the wrong resolution, so set the new graphics mode // Status = GraphicsOutput->SetMode (GraphicsOutput, ModeData->GopModeNumber); if (EFI_ERROR (Status)) { // // The mode set operation failed // goto Done; } } else { // // The current graphics mode is correct, so simply clear the entire display // Status = GraphicsOutput->Blt ( GraphicsOutput, &mGraphicsEfiColors[0], EfiBltVideoFill, 0, 0, 0, 0, ModeData->GopWidth, ModeData->GopHeight, 0 ); } } else if (FeaturePcdGet (PcdUgaConsumeSupport)) { // // Get the current UGA Draw mode information // Status = UgaDraw->GetMode ( UgaDraw, &HorizontalResolution, &VerticalResolution, &ColorDepth, &RefreshRate ); if (EFI_ERROR (Status) || HorizontalResolution != ModeData->GopWidth || VerticalResolution != ModeData->GopHeight) { // // Either no graphics mode is currently set, or it is set to the wrong resolution, so set the new graphics mode // Status = UgaDraw->SetMode ( UgaDraw, ModeData->GopWidth, ModeData->GopHeight, 32, 60 ); if (EFI_ERROR (Status)) { // // The mode set operation failed // goto Done; } } else { // // The current graphics mode is correct, so simply clear the entire display // Status = UgaDraw->Blt ( UgaDraw, (EFI_UGA_PIXEL *) (UINTN) &mGraphicsEfiColors[0], EfiUgaVideoFill, 0, 0, 0, 0, ModeData->GopWidth, ModeData->GopHeight, 0 ); } } // // The new mode is valid, so commit the mode change // This->Mode->Mode = (INT32) ModeNumber; // // Move the text cursor to the upper left hand corner of the display and flush it // This->Mode->CursorColumn = 0; This->Mode->CursorRow = 0; FlushCursor (This); Status = EFI_SUCCESS; Done: gBS->RestoreTPL (OldTpl); return Status; } /** Sets the background and foreground colors for the OutputString () and ClearScreen () functions. Implements SIMPLE_TEXT_OUTPUT.SetAttribute(). @param This Protocol instance pointer. @param Attribute The attribute to set. Bits 0..3 are the foreground color, and bits 4..6 are the background color. All other bits are undefined and must be zero. @retval EFI_SUCCESS The requested attribute is set. @retval EFI_DEVICE_ERROR The requested attribute cannot be set due to Graphics Console port error. @retval EFI_UNSUPPORTED The attribute requested is not defined. **/ EFI_STATUS EFIAPI GraphicsConsoleConOutSetAttribute ( IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This, IN UINTN Attribute ) { EFI_TPL OldTpl; if ((Attribute | 0x7F) != 0x7F) { return EFI_UNSUPPORTED; } if ((INT32) Attribute == This->Mode->Attribute) { return EFI_SUCCESS; } OldTpl = gBS->RaiseTPL (TPL_NOTIFY); FlushCursor (This); This->Mode->Attribute = (INT32) Attribute; FlushCursor (This); gBS->RestoreTPL (OldTpl); return EFI_SUCCESS; } /** Clears the output device(s) display to the currently selected background color. Implements SIMPLE_TEXT_OUTPUT.ClearScreen(). @param This Protocol instance pointer. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_DEVICE_ERROR The device had an error and could not complete the request. @retval EFI_UNSUPPORTED The output device is not in a valid text mode. **/ EFI_STATUS EFIAPI GraphicsConsoleConOutClearScreen ( IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This ) { EFI_STATUS Status; GRAPHICS_CONSOLE_DEV *Private; GRAPHICS_CONSOLE_MODE_DATA *ModeData; EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; EFI_UGA_DRAW_PROTOCOL *UgaDraw; EFI_GRAPHICS_OUTPUT_BLT_PIXEL Foreground; EFI_GRAPHICS_OUTPUT_BLT_PIXEL Background; EFI_TPL OldTpl; if (This->Mode->Mode == -1) { // // If current mode is not valid, return error. // return EFI_UNSUPPORTED; } OldTpl = gBS->RaiseTPL (TPL_NOTIFY); Private = GRAPHICS_CONSOLE_CON_OUT_DEV_FROM_THIS (This); GraphicsOutput = Private->GraphicsOutput; UgaDraw = Private->UgaDraw; ModeData = &(Private->ModeData[This->Mode->Mode]); GetTextColors (This, &Foreground, &Background); if (GraphicsOutput != NULL) { Status = GraphicsOutput->Blt ( GraphicsOutput, &Background, EfiBltVideoFill, 0, 0, 0, 0, ModeData->GopWidth, ModeData->GopHeight, 0 ); } else if (FeaturePcdGet (PcdUgaConsumeSupport)) { Status = UgaDraw->Blt ( UgaDraw, (EFI_UGA_PIXEL *) (UINTN) &Background, EfiUgaVideoFill, 0, 0, 0, 0, ModeData->GopWidth, ModeData->GopHeight, 0 ); } else { Status = EFI_UNSUPPORTED; } This->Mode->CursorColumn = 0; This->Mode->CursorRow = 0; FlushCursor (This); gBS->RestoreTPL (OldTpl); return Status; } /** Sets the current coordinates of the cursor position. Implements SIMPLE_TEXT_OUTPUT.SetCursorPosition(). @param This Protocol instance pointer. @param Column The position to set the cursor to. Must be greater than or equal to zero and less than the number of columns and rows by QueryMode (). @param Row The position to set the cursor to. Must be greater than or equal to zero and less than the number of columns and rows by QueryMode (). @retval EFI_SUCCESS The operation completed successfully. @retval EFI_DEVICE_ERROR The device had an error and could not complete the request. @retval EFI_UNSUPPORTED The output device is not in a valid text mode, or the cursor position is invalid for the current mode. **/ EFI_STATUS EFIAPI GraphicsConsoleConOutSetCursorPosition ( IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This, IN UINTN Column, IN UINTN Row ) { GRAPHICS_CONSOLE_DEV *Private; GRAPHICS_CONSOLE_MODE_DATA *ModeData; EFI_STATUS Status; EFI_TPL OldTpl; if (This->Mode->Mode == -1) { // // If current mode is not valid, return error. // return EFI_UNSUPPORTED; } Status = EFI_SUCCESS; OldTpl = gBS->RaiseTPL (TPL_NOTIFY); Private = GRAPHICS_CONSOLE_CON_OUT_DEV_FROM_THIS (This); ModeData = &(Private->ModeData[This->Mode->Mode]); if ((Column >= ModeData->Columns) || (Row >= ModeData->Rows)) { Status = EFI_UNSUPPORTED; goto Done; } if ((This->Mode->CursorColumn == (INT32) Column) && (This->Mode->CursorRow == (INT32) Row)) { Status = EFI_SUCCESS; goto Done; } FlushCursor (This); This->Mode->CursorColumn = (INT32) Column; This->Mode->CursorRow = (INT32) Row; FlushCursor (This); Done: gBS->RestoreTPL (OldTpl); return Status; } /** Makes the cursor visible or invisible. Implements SIMPLE_TEXT_OUTPUT.EnableCursor(). @param This Protocol instance pointer. @param Visible If TRUE, the cursor is set to be visible, If FALSE, the cursor is set to be invisible. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_UNSUPPORTED The output device's mode is not currently in a defined text mode. **/ EFI_STATUS EFIAPI GraphicsConsoleConOutEnableCursor ( IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This, IN BOOLEAN Visible ) { EFI_TPL OldTpl; if (This->Mode->Mode == -1) { // // If current mode is not valid, return error. // return EFI_UNSUPPORTED; } OldTpl = gBS->RaiseTPL (TPL_NOTIFY); FlushCursor (This); This->Mode->CursorVisible = Visible; FlushCursor (This); gBS->RestoreTPL (OldTpl); return EFI_SUCCESS; } /** Gets Graphics Console devcie's foreground color and background color. @param This Protocol instance pointer. @param Foreground Returned text foreground color. @param Background Returned text background color. @retval EFI_SUCCESS It returned always. **/ EFI_STATUS GetTextColors ( IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This, OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Foreground, OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Background ) { INTN Attribute; Attribute = This->Mode->Attribute & 0x7F; *Foreground = mGraphicsEfiColors[Attribute & 0x0f]; *Background = mGraphicsEfiColors[Attribute >> 4]; return EFI_SUCCESS; } /** Draw Unicode string on the Graphics Console device's screen. @param This Protocol instance pointer. @param UnicodeWeight One Unicode string to be displayed. @param Count The count of Unicode string. @retval EFI_OUT_OF_RESOURCES If no memory resource to use. @retval EFI_UNSUPPORTED If no Graphics Output protocol and UGA Draw protocol exist. @retval EFI_SUCCESS Drawing Unicode string implemented successfully. **/ EFI_STATUS DrawUnicodeWeightAtCursorN ( IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This, IN CHAR16 *UnicodeWeight, IN UINTN Count ) { EFI_STATUS Status; GRAPHICS_CONSOLE_DEV *Private; EFI_IMAGE_OUTPUT *Blt; EFI_STRING String; EFI_FONT_DISPLAY_INFO *FontInfo; EFI_UGA_DRAW_PROTOCOL *UgaDraw; EFI_HII_ROW_INFO *RowInfoArray; UINTN RowInfoArraySize; Private = GRAPHICS_CONSOLE_CON_OUT_DEV_FROM_THIS (This); Blt = (EFI_IMAGE_OUTPUT *) AllocateZeroPool (sizeof (EFI_IMAGE_OUTPUT)); if (Blt == NULL) { return EFI_OUT_OF_RESOURCES; } Blt->Width = (UINT16) (Private->ModeData[This->Mode->Mode].GopWidth); Blt->Height = (UINT16) (Private->ModeData[This->Mode->Mode].GopHeight); String = AllocateCopyPool ((Count + 1) * sizeof (CHAR16), UnicodeWeight); if (String == NULL) { FreePool (Blt); return EFI_OUT_OF_RESOURCES; } // // Set the end character // *(String + Count) = L'\0'; FontInfo = (EFI_FONT_DISPLAY_INFO *) AllocateZeroPool (sizeof (EFI_FONT_DISPLAY_INFO)); if (FontInfo == NULL) { FreePool (Blt); FreePool (String); return EFI_OUT_OF_RESOURCES; } // // Get current foreground and background colors. // GetTextColors (This, &FontInfo->ForegroundColor, &FontInfo->BackgroundColor); if (Private->GraphicsOutput != NULL) { // // If Graphics Output protocol exists, using HII Font protocol to draw. // Blt->Image.Screen = Private->GraphicsOutput; Status = mHiiFont->StringToImage ( mHiiFont, EFI_HII_IGNORE_IF_NO_GLYPH | EFI_HII_DIRECT_TO_SCREEN | EFI_HII_IGNORE_LINE_BREAK, String, FontInfo, &Blt, This->Mode->CursorColumn * EFI_GLYPH_WIDTH + Private->ModeData[This->Mode->Mode].DeltaX, This->Mode->CursorRow * EFI_GLYPH_HEIGHT + Private->ModeData[This->Mode->Mode].DeltaY, NULL, NULL, NULL ); } else if (FeaturePcdGet (PcdUgaConsumeSupport)) { // // If Graphics Output protocol cannot be found and PcdUgaConsumeSupport enabled, // using UGA Draw protocol to draw. // ASSERT (Private->UgaDraw!= NULL); UgaDraw = Private->UgaDraw; Blt->Image.Bitmap = AllocateZeroPool (Blt->Width * Blt->Height * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL)); if (Blt->Image.Bitmap == NULL) { FreePool (Blt); FreePool (String); return EFI_OUT_OF_RESOURCES; } RowInfoArray = NULL; // // StringToImage only support blt'ing image to device using GOP protocol. If GOP is not supported in this platform, // we ask StringToImage to print the string to blt buffer, then blt to device using UgaDraw. // Status = mHiiFont->StringToImage ( mHiiFont, EFI_HII_IGNORE_IF_NO_GLYPH | EFI_HII_IGNORE_LINE_BREAK, String, FontInfo, &Blt, This->Mode->CursorColumn * EFI_GLYPH_WIDTH + Private->ModeData[This->Mode->Mode].DeltaX, This->Mode->CursorRow * EFI_GLYPH_HEIGHT + Private->ModeData[This->Mode->Mode].DeltaY, &RowInfoArray, &RowInfoArraySize, NULL ); if (!EFI_ERROR (Status)) { // // Line breaks are handled by caller of DrawUnicodeWeightAtCursorN, so the updated parameter RowInfoArraySize by StringToImage will // always be 1 or 0 (if there is no valid Unicode Char can be printed). ASSERT here to make sure. // ASSERT (RowInfoArraySize <= 1); Status = UgaDraw->Blt ( UgaDraw, (EFI_UGA_PIXEL *) Blt->Image.Bitmap, EfiUgaBltBufferToVideo, This->Mode->CursorColumn * EFI_GLYPH_WIDTH + Private->ModeData[This->Mode->Mode].DeltaX, (This->Mode->CursorRow) * EFI_GLYPH_HEIGHT + Private->ModeData[This->Mode->Mode].DeltaY, This->Mode->CursorColumn * EFI_GLYPH_WIDTH + Private->ModeData[This->Mode->Mode].DeltaX, (This->Mode->CursorRow) * EFI_GLYPH_HEIGHT + Private->ModeData[This->Mode->Mode].DeltaY, RowInfoArray[0].LineWidth, RowInfoArray[0].LineHeight, Blt->Width * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL) ); } FreePool (RowInfoArray); FreePool (Blt->Image.Bitmap); } else { Status = EFI_UNSUPPORTED; } if (Blt != NULL) { FreePool (Blt); } if (String != NULL) { FreePool (String); } if (FontInfo != NULL) { FreePool (FontInfo); } return Status; } /** Flush the cursor on the screen. If CursorVisible is FALSE, nothing to do and return directly. If CursorVisible is TRUE, i) If the cursor shows on screen, it will be erased. ii) If the cursor does not show on screen, it will be shown. @param This Protocol instance pointer. @retval EFI_SUCCESS The cursor is erased successfully. **/ EFI_STATUS FlushCursor ( IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This ) { GRAPHICS_CONSOLE_DEV *Private; EFI_SIMPLE_TEXT_OUTPUT_MODE *CurrentMode; INTN GlyphX; INTN GlyphY; EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; EFI_UGA_DRAW_PROTOCOL *UgaDraw; EFI_GRAPHICS_OUTPUT_BLT_PIXEL_UNION Foreground; EFI_GRAPHICS_OUTPUT_BLT_PIXEL_UNION Background; EFI_GRAPHICS_OUTPUT_BLT_PIXEL_UNION BltChar[EFI_GLYPH_HEIGHT][EFI_GLYPH_WIDTH]; UINTN PosX; UINTN PosY; CurrentMode = This->Mode; if (!CurrentMode->CursorVisible) { return EFI_SUCCESS; } Private = GRAPHICS_CONSOLE_CON_OUT_DEV_FROM_THIS (This); GraphicsOutput = Private->GraphicsOutput; UgaDraw = Private->UgaDraw; // // In this driver, only narrow character was supported. // // // Blt a character to the screen // GlyphX = (CurrentMode->CursorColumn * EFI_GLYPH_WIDTH) + Private->ModeData[CurrentMode->Mode].DeltaX; GlyphY = (CurrentMode->CursorRow * EFI_GLYPH_HEIGHT) + Private->ModeData[CurrentMode->Mode].DeltaY; if (GraphicsOutput != NULL) { GraphicsOutput->Blt ( GraphicsOutput, (EFI_GRAPHICS_OUTPUT_BLT_PIXEL *) BltChar, EfiBltVideoToBltBuffer, GlyphX, GlyphY, 0, 0, EFI_GLYPH_WIDTH, EFI_GLYPH_HEIGHT, EFI_GLYPH_WIDTH * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL) ); } else if (FeaturePcdGet (PcdUgaConsumeSupport)) { UgaDraw->Blt ( UgaDraw, (EFI_UGA_PIXEL *) (UINTN) BltChar, EfiUgaVideoToBltBuffer, GlyphX, GlyphY, 0, 0, EFI_GLYPH_WIDTH, EFI_GLYPH_HEIGHT, EFI_GLYPH_WIDTH * sizeof (EFI_UGA_PIXEL) ); } GetTextColors (This, &Foreground.Pixel, &Background.Pixel); // // Convert Monochrome bitmap of the Glyph to BltBuffer structure // for (PosY = 0; PosY < EFI_GLYPH_HEIGHT; PosY++) { for (PosX = 0; PosX < EFI_GLYPH_WIDTH; PosX++) { if ((mCursorGlyph.GlyphCol1[PosY] & (BIT0 << PosX)) != 0) { BltChar[PosY][EFI_GLYPH_WIDTH - PosX - 1].Raw ^= Foreground.Raw; } } } if (GraphicsOutput != NULL) { GraphicsOutput->Blt ( GraphicsOutput, (EFI_GRAPHICS_OUTPUT_BLT_PIXEL *) BltChar, EfiBltBufferToVideo, 0, 0, GlyphX, GlyphY, EFI_GLYPH_WIDTH, EFI_GLYPH_HEIGHT, EFI_GLYPH_WIDTH * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL) ); } else if (FeaturePcdGet (PcdUgaConsumeSupport)) { UgaDraw->Blt ( UgaDraw, (EFI_UGA_PIXEL *) (UINTN) BltChar, EfiUgaBltBufferToVideo, 0, 0, GlyphX, GlyphY, EFI_GLYPH_WIDTH, EFI_GLYPH_HEIGHT, EFI_GLYPH_WIDTH * sizeof (EFI_UGA_PIXEL) ); } return EFI_SUCCESS; } /** HII Database Protocol notification event handler. Register font package when HII Database Protocol has been installed. @param[in] Event Event whose notification function is being invoked. @param[in] Context Pointer to the notification function's context. **/ VOID EFIAPI RegisterFontPackage ( IN EFI_EVENT Event, IN VOID *Context ) { EFI_STATUS Status; EFI_HII_SIMPLE_FONT_PACKAGE_HDR *SimplifiedFont; UINT32 PackageLength; UINT8 *Package; UINT8 *Location; EFI_HII_DATABASE_PROTOCOL *HiiDatabase; // // Locate HII Database Protocol // Status = gBS->LocateProtocol ( &gEfiHiiDatabaseProtocolGuid, NULL, (VOID **) &HiiDatabase ); if (EFI_ERROR (Status)) { return; } // // Add 4 bytes to the header for entire length for HiiAddPackages use only. // // +--------------------------------+ <-- Package // | | // | PackageLength(4 bytes) | // | | // |--------------------------------| <-- SimplifiedFont // | | // |EFI_HII_SIMPLE_FONT_PACKAGE_HDR | // | | // |--------------------------------| <-- Location // | | // | gUsStdNarrowGlyphData | // | | // +--------------------------------+ PackageLength = sizeof (EFI_HII_SIMPLE_FONT_PACKAGE_HDR) + mNarrowFontSize + 4; Package = AllocateZeroPool (PackageLength); ASSERT (Package != NULL); WriteUnaligned32((UINT32 *) Package,PackageLength); SimplifiedFont = (EFI_HII_SIMPLE_FONT_PACKAGE_HDR *) (Package + 4); SimplifiedFont->Header.Length = (UINT32) (PackageLength - 4); SimplifiedFont->Header.Type = EFI_HII_PACKAGE_SIMPLE_FONTS; SimplifiedFont->NumberOfNarrowGlyphs = (UINT16) (mNarrowFontSize / sizeof (EFI_NARROW_GLYPH)); Location = (UINT8 *) (&SimplifiedFont->NumberOfWideGlyphs + 1); CopyMem (Location, gUsStdNarrowGlyphData, mNarrowFontSize); // // Add this simplified font package to a package list then install it. // mHiiHandle = HiiAddPackages ( &mFontPackageListGuid, NULL, Package, NULL ); ASSERT (mHiiHandle != NULL); FreePool (Package); } /** The user Entry Point for module GraphicsConsole. The user code starts with this function. @param[in] ImageHandle The firmware allocated handle for the EFI image. @param[in] SystemTable A pointer to the EFI System Table. @retval EFI_SUCCESS The entry point is executed successfully. @return other Some error occurs when executing this entry point. **/ EFI_STATUS EFIAPI InitializeGraphicsConsole ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_STATUS Status; // // Register notify function on HII Database Protocol to add font package. // EfiCreateProtocolNotifyEvent ( &gEfiHiiDatabaseProtocolGuid, TPL_CALLBACK, RegisterFontPackage, NULL, &mHiiRegistration ); // // Install driver model protocol(s). // Status = EfiLibInstallDriverBindingComponentName2 ( ImageHandle, SystemTable, &gGraphicsConsoleDriverBinding, ImageHandle, &gGraphicsConsoleComponentName, &gGraphicsConsoleComponentName2 ); ASSERT_EFI_ERROR (Status); return Status; }