• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 #include "ApiGen.h"
17 #include "EntryPoint.h"
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include "strUtils.h"
21 #include <errno.h>
22 #include <sys/types.h>
23 
24 /* Define this to 1 to enable support for the 'isLarge' variable flag
25  * that instructs the encoder to send large data buffers by a direct
26  * write through the pipe (i.e. without copying it into a temporary
27  * buffer. This has definite performance benefits when using a QEMU Pipe.
28  *
29  * Set to 0 otherwise.
30  */
31 #define WITH_LARGE_SUPPORT  1
32 
findEntryByName(const std::string & name)33 EntryPoint * ApiGen::findEntryByName(const std::string & name)
34 {
35     EntryPoint * entry = NULL;
36 
37     size_t n = this->size();
38     for (size_t i = 0; i < n; i++) {
39         if (at(i).name() == name) {
40             entry = &(at(i));
41             break;
42         }
43     }
44     return entry;
45 }
46 
printHeader(FILE * fp) const47 void ApiGen::printHeader(FILE *fp) const
48 {
49     fprintf(fp, "// Generated Code - DO NOT EDIT !!\n");
50     fprintf(fp, "// generated by 'emugen'\n");
51 }
52 
genProcTypes(const std::string & filename,SideType side)53 int ApiGen::genProcTypes(const std::string &filename, SideType side)
54 {
55     FILE *fp = fopen(filename.c_str(), "wt");
56     if (fp == NULL) {
57         perror(filename.c_str());
58         return -1;
59     }
60     printHeader(fp);
61 
62     const char* basename = m_basename.c_str();
63 
64     fprintf(fp, "#ifndef __%s_%s_proc_t_h\n", basename, sideString(side));
65     fprintf(fp, "#define __%s_%s_proc_t_h\n", basename, sideString(side));
66     fprintf(fp, "\n\n");
67     fprintf(fp, "\n#include \"%s_types.h\"\n",basename);
68     fprintf(fp, "#ifndef %s_APIENTRY\n",basename);
69     fprintf(fp, "#define %s_APIENTRY \n",basename);
70     fprintf(fp, "#endif\n");
71 
72 
73     for (size_t i = 0; i < size(); i++) {
74         EntryPoint *e = &at(i);
75 
76         fprintf(fp, "typedef ");
77         e->retval().printType(fp);
78         fprintf(fp, " (%s_APIENTRY *%s_%s_proc_t) (", basename, e->name().c_str(), sideString(side));
79         if (side == CLIENT_SIDE) { fprintf(fp, "void * ctx"); }
80         if (e->customDecoder() && side == SERVER_SIDE) { fprintf(fp, "void *ctx"); }
81 
82         VarsArray & evars = e->vars();
83         size_t n = evars.size();
84 
85         for (size_t j = 0; j < n; j++) {
86             if (!evars[j].isVoid()) {
87                 if (j != 0 || side == CLIENT_SIDE || (side == SERVER_SIDE && e->customDecoder())) fprintf(fp, ", ");
88                 evars[j].printType(fp);
89             }
90         }
91         fprintf(fp, ");\n");
92     }
93     fprintf(fp, "\n\n#endif\n");
94     return 0;
95 }
96 
genFuncTable(const std::string & filename,SideType side)97 int ApiGen::genFuncTable(const std::string &filename, SideType side)
98 {
99     FILE *fp = fopen(filename.c_str(), "wt");
100     if (fp == NULL) {
101         perror(filename.c_str());
102         return -1;
103     }
104     printHeader(fp);
105 
106     fprintf(fp, "#ifndef __%s_%s_ftable_t_h\n", m_basename.c_str(), sideString(side));
107     fprintf(fp, "#define __%s_%s_ftable_t_h\n", m_basename.c_str(), sideString(side));
108     fprintf(fp, "\n\n");
109     fprintf(fp, "static struct _%s_funcs_by_name {\n", m_basename.c_str());
110     fprintf(fp,
111             "\tconst char *name;\n" \
112             "\tvoid *proc;\n" \
113             "} %s_funcs_by_name[] = {\n", m_basename.c_str());
114 
115 
116     for (size_t i = 0; i < size(); i++) {
117         EntryPoint *e = &at(i);
118         if (e->notApi()) continue;
119         fprintf(fp, "\t{\"%s\", (void*)%s},\n", e->name().c_str(), e->name().c_str());
120     }
121     fprintf(fp, "};\n");
122     fprintf(fp, "static int %s_num_funcs = sizeof(%s_funcs_by_name) / sizeof(struct _%s_funcs_by_name);\n",
123             m_basename.c_str(), m_basename.c_str(), m_basename.c_str());
124     fprintf(fp, "\n\n#endif\n");
125     return 0;
126 }
127 
128 
genContext(const std::string & filename,SideType side)129 int ApiGen::genContext(const std::string & filename, SideType side)
130 {
131     FILE *fp = fopen(filename.c_str(), "wt");
132     if (fp == NULL) {
133         perror(filename.c_str());
134         return -1;
135     }
136     printHeader(fp);
137 
138     fprintf(fp, "#ifndef __%s_%s_context_t_h\n", m_basename.c_str(), sideString(side));
139     fprintf(fp, "#define __%s_%s_context_t_h\n", m_basename.c_str(), sideString(side));
140 
141     //  fprintf(fp, "\n#include \"%s_types.h\"\n", m_basename.c_str());
142     fprintf(fp, "\n#include \"%s_%s_proc.h\"\n", m_basename.c_str(), sideString(side));
143 
144     StringVec & contextHeaders = side == CLIENT_SIDE ? m_clientContextHeaders : m_serverContextHeaders;
145     for (size_t i = 0; i < contextHeaders.size(); i++) {
146         fprintf(fp, "#include %s\n", contextHeaders[i].c_str());
147     }
148     fprintf(fp, "\n");
149 
150     fprintf(fp, "\nstruct %s_%s_context_t {\n\n", m_basename.c_str(), sideString(side));
151     for (size_t i = 0; i < size(); i++) {
152         EntryPoint *e = &at(i);
153         fprintf(fp, "\t%s_%s_proc_t %s;\n", e->name().c_str(), sideString(side), e->name().c_str());
154     }
155     // accessors
156     fprintf(fp, "\t//Accessors \n");
157 
158     for (size_t i = 0; i < size(); i++) {
159         EntryPoint *e = &at(i);
160         const char *n = e->name().c_str();
161         const char *s = sideString(side);
162         fprintf(fp, "\tvirtual %s_%s_proc_t set_%s(%s_%s_proc_t f) { %s_%s_proc_t retval = %s; %s = f; return retval;}\n", n, s, n, n, s, n, s,  n, n);
163     }
164 
165     // virtual destructor
166     fprintf(fp, "\t virtual ~%s_%s_context_t() {}\n", m_basename.c_str(), sideString(side));
167     // accessor
168     if (side == CLIENT_SIDE || side == WRAPPER_SIDE) {
169         fprintf(fp, "\n\ttypedef %s_%s_context_t *CONTEXT_ACCESSOR_TYPE(void);\n",
170                 m_basename.c_str(), sideString(side));
171         fprintf(fp, "\tstatic void setContextAccessor(CONTEXT_ACCESSOR_TYPE *f);\n");
172     }
173 
174     // init function
175     fprintf(fp, "\tint initDispatchByName( void *(*getProc)(const char *name, void *userData), void *userData);\n");
176 
177     //client site set error virtual func
178     if (side == CLIENT_SIDE) {
179         fprintf(fp, "\tvirtual void setError(unsigned int  error){};\n");
180         fprintf(fp, "\tvirtual unsigned int getError(){ return 0; };\n");
181     }
182 
183     fprintf(fp, "};\n");
184 
185     fprintf(fp, "\n#endif\n");
186     fclose(fp);
187     return 0;
188 }
189 
genEntryPoints(const std::string & filename,SideType side)190 int ApiGen::genEntryPoints(const std::string & filename, SideType side)
191 {
192 
193     if (side != CLIENT_SIDE && side != WRAPPER_SIDE) {
194         fprintf(stderr, "Entry points are only defined for Client and Wrapper components\n");
195         return -999;
196     }
197 
198 
199     FILE *fp = fopen(filename.c_str(), "wt");
200     if (fp == NULL) {
201         perror(filename.c_str());
202         return errno;
203     }
204 
205     printHeader(fp);
206     fprintf(fp, "#include <stdio.h>\n");
207     fprintf(fp, "#include <stdlib.h>\n");
208     fprintf(fp, "#include \"%s_%s_context.h\"\n", m_basename.c_str(), sideString(side));
209     fprintf(fp, "\n");
210 
211     fprintf(fp, "#ifndef GL_TRUE\n");
212     fprintf(fp, "extern \"C\" {\n");
213 
214     for (size_t i = 0; i < size(); i++) {
215         fprintf(fp, "\t"); at(i).print(fp, false); fprintf(fp, ";\n");
216     }
217     fprintf(fp, "};\n\n");
218     fprintf(fp, "#endif\n");
219 
220     fprintf(fp, "#ifndef GET_CONTEXT\n");
221     fprintf(fp, "static %s_%s_context_t::CONTEXT_ACCESSOR_TYPE *getCurrentContext = NULL;\n",
222             m_basename.c_str(), sideString(side));
223 
224     fprintf(fp,
225             "void %s_%s_context_t::setContextAccessor(CONTEXT_ACCESSOR_TYPE *f) { getCurrentContext = f; }\n",
226             m_basename.c_str(), sideString(side));
227     fprintf(fp, "#define GET_CONTEXT %s_%s_context_t * ctx = getCurrentContext() \n",
228                 m_basename.c_str(), sideString(side));
229     fprintf(fp, "#endif\n\n");
230 
231 
232     for (size_t i = 0; i < size(); i++) {
233         EntryPoint *e = &at(i);
234         e->print(fp);
235         fprintf(fp, "{\n");
236         fprintf(fp, "\tGET_CONTEXT; \n");
237 
238         bool shouldReturn = !e->retval().isVoid();
239         bool shouldCallWithContext = (side == CLIENT_SIDE);
240         //param check
241         if (shouldCallWithContext) {
242             for (size_t j=0; j<e->vars().size(); j++) {
243                 if (e->vars()[j].paramCheckExpression() != "")
244                     fprintf(fp, "\t%s\n", e->vars()[j].paramCheckExpression().c_str());
245             }
246         }
247         fprintf(fp, "\t %sctx->%s(%s",
248                 shouldReturn ? "return " : "",
249                 e->name().c_str(),
250                 shouldCallWithContext ? "ctx" : "");
251         size_t nvars = e->vars().size();
252 
253         for (size_t j = 0; j < nvars; j++) {
254             if (!e->vars()[j].isVoid()) {
255                 fprintf(fp, "%s %s",
256                         j != 0 || shouldCallWithContext ? "," : "",
257                         e->vars()[j].name().c_str());
258             }
259         }
260         fprintf(fp, ");\n");
261         fprintf(fp, "}\n\n");
262     }
263     fclose(fp);
264     return 0;
265 }
266 
267 
genOpcodes(const std::string & filename)268 int ApiGen::genOpcodes(const std::string &filename)
269 {
270     FILE *fp = fopen(filename.c_str(), "wt");
271     if (fp == NULL) {
272         perror(filename.c_str());
273         return errno;
274     }
275 
276     printHeader(fp);
277     fprintf(fp, "#ifndef __GUARD_%s_opcodes_h_\n", m_basename.c_str());
278     fprintf(fp, "#define __GUARD_%s_opcodes_h_\n\n", m_basename.c_str());
279     for (size_t i = 0; i < size(); i++) {
280         fprintf(fp, "#define OP_%s \t\t\t\t\t%u\n", at(i).name().c_str(), (unsigned int)i + m_baseOpcode);
281     }
282     fprintf(fp, "#define OP_last \t\t\t\t\t%u\n", (unsigned int)size() + m_baseOpcode);
283     fprintf(fp,"\n\n#endif\n");
284     fclose(fp);
285     return 0;
286 
287 }
genAttributesTemplate(const std::string & filename)288 int ApiGen::genAttributesTemplate(const std::string &filename )
289 {
290     FILE *fp = fopen(filename.c_str(), "wt");
291     if (fp == NULL) {
292         perror(filename.c_str());
293         return -1;
294     }
295 
296     for (size_t i = 0; i < size(); i++) {
297         if (at(i).hasPointers()) {
298             fprintf(fp, "#");
299             at(i).print(fp);
300             fprintf(fp, "%s\n\n", at(i).name().c_str());
301         }
302     }
303     fclose(fp);
304     return 0;
305 }
306 
genEncoderHeader(const std::string & filename)307 int ApiGen::genEncoderHeader(const std::string &filename)
308 {
309     FILE *fp = fopen(filename.c_str(), "wt");
310     if (fp == NULL) {
311         perror(filename.c_str());
312         return -1;
313     }
314 
315     printHeader(fp);
316     std::string classname = m_basename + "_encoder_context_t";
317 
318     fprintf(fp, "\n#ifndef GUARD_%s\n", classname.c_str());
319     fprintf(fp, "#define GUARD_%s\n\n", classname.c_str());
320 
321     fprintf(fp, "#include \"IOStream.h\"\n");
322     fprintf(fp, "#include \"%s_%s_context.h\"\n\n\n", m_basename.c_str(), sideString(CLIENT_SIDE));
323 
324     for (size_t i = 0; i < m_encoderHeaders.size(); i++) {
325         fprintf(fp, "#include %s\n", m_encoderHeaders[i].c_str());
326     }
327     fprintf(fp, "\n");
328 
329     fprintf(fp, "struct %s : public %s_%s_context_t {\n\n",
330             classname.c_str(), m_basename.c_str(), sideString(CLIENT_SIDE));
331     fprintf(fp, "\tIOStream *m_stream;\n\n");
332 
333     fprintf(fp, "\t%s(IOStream *stream);\n\n", classname.c_str());
334     fprintf(fp, "\n};\n\n");
335 
336     fprintf(fp,"extern \"C\" {\n");
337 
338     for (size_t i = 0; i < size(); i++) {
339         fprintf(fp, "\t");
340         at(i).print(fp, false, "_enc", /* classname + "::" */"", "void *self");
341         fprintf(fp, ";\n");
342     }
343     fprintf(fp, "};\n");
344     fprintf(fp, "#endif");
345 
346     fclose(fp);
347     return 0;
348 }
349 
350 // Format the byte length expression for a given variable into a user-provided buffer
351 // If the variable type is not a pointer, this is simply its size as a decimal constant
352 // If the variable is a pointer, this will be an expression provided by the .attrib file
353 // through the 'len' attribute.
354 //
355 // Returns 1 if the variable is a pointer, 0 otherwise
356 //
getVarEncodingSizeExpression(Var & var,EntryPoint * e,char * buff,size_t bufflen)357 static int getVarEncodingSizeExpression(Var&  var, EntryPoint* e, char* buff, size_t bufflen)
358 {
359     int ret = 0;
360     if (!var.isPointer()) {
361         snprintf(buff, bufflen, "%u", (unsigned int) var.type()->bytes());
362     } else {
363         ret = 1;
364         const char* lenExpr = var.lenExpression().c_str();
365         const char* varname = var.name().c_str();
366         if (e != NULL && lenExpr[0] == '\0') {
367             fprintf(stderr, "%s: data len is undefined for '%s'\n",
368                     e->name().c_str(), varname);
369         }
370         if (var.nullAllowed()) {
371             snprintf(buff, bufflen, "((%s != NULL) ? %s : 0)", varname, lenExpr);
372         } else {
373             snprintf(buff, bufflen, "%s", lenExpr);
374         }
375     }
376     return ret;
377 }
378 
writeVarEncodingSize(Var & var,FILE * fp)379 static int writeVarEncodingSize(Var& var, FILE* fp)
380 {
381     int ret = 0;
382     if (!var.isPointer()) {
383         fprintf(fp, "%u", (unsigned int) var.type()->bytes());
384     } else {
385         ret = 1;
386         fprintf(fp, "__size_%s", var.name().c_str());
387     }
388     return ret;
389 }
390 
391 
392 
writeVarEncodingExpression(Var & var,FILE * fp)393 static void writeVarEncodingExpression(Var& var, FILE* fp)
394 {
395     const char* varname = var.name().c_str();
396 
397     if (var.isPointer()) {
398         // encode a pointer header
399         fprintf(fp, "\t*(unsigned int *)(ptr) = __size_%s; ptr += 4;\n", varname);
400 
401         Var::PointerDir dir = var.pointerDir();
402         if (dir == Var::POINTER_INOUT || dir == Var::POINTER_IN) {
403             if (var.nullAllowed()) {
404                 fprintf(fp, "\tif (%s != NULL) ", varname);
405             } else {
406                 fprintf(fp, "\t");
407             }
408 
409             if (var.packExpression().size() != 0) {
410                 fprintf(fp, "%s;", var.packExpression().c_str());
411             } else {
412                 fprintf(fp, "memcpy(ptr, %s, __size_%s);",
413                         varname, varname);
414             }
415 
416             fprintf(fp, "ptr += __size_%s;\n", varname);
417         }
418     } else {
419         // encode a non pointer variable
420         if (!var.isVoid()) {
421             fprintf(fp, "\t*(%s *) (ptr) = %s; ptr += %u;\n",
422                     var.type()->name().c_str(), varname,
423                     (uint) var.type()->bytes());
424         }
425     }
426 }
427 
428 #if WITH_LARGE_SUPPORT
writeVarLargeEncodingExpression(Var & var,FILE * fp)429 static void writeVarLargeEncodingExpression(Var& var, FILE* fp)
430 {
431     const char* varname = var.name().c_str();
432 
433     fprintf(fp, "\tstream->writeFully(&__size_%s,4);\n", varname);
434     if (var.nullAllowed()) {
435         fprintf(fp, "\tif (%s != NULL) ", varname);
436     } else {
437         fprintf(fp, "\t");
438     }
439     if (var.writeExpression() != "") {
440         fprintf(fp, "%s", var.writeExpression().c_str());
441     } else {
442         fprintf(fp, "stream->writeFully(%s, __size_%s)", varname, varname);
443     }
444     fprintf(fp, ";\n");
445 }
446 #endif /* WITH_LARGE_SUPPORT */
447 
genEncoderImpl(const std::string & filename)448 int ApiGen::genEncoderImpl(const std::string &filename)
449 {
450     FILE *fp = fopen(filename.c_str(), "wt");
451     if (fp == NULL) {
452         perror(filename.c_str());
453         return -1;
454     }
455 
456     printHeader(fp);
457     fprintf(fp, "\n\n#include <string.h>\n");
458     fprintf(fp, "#include \"%s_opcodes.h\"\n\n", m_basename.c_str());
459     fprintf(fp, "#include \"%s_enc.h\"\n\n\n", m_basename.c_str());
460     fprintf(fp, "#include <stdio.h>\n");
461     std::string classname = m_basename + "_encoder_context_t";
462     size_t n = size();
463 
464     // unsupport printout
465     fprintf(fp,
466             "static void enc_unsupported()\n{\n\tALOGE(\"Function is unsupported\\n\");\n}\n\n");
467 
468     // entry points;
469     for (size_t i = 0; i < n; i++) {
470         EntryPoint *e = &at(i);
471 
472         if (e->unsupported()) continue;
473 
474 
475         e->print(fp, true, "_enc", /* classname + "::" */"", "void *self");
476         fprintf(fp, "{\n");
477 
478 //      fprintf(fp, "\n\tDBG(\">>>> %s\\n\");\n", e->name().c_str());
479         fprintf(fp, "\n\t%s *ctx = (%s *)self;\n",
480                 classname.c_str(),
481                 classname.c_str());
482         fprintf(fp, "\tIOStream *stream = ctx->m_stream;\n\n");
483         VarsArray & evars = e->vars();
484         size_t  maxvars = evars.size();
485         size_t  j;
486 
487         char    buff[256];
488 
489         // Define the __size_XXX variables that contain the size of data
490         // associated with pointers.
491         for (j = 0; j < maxvars; j++) {
492             Var& var = evars[j];
493 
494             if (!var.isPointer())
495                 continue;
496 
497             const char* varname = var.name().c_str();
498             fprintf(fp, "\tconst unsigned int __size_%s = ", varname);
499 
500             getVarEncodingSizeExpression(var, e, buff, sizeof(buff));
501             fprintf(fp, "%s;\n", buff);
502         }
503 
504 #if WITH_LARGE_SUPPORT
505         // We need to take care of 'isLarge' variable in a special way
506         // Anything before an isLarge variable can be packed into a single
507         // buffer, which is then commited. Each isLarge variable is a pointer
508         // to data that can be written to directly through the pipe, which
509         // will be instant when using a QEMU pipe
510 
511         size_t  nvars   = 0;
512         size_t  npointers = 0;
513 
514         // First, compute the total size, 8 bytes for the opcode + payload size
515         fprintf(fp, "\t unsigned char *ptr;\n");
516         fprintf(fp, "\t const size_t packetSize = 8");
517 
518         for (j = 0; j < maxvars; j++) {
519             fprintf(fp, " + ");
520             npointers += writeVarEncodingSize(evars[j], fp);
521         }
522         if (npointers > 0) {
523             fprintf(fp, " + %zu*4", npointers);
524         }
525         fprintf(fp, ";\n");
526 
527         // We need to divide the packet into fragments. Each fragment contains
528         // either copied arguments to a temporary buffer, or direct writes for
529         // large variables.
530         //
531         // The first fragment must also contain the opcode+payload_size
532         //
533         nvars = 0;
534         while (nvars < maxvars || maxvars == 0) {
535 
536             // Skip over non-large fields
537             for (j = nvars; j < maxvars; j++) {
538                 if (evars[j].isLarge())
539                     break;
540             }
541 
542             // Write a fragment if needed.
543             if (nvars == 0 || j > nvars) {
544                 const char* plus = "";
545 
546                 if (nvars == 0 && j == maxvars) {
547                     // Simple shortcut for the common case where we don't have large variables;
548                     fprintf(fp, "\tptr = stream->alloc(packetSize);\n");
549 
550                 } else {
551                     // allocate buffer from the stream until the first large variable
552                     fprintf(fp, "\tptr = stream->alloc(");
553                     plus = "";
554 
555                     if (nvars == 0) {
556                         fprintf(fp,"8"); plus = " + ";
557                     }
558                     if (j > nvars) {
559                         npointers = 0;
560                         for (j = nvars; j < maxvars && !evars[j].isLarge(); j++) {
561                             fprintf(fp, "%s", plus); plus = " + ";
562                             npointers += writeVarEncodingSize(evars[j], fp);
563                         }
564                         if (npointers > 0) {
565                             fprintf(fp, "%s%zu*4", plus, npointers); plus = " + ";
566                         }
567                     }
568                     fprintf(fp,");\n");
569                 }
570 
571                 // encode packet header if needed.
572                 if (nvars == 0) {
573                     fprintf(fp, "\t*(unsigned int *)(ptr) = OP_%s; ptr += 4;\n", e->name().c_str());
574                     fprintf(fp, "\t*(unsigned int *)(ptr) = (unsigned int) packetSize; ptr += 4;\n");
575                 }
576 
577                 if (maxvars == 0)
578                     break;
579 
580                 // encode non-large fields in this fragment
581                 for (j = nvars; j < maxvars && !evars[j].isLarge(); j++) {
582                     writeVarEncodingExpression(evars[j],fp);
583                 }
584 
585                 // Ensure the fragment is commited if it is followed by a large variable
586                 if (j < maxvars) {
587                     fprintf(fp, "\tstream->flush();\n");
588                 }
589             }
590 
591             // If we have one or more large variables, write them directly.
592             // As size + data
593             for ( ; j < maxvars && evars[j].isLarge(); j++) {
594                 writeVarLargeEncodingExpression(evars[j], fp);
595             }
596 
597             nvars = j;
598         }
599 
600 #else /* !WITH_LARGE_SUPPORT */
601         size_t nvars = evars.size();
602         size_t npointers = 0;
603         fprintf(fp, "\t const size_t packetSize = 8");
604         for (size_t j = 0; j < nvars; j++) {
605             npointers += getVarEncodingSizeExpression(evars[j],e,buff,sizeof(buff));
606             fprintf(fp, " + %s", buff);
607         }
608         fprintf(fp, " + %u * 4;\n", (unsigned int) npointers);
609 
610         // allocate buffer from the stream;
611         fprintf(fp, "\t unsigned char *ptr = stream->alloc(packetSize);\n\n");
612 
613         // encode into the stream;
614         fprintf(fp, "\t*(unsigned int *)(ptr) = OP_%s; ptr += 4;\n",  e->name().c_str());
615         fprintf(fp, "\t*(unsigned int *)(ptr) = (unsigned int) packetSize;  ptr += 4;\n\n");
616 
617         // out variables
618         for (size_t j = 0; j < nvars; j++) {
619             writeVarEncodingExpression(evars[j], fp);
620         }
621 #endif /* !WITH_LARGE_SUPPORT */
622 
623         // in variables;
624         for (size_t j = 0; j < nvars; j++) {
625             if (evars[j].isPointer()) {
626                 Var::PointerDir dir = evars[j].pointerDir();
627                 if (dir == Var::POINTER_INOUT || dir == Var::POINTER_OUT) {
628                     const char* varname = evars[j].name().c_str();
629                     if (evars[j].nullAllowed()) {
630                         fprintf(fp, "\tif (%s != NULL) ",varname);
631                     } else {
632                         fprintf(fp, "\t");
633                     }
634                     fprintf(fp, "stream->readback(%s, __size_%s);\n",
635                             varname, varname);
636                 }
637             }
638         }
639 //XXX       fprintf(fp, "\n\tDBG(\"<<<< %s\\n\");\n", e->name().c_str());
640         // todo - return value for pointers
641         if (e->retval().isPointer()) {
642             fprintf(stderr, "WARNING: %s : return value of pointer is unsupported\n",
643                     e->name().c_str());
644             fprintf(fp, "\t return NULL;\n");
645         } else if (e->retval().type()->name() != "void") {
646             fprintf(fp, "\n\t%s retval;\n", e->retval().type()->name().c_str());
647             fprintf(fp, "\tstream->readback(&retval, %u);\n",(uint) e->retval().type()->bytes());
648             fprintf(fp, "\treturn retval;\n");
649         }
650         fprintf(fp, "}\n\n");
651     }
652 
653     // constructor
654     fprintf(fp, "%s::%s(IOStream *stream)\n{\n", classname.c_str(), classname.c_str());
655     fprintf(fp, "\tm_stream = stream;\n\n");
656 
657     for (size_t i = 0; i < n; i++) {
658         EntryPoint *e = &at(i);
659         if (e->unsupported()) {
660             fprintf(fp, "\tset_%s((%s_%s_proc_t)(enc_unsupported));\n", e->name().c_str(), e->name().c_str(), sideString(CLIENT_SIDE));
661         } else {
662             fprintf(fp, "\tset_%s(%s_enc);\n", e->name().c_str(), e->name().c_str());
663         }
664         /**
665            if (e->unsupsported()) {
666            fprintf(fp, "\tmemcpy((void *)(&%s), (const void *)(&enc_unsupported), sizeof(%s));\n",
667            e->name().c_str(),
668            e->name().c_str());
669            } else {
670            fprintf(fp, "\t%s = %s_enc;\n", e->name().c_str(), e->name().c_str());
671            }
672         **/
673     }
674     fprintf(fp, "}\n\n");
675 
676     fclose(fp);
677     return 0;
678 }
679 
680 
genDecoderHeader(const std::string & filename)681 int ApiGen::genDecoderHeader(const std::string &filename)
682 {
683     FILE *fp = fopen(filename.c_str(), "wt");
684     if (fp == NULL) {
685         perror(filename.c_str());
686         return -1;
687     }
688 
689     printHeader(fp);
690     std::string classname = m_basename + "_decoder_context_t";
691 
692     fprintf(fp, "\n#ifndef GUARD_%s\n", classname.c_str());
693     fprintf(fp, "#define GUARD_%s\n\n", classname.c_str());
694 
695     fprintf(fp, "#include \"IOStream.h\" \n");
696     fprintf(fp, "#include \"%s_%s_context.h\"\n\n\n", m_basename.c_str(), sideString(SERVER_SIDE));
697 
698     for (size_t i = 0; i < m_decoderHeaders.size(); i++) {
699         fprintf(fp, "#include %s\n", m_decoderHeaders[i].c_str());
700     }
701     fprintf(fp, "\n");
702 
703     fprintf(fp, "struct %s : public %s_%s_context_t {\n\n",
704             classname.c_str(), m_basename.c_str(), sideString(SERVER_SIDE));
705     fprintf(fp, "\tsize_t decode(void *buf, size_t bufsize, IOStream *stream);\n");
706     fprintf(fp, "\n};\n\n");
707     fprintf(fp, "#endif\n");
708 
709     fclose(fp);
710     return 0;
711 }
712 
genContextImpl(const std::string & filename,SideType side)713 int ApiGen::genContextImpl(const std::string &filename, SideType side)
714 {
715     FILE *fp = fopen(filename.c_str(), "wt");
716     if (fp == NULL) {
717         perror(filename.c_str());
718         return -1;
719     }
720     printHeader(fp);
721 
722     std::string classname = m_basename + "_" + sideString(side) + "_context_t";
723     size_t n = size();
724     fprintf(fp, "\n\n#include <string.h>\n");
725     fprintf(fp, "#include \"%s_%s_context.h\"\n\n\n", m_basename.c_str(), sideString(side));
726     fprintf(fp, "#include <stdio.h>\n\n");
727 
728     // init function;
729     fprintf(fp, "int %s::initDispatchByName(void *(*getProc)(const char *, void *userData), void *userData)\n{\n", classname.c_str());
730     fprintf(fp, "\tvoid *ptr;\n\n");
731     for (size_t i = 0; i < n; i++) {
732         EntryPoint *e = &at(i);
733         fprintf(fp, "\tptr = getProc(\"%s\", userData); set_%s((%s_%s_proc_t)ptr);\n",
734                 e->name().c_str(),
735                 e->name().c_str(),
736                 e->name().c_str(),
737                 sideString(side));
738 
739     }
740     fprintf(fp, "\treturn 0;\n");
741     fprintf(fp, "}\n\n");
742     fclose(fp);
743     return 0;
744 }
745 
genDecoderImpl(const std::string & filename)746 int ApiGen::genDecoderImpl(const std::string &filename)
747 {
748     FILE *fp = fopen(filename.c_str(), "wt");
749     if (fp == NULL) {
750         perror(filename.c_str());
751         return -1;
752     }
753 
754     printHeader(fp);
755 
756     std::string classname = m_basename + "_decoder_context_t";
757 
758     size_t n = size();
759 
760     fprintf(fp, "\n\n#include <string.h>\n");
761     fprintf(fp, "#include \"%s_opcodes.h\"\n\n", m_basename.c_str());
762     fprintf(fp, "#include \"%s_dec.h\"\n\n\n", m_basename.c_str());
763     fprintf(fp, "#include <stdio.h>\n\n");
764     fprintf(fp, "typedef unsigned int tsize_t; // Target \"size_t\", which is 32-bit for now. It may or may not be the same as host's size_t when emugen is compiled.\n\n");
765 
766     // decoder switch;
767     fprintf(fp, "size_t %s::decode(void *buf, size_t len, IOStream *stream)\n{\n", classname.c_str());
768     fprintf(fp,
769             "                           \n\
770 \tsize_t pos = 0;\n\
771 \tif (len < 8) return pos; \n\
772 \tunsigned char *ptr = (unsigned char *)buf;\n\
773 \tbool unknownOpcode = false;  \n\
774 #ifdef CHECK_GL_ERROR \n\
775 \tchar lastCall[256] = {0}; \n\
776 #endif \n\
777 \twhile ((len - pos >= 8) && !unknownOpcode) {   \n\
778 \t\tvoid *params[%u]; \n\
779 \t\tint opcode = *(int *)ptr;   \n\
780 \t\tunsigned int packetLen = *(int *)(ptr + 4);\n\
781 \t\tif (len - pos < packetLen)  return pos; \n\
782 \t\tswitch(opcode) {\n",
783             (uint) m_maxEntryPointsParams);
784 
785     for (size_t f = 0; f < n; f++) {
786         enum Pass_t { PASS_TmpBuffAlloc = 0, PASS_MemAlloc, PASS_DebugPrint, PASS_FunctionCall, PASS_Epilog, PASS_LAST };
787         EntryPoint *e = &at(f);
788 
789         // construct a printout string;
790         std::string printString = "";
791         for (size_t i = 0; i < e->vars().size(); i++) {
792             Var *v = &e->vars()[i];
793             if (!v->isVoid())  printString += (v->isPointer() ? "%p(%u)" : v->type()->printFormat()) + " ";
794         }
795         printString += "";
796         // TODO - add for return value;
797 
798         fprintf(fp, "\t\t\tcase OP_%s:\n", e->name().c_str());
799         fprintf(fp, "\t\t\t{\n");
800 
801         bool totalTmpBuffExist = false;
802         std::string totalTmpBuffOffset = "0";
803         std::string *tmpBufOffset = new std::string[e->vars().size()];
804 
805         // construct retval type string
806         std::string retvalType;
807         if (!e->retval().isVoid()) {
808             retvalType = e->retval().type()->name();
809         }
810 
811         for (int pass = PASS_TmpBuffAlloc; pass < PASS_LAST; pass++) {
812             if (pass == PASS_FunctionCall && !e->retval().isVoid() && !e->retval().isPointer()) {
813                 fprintf(fp, "\t\t\t*(%s *)(&tmpBuf[%s]) = ", retvalType.c_str(),
814                         totalTmpBuffOffset.c_str());
815             }
816 
817 
818             if (pass == PASS_FunctionCall) {
819                 fprintf(fp, "\t\t\tthis->%s(", e->name().c_str());
820                 if (e->customDecoder()) {
821                     fprintf(fp, "this"); // add a context to the call
822                 }
823             } else if (pass == PASS_DebugPrint) {
824                 fprintf(fp, "#ifdef DEBUG_PRINTOUT\n");
825                 fprintf(fp, "\t\t\tfprintf(stderr,\"%s: %s(%s)\\n\"", m_basename.c_str(), e->name().c_str(), printString.c_str());
826                 if (e->vars().size() > 0 && !e->vars()[0].isVoid()) fprintf(fp, ",");
827             }
828 
829             std::string varoffset = "8"; // skip the header
830             VarsArray & evars = e->vars();
831             // allocate memory for out pointers;
832             for (size_t j = 0; j < evars.size(); j++) {
833                 Var *v = & evars[j];
834                 if (!v->isVoid()) {
835                     if ((pass == PASS_FunctionCall) && (j != 0 || e->customDecoder())) fprintf(fp, ", ");
836                     if (pass == PASS_DebugPrint && j != 0) fprintf(fp, ", ");
837 
838                     if (!v->isPointer()) {
839                         if (pass == PASS_FunctionCall || pass == PASS_DebugPrint) {
840                             fprintf(fp, "*(%s *)(ptr + %s)", v->type()->name().c_str(), varoffset.c_str());
841                         }
842                         varoffset += " + " + toString(v->type()->bytes());
843                     } else {
844                         if (v->pointerDir() == Var::POINTER_IN || v->pointerDir() == Var::POINTER_INOUT) {
845                             if (pass == PASS_MemAlloc && v->pointerDir() == Var::POINTER_INOUT) {
846                                 fprintf(fp, "\t\t\tsize_t tmpPtr%uSize = (size_t)*(unsigned int *)(ptr + %s);\n",
847                                         (uint) j, varoffset.c_str());
848                                 fprintf(fp, "unsigned char *tmpPtr%u = (ptr + %s + 4);\n",
849                                         (uint) j, varoffset.c_str());
850                             }
851                             if (pass == PASS_FunctionCall) {
852                                 if (v->nullAllowed()) {
853                                     fprintf(fp, "*((unsigned int *)(ptr + %s)) == 0 ? NULL : (%s)(ptr + %s + 4)",
854                                             varoffset.c_str(), v->type()->name().c_str(), varoffset.c_str());
855                                 } else {
856                                     fprintf(fp, "(%s)(ptr + %s + 4)",
857                                             v->type()->name().c_str(), varoffset.c_str());
858                                 }
859                             } else if (pass == PASS_DebugPrint) {
860                                 fprintf(fp, "(%s)(ptr + %s + 4), *(unsigned int *)(ptr + %s)",
861                                         v->type()->name().c_str(), varoffset.c_str(),
862                                         varoffset.c_str());
863                             }
864                             varoffset += " + 4 + *(tsize_t *)(ptr +" + varoffset + ")";
865                         } else { // out pointer;
866                             if (pass == PASS_TmpBuffAlloc) {
867                                 fprintf(fp, "\t\t\tsize_t tmpPtr%uSize = (size_t)*(unsigned int *)(ptr + %s);\n",
868                                         (uint) j, varoffset.c_str());
869                                 if (!totalTmpBuffExist) {
870                                     fprintf(fp, "\t\t\tsize_t totalTmpSize = tmpPtr%uSize;\n", (uint)j);
871                                 } else {
872                                     fprintf(fp, "\t\t\ttotalTmpSize += tmpPtr%uSize;\n", (uint)j);
873                                 }
874                                 tmpBufOffset[j] = totalTmpBuffOffset;
875                                 char tmpPtrName[16];
876                                 sprintf(tmpPtrName," + tmpPtr%uSize", (uint)j);
877                                 totalTmpBuffOffset += std::string(tmpPtrName);
878                                 totalTmpBuffExist = true;
879                             } else if (pass == PASS_MemAlloc) {
880                                 fprintf(fp, "\t\t\tunsigned char *tmpPtr%u = &tmpBuf[%s];\n",
881                                         (uint)j, tmpBufOffset[j].c_str());
882                             } else if (pass == PASS_FunctionCall) {
883                                 if (v->nullAllowed()) {
884                                     fprintf(fp, "tmpPtr%uSize == 0 ? NULL : (%s)(tmpPtr%u)",
885                                             (uint) j, v->type()->name().c_str(), (uint) j);
886                                 } else {
887                                     fprintf(fp, "(%s)(tmpPtr%u)", v->type()->name().c_str(), (uint) j);
888                                 }
889                             } else if (pass == PASS_DebugPrint) {
890                                 fprintf(fp, "(%s)(tmpPtr%u), *(unsigned int *)(ptr + %s)",
891                                         v->type()->name().c_str(), (uint) j,
892                                         varoffset.c_str());
893                             }
894                             varoffset += " + 4";
895                         }
896                     }
897                 }
898             }
899 
900             if (pass == PASS_FunctionCall || pass == PASS_DebugPrint) fprintf(fp, ");\n");
901             if (pass == PASS_DebugPrint) fprintf(fp, "#endif\n");
902 
903             if (pass == PASS_TmpBuffAlloc) {
904                 if (!e->retval().isVoid() && !e->retval().isPointer()) {
905                     if (!totalTmpBuffExist)
906                         fprintf(fp, "\t\t\tsize_t totalTmpSize = sizeof(%s);\n", retvalType.c_str());
907                     else
908                         fprintf(fp, "\t\t\ttotalTmpSize += sizeof(%s);\n", retvalType.c_str());
909 
910                     totalTmpBuffExist = true;
911                 }
912                 if (totalTmpBuffExist) {
913                     fprintf(fp, "\t\t\tunsigned char *tmpBuf = stream->alloc(totalTmpSize);\n");
914                 }
915             }
916 
917             if (pass == PASS_Epilog) {
918                 // send back out pointers data as well as retval
919                 if (totalTmpBuffExist) {
920                     fprintf(fp, "\t\t\tstream->flush();\n");
921                 }
922 
923                 fprintf(fp, "\t\t\tpos += *(int *)(ptr + 4);\n");
924                 fprintf(fp, "\t\t\tptr += *(int *)(ptr + 4);\n");
925             }
926 
927         } // pass;
928         fprintf(fp, "\t\t\t}\n");
929         fprintf(fp, "#ifdef CHECK_GL_ERROR\n");
930         fprintf(fp, "\t\t\tsprintf(lastCall, \"%s\");\n", e->name().c_str());
931         fprintf(fp, "#endif\n");
932         fprintf(fp, "\t\t\tbreak;\n");
933 
934         delete [] tmpBufOffset;
935     }
936     fprintf(fp, "\t\t\tdefault:\n");
937     fprintf(fp, "\t\t\t\tunknownOpcode = true;\n");
938     fprintf(fp, "\t\t} //switch\n");
939     if (strstr(m_basename.c_str(), "gl")) {
940         fprintf(fp, "#ifdef CHECK_GL_ERROR\n");
941         fprintf(fp, "\tint err = this->glGetError();\n");
942         fprintf(fp, "\tif (err) fprintf(stderr, \"%s Error: 0x%%X in %%s\\n\", err, lastCall);\n", m_basename.c_str());
943         fprintf(fp, "#endif\n");
944     }
945     fprintf(fp, "\t} // while\n");
946     fprintf(fp, "\treturn pos;\n");
947     fprintf(fp, "}\n");
948 
949     fclose(fp);
950     return 0;
951 }
952 
readSpec(const std::string & filename)953 int ApiGen::readSpec(const std::string & filename)
954 {
955     FILE *specfp = fopen(filename.c_str(), "rt");
956     if (specfp == NULL) {
957         return -1;
958     }
959 
960     char line[1000];
961     unsigned int lc = 0;
962     while (fgets(line, sizeof(line), specfp) != NULL) {
963         lc++;
964         EntryPoint ref;
965         if (ref.parse(lc, std::string(line))) {
966             push_back(ref);
967             updateMaxEntryPointsParams(ref.vars().size());
968         }
969     }
970     fclose(specfp);
971     return 0;
972 }
973 
readAttributes(const std::string & attribFilename)974 int ApiGen::readAttributes(const std::string & attribFilename)
975 {
976     enum { ST_NAME, ST_ATT } state;
977 
978     FILE *fp = fopen(attribFilename.c_str(), "rt");
979     if (fp == NULL) {
980         perror(attribFilename.c_str());
981         return -1;
982     }
983     char buf[1000];
984 
985     state = ST_NAME;
986     EntryPoint *currentEntry = NULL;
987     size_t lc = 0;
988     bool globalAttributes = false;
989     while (fgets(buf, sizeof(buf), fp) != NULL) {
990         lc++;
991         std::string line(buf);
992         if (line.size() == 0) continue; // could that happen?
993 
994         if (line.at(0) == '#') continue; // comment
995 
996         size_t first = line.find_first_not_of(" \t\n");
997         if (state == ST_ATT && (first == std::string::npos || first == 0)) state = ST_NAME;
998 
999         line = trim(line);
1000         if (line.size() == 0 || line.at(0) == '#') continue;
1001 
1002         switch(state) {
1003         case ST_NAME:
1004             if (line == "GLOBAL") {
1005                 globalAttributes = true;
1006             } else {
1007                 globalAttributes = false;
1008                 currentEntry = findEntryByName(line);
1009                 if (currentEntry == NULL) {
1010                     fprintf(stderr, "WARNING: %u: attribute of non existant entry point %s\n", (unsigned int)lc, line.c_str());
1011                 }
1012             }
1013             state = ST_ATT;
1014             break;
1015         case ST_ATT:
1016             if (globalAttributes) {
1017                 setGlobalAttribute(line, lc);
1018             } else  if (currentEntry != NULL) {
1019                 currentEntry->setAttribute(line, lc);
1020             }
1021             break;
1022         }
1023     }
1024     return 0;
1025 }
1026 
1027 
setGlobalAttribute(const std::string & line,size_t lc)1028 int ApiGen::setGlobalAttribute(const std::string & line, size_t lc)
1029 {
1030     size_t pos = 0;
1031     size_t last;
1032     std::string token = getNextToken(line, pos, &last, WHITESPACE);
1033     pos = last;
1034 
1035     if (token == "base_opcode") {
1036         std::string str = getNextToken(line, pos, &last, WHITESPACE);
1037         if (str.size() == 0) {
1038             fprintf(stderr, "line %u: missing value for base_opcode\n", (uint) lc);
1039         } else {
1040             setBaseOpcode(atoi(str.c_str()));
1041         }
1042     } else  if (token == "encoder_headers") {
1043         std::string str = getNextToken(line, pos, &last, WHITESPACE);
1044         pos = last;
1045         while (str.size() != 0) {
1046             encoderHeaders().push_back(str);
1047             str = getNextToken(line, pos, &last, WHITESPACE);
1048             pos = last;
1049         }
1050     } else if (token == "client_context_headers") {
1051         std::string str = getNextToken(line, pos, &last, WHITESPACE);
1052         pos = last;
1053         while (str.size() != 0) {
1054             clientContextHeaders().push_back(str);
1055             str = getNextToken(line, pos, &last, WHITESPACE);
1056             pos = last;
1057         }
1058     } else if (token == "server_context_headers") {
1059         std::string str = getNextToken(line, pos, &last, WHITESPACE);
1060         pos = last;
1061         while (str.size() != 0) {
1062             serverContextHeaders().push_back(str);
1063             str = getNextToken(line, pos, &last, WHITESPACE);
1064             pos = last;
1065         }
1066     } else if (token == "decoder_headers") {
1067         std::string str = getNextToken(line, pos, &last, WHITESPACE);
1068         pos = last;
1069         while (str.size() != 0) {
1070             decoderHeaders().push_back(str);
1071             str = getNextToken(line, pos, &last, WHITESPACE);
1072             pos = last;
1073         }
1074     }
1075     else {
1076         fprintf(stderr, "WARNING: %u : unknown global attribute %s\n", (unsigned int)lc, line.c_str());
1077     }
1078 
1079     return 0;
1080 }
1081 
1082