-
Notifications
You must be signed in to change notification settings - Fork 200
Expand file tree
/
Copy pathemitter.cc
More file actions
684 lines (596 loc) · 24.4 KB
/
Copy pathemitter.cc
File metadata and controls
684 lines (596 loc) · 24.4 KB
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
681
682
683
684
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "sandboxed_api/tools/clang_generator/emitter.h"
#include <algorithm>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_set.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/status/status_macros.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/Type.h"
#include "llvm/Config/llvm-config.h"
#include "sandboxed_api/tools/clang_generator/diagnostics.h"
#include "sandboxed_api/tools/clang_generator/emitter_base.h"
#include "sandboxed_api/tools/clang_generator/generator.h"
#include "sandboxed_api/tools/clang_generator/types.h"
namespace sapi {
// Common header description with auto-generation notice. Used for both the
// sandboxee header file and source files.
constexpr absl::string_view kGeneratorComment =
R"(// AUTO-GENERATED by the Sandboxed API Clang tool.
// Edits will be discarded when regenerating this file.
)";
// Common header file prolog with auto-generation notice.
// Note: The includes will be adjusted by Copybara when converting to/from
// internal code. This is intentional.
// Text template arguments:
// 1. Header guard
constexpr absl::string_view kHeaderIncludes =
R"(
#include "absl/base/macros.h"
#include "absl/status/status.h"
#include "absl/status/status_macros.h"
#include "absl/status/statusor.h"
#include "sandboxed_api/sandbox.h"
#include "sandboxed_api/sandbox2_backend.h"
#include "sandboxed_api/sandbox_config.h"
#include "sandboxed_api/vars.h"
)";
constexpr absl::string_view kSandboxBackendInclude =
R"(#include "sandboxed_api/%1$s_backend.h"
)";
// Text template arguments:
// 1. Include for embedded sandboxee objects
constexpr absl::string_view kEmbedInclude = R"(#include "%1$s_embed.h"
)";
// Text template arguments:
// 1. Class name
// 2. Embedded object identifier
constexpr absl::string_view kEmbedClassTemplate = R"(
// Sandbox with embedded sandboxee and default policy
class %1$s : public ::sapi::Sandbox<::sapi::Sandbox2Backend> {
public:
%1$s()
: %1$s(::sapi::SandboxConfig::DefaultConfig()) {}
explicit %1$s(::sapi::SandboxConfig config)
: %1$s(::sapi::Sandbox2Backend(
ConfigWithForkClientContext(std::move(config)),
[this] { return CreateNotifier(); })) {}
// This constructor should only be used for special cases, e.g. when using the
// CreateNotifier() method. Otherwise, prefer to use the SandboxConfig
// constructor above.
explicit %1$s(::sapi::Sandbox2Backend backend)
: ::sapi::Sandbox<::sapi::Sandbox2Backend>(std::move(backend)) {}
private:
static ::sapi::SandboxConfig ConfigWithForkClientContext(
::sapi::SandboxConfig config) {
if (!config.sandbox2.fork_client_context.has_value()) {
static ::sapi::ForkClientContext fork_client_context(%2$s_embed_create());
config.sandbox2.fork_client_context = fork_client_context;
}
return config;
}
};
)";
// Text template arguments:
// 1. Class name
constexpr absl::string_view kSandboxTypedefTemplate = R"(
using %1$s = ::sapi::Sandbox<::sapi::Sandbox2Backend>;
)";
// Text template arguments:
// 1. Function name prefix
constexpr absl::string_view kHandleMsgDeclarationTemplate = R"(
namespace sapi::client {
void %1$sHandleCallMsg(const ::sapi::FuncCall& call, ::sapi::FuncRet* ret);
void %1$sHandleSymbolMsg(const char* symname, ::sapi::FuncRet* ret);
} // namespace sapi::client
)";
// Text template arguments:
// 1. Class name
// 2. HandleCallMsg function name
constexpr std::string_view kPassthroughClassTemplate = R"(
// Sandbox class for the Passthrough backend with default policy.
class %1$s : public ::sapi::Sandbox<::sapi::PassthroughBackend> {
public:
%1$s()
: %1$s(::sapi::SandboxConfig{}) {}
explicit %1$s(::sapi::SandboxConfig config)
: %1$s(::sapi::PassthroughBackend(std::move(config), %2$s, %3$s)) {}
explicit %1$s(::sapi::PassthroughBackend backend)
: ::sapi::Sandbox<::sapi::PassthroughBackend>(std::move(backend)) {}
};
)";
// Sandboxed API class template.
// Text template arguments:
// 1. Class name
constexpr absl::string_view kClassHeaderTemplate = R"(
// Sandboxed API
class %1$s {
public:
explicit %1$s(::sapi::SandboxBase* sandbox) : sandbox_(sandbox) {}
[[deprecated("Call sandbox() instead")]]
::sapi::SandboxBase* GetSandbox() const { return sandbox(); }
::sapi::SandboxBase* sandbox() const { return sandbox_; }
)";
// Sandboxed API class template footer.
constexpr absl::string_view kClassFooterTemplate = R"(
private:
::sapi::SandboxBase* sandbox_;
};
)";
inline constexpr std::string_view kSandboxeeCommonIncludes = R"(
#include "absl/base/no_destructor.h"
#include "absl/base/optimization.h"
#include "absl/container/flat_hash_map.h"
#include "absl/log/log.h"
#include "absl/strings/string_view.h"
#include "sandboxed_api/call.h"
#include "sandboxed_api/function_call_helper.h"
)";
// Text template arguments:
// 1. Sandboxee prototypes
// 2. Sandboxee handler functions
// 3. HandleCallMsg name prefix
// 4. Sandboxee function names
// 5. Sandboxee symbol names
inline constexpr std::string_view kSandboxeeSrcTemplate = R"(
#if defined(__x86_64__) || defined(__aarch64__)
extern "C" char sapi_callback_trampolines[];
#endif
extern "C" {
%1$s
}
namespace sapi::client {
namespace {
%2$s
}
void %3$sHandleCallMsg(const ::sapi::FuncCall& call, ::sapi::FuncRet* ret) {
VLOG(1) << "HandleMsgCall, func: '" << call.func
<< "', # of args: " << call.argc;
static const absl::NoDestructor<absl::flat_hash_map<std::string,
FuncRet (*)(const ::sapi::FunctionCallPreparer& call)>>
kSandboxeeFunctions({
%4$s
});
auto it = kSandboxeeFunctions->find(call.func);
if (ABSL_PREDICT_FALSE(it == kSandboxeeFunctions->end())) {
LOG(ERROR) << "Function not found: '" << call.func << "'";
*ret = FuncRet::FromError(Error::kInvalidFunctionName);
return;
}
::sapi::FunctionCallPreparer preparer(call);
*ret = it->second(preparer);
}
void %3$sHandleSymbolMsg(const char* symname, ::sapi::FuncRet* ret) {
static const absl::NoDestructor<absl::flat_hash_map<std::string, void*>>
kSandboxeeSymbols({
%5$s
});
auto it = kSandboxeeSymbols->find(symname);
if (ABSL_PREDICT_FALSE(it == kSandboxeeSymbols->end())) {
LOG(ERROR) << "Symbol not found: '" << symname << "'";
*ret = FuncRet::FromError(Error::kInvalidFunctionName);
return;
}
ret->int_val = reinterpret_cast<uintptr_t>(it->second);
ret->success = true;
ret->ret_type = ::sapi::v::Type::kPointer;
}
} // namespace sapi::client
)";
inline constexpr std::string_view kFuncHandlerHeaderTemplate = R"(
FuncRet HandleCall_%1$s(const FunctionCallPreparer& call) {
if (ABSL_PREDICT_FALSE(call.arg_count() != %2$d)) {
LOG(ERROR) << "Function '%1$s' called with "
<< call.arg_count() << " arguments, expected " << %2$d;
return FuncRet::FromError(Error::kInvalidArgCount);
}
)";
inline constexpr std::string_view kHandleFuncHasCompatibleArgTemplate = R"(
if (ABSL_PREDICT_FALSE(!call.HasCompatibleArg<%1$s>(%2$d))) {
LOG(ERROR) << "Type mismatch for argument %2$d to '%1$s'";
return FuncRet::FromError(Error::kInvalidArgType);
}
)";
// Returns a unique name for a parameter. If `decl` has no name, a unique name
// will be generated in the form of `unnamed<index>_`.
std::string GetParamName(const clang::ParmVarDecl* decl, int index) {
if (std::string name = decl->getName().str(); !name.empty()) {
return absl::StrCat(name, "_"); // Suffix to avoid collisions
}
return absl::StrCat("unnamed", index, "_");
}
// Returns a comment for the given function `decl` which represents the
// unsandboxed function signature.
absl::StatusOr<std::string> PrintFunctionPrototypeComment(
const TypeMapper& type_mapper, const clang::FunctionDecl* decl) {
std::string out = absl::StrCat(
type_mapper.MapQualTypeParameterForCxx(decl->getDeclaredReturnType()),
" ", ToStringView(decl->getName()), "(");
std::string print_separator;
for (int i = 0; i < decl->getNumParams(); ++i) {
const clang::ParmVarDecl* param = decl->getParamDecl(i);
absl::StrAppend(&out, print_separator);
print_separator = ", ";
absl::StrAppend(&out,
type_mapper.MapQualTypeParameterForCxx(param->getType()));
if (std::string name = param->getName().str(); !name.empty()) {
absl::StrAppend(&out, " ", name);
}
}
absl::StrAppend(&out, ")");
ABSL_ASSIGN_OR_RETURN(std::string formatted,
ReformatGoogleStyle(/*filename=*/"input", out,
/*column_limit=*/75));
out.clear();
for (const auto& line : absl::StrSplit(formatted, '\n')) {
absl::StrAppend(&out, "// ", line, "\n");
}
return out;
}
// Returns the C++ type of the given `type` as it would be used in the sandboxee
// code. Note that this is generally different from the type used in the
// sapi generated header code since we do not care about user types.
std::string GetSandboxeeCppType(TypeMapper& type_mapper, clang::QualType type) {
type = type.getCanonicalType();
if (type->isEnumeralType()) {
#if LLVM_VERSION_MAJOR >= 22
clang::EnumDecl* enum_decl = type->getAsEnumDecl();
#else
clang::EnumDecl* enum_decl = type->getAs<clang::EnumType>()->getDecl();
if (enum_decl->getDefinition()) {
enum_decl = enum_decl->getDefinition();
}
#endif
if (!enum_decl->isComplete()) return "int";
type = enum_decl->getIntegerType();
}
if (type->isPointerType() && !type->getPointeeType()->isBuiltinType()) {
return "void *";
}
return type_mapper.MapQualTypeParameterForCxx(type);
}
absl::StatusOr<std::string> Emitter::DoEmitSandboxeeStub(
const clang::FunctionDecl* decl) {
TypeMapper type_mapper(decl->getASTContext(), options_.namespace_name);
auto function_name = ToStringView(decl->getName());
int arg_count = decl->getNumParams();
std::string out;
const clang::QualType return_type = decl->getDeclaredReturnType();
std::vector<std::string> params;
std::vector<std::string> has_compatible_args;
// Skip variadic functions.
if (decl->isVariadic()) {
return MakeStatusWithDiagnostic(decl->getBeginLoc(),
absl::StatusCode::kCancelled,
"Variadic functions are not supported.");
}
// Process the function parameter list and generate code for the call to
// `FunctionCallPreparer::GetArg`.
// Resulting strings will look like: "call.GetArg<T>(n)"
for (int i = 0; i < decl->getNumParams(); ++i) {
const clang::ParmVarDecl* param = decl->getParamDecl(i);
std::string param_type = GetSandboxeeCppType(type_mapper, param->getType());
params.emplace_back(absl::StrFormat("call.GetArg<%s>(%d)", param_type, i));
has_compatible_args.emplace_back(
absl::StrFormat(kHandleFuncHasCompatibleArgTemplate, param_type, i));
}
absl::StrAppendFormat(&out, kFuncHandlerHeaderTemplate, function_name,
arg_count);
absl::StrAppend(&out, absl::StrJoin(has_compatible_args, "\n"));
// If the sandboxed function returns a value, we need to store that value and
// copy it out to `FuncRet` before returning.
if (!return_type->isVoidType()) {
absl::StrAppendFormat(&out, R"(
return FuncRet::FromValue(::%1$s(%2$s));
}
)",
function_name, absl::StrJoin(params, ", "));
} else {
absl::StrAppendFormat(&out, R"(
::%1$s(%2$s);
return FuncRet {.ret_type = v::Type::kVoid, .success = true};
}
)",
function_name, absl::StrJoin(params, ", "));
}
return out;
}
absl::StatusOr<std::string> Emitter::DoEmitPrototypeSandboxeeFunction(
const clang::FunctionDecl* decl) {
TypeMapper type_mapper(decl->getASTContext(), options_.namespace_name);
std::string out;
auto function_name = ToStringView(decl->getName());
absl::StrAppendFormat(
&out, "\n%1$s %2$s(%3$s);\n",
GetSandboxeeCppType(type_mapper, decl->getDeclaredReturnType()),
function_name,
absl::StrJoin(
decl->parameters(), ", ",
[&type_mapper](std::string* out, const clang::ParmVarDecl* param) {
absl::StrAppend(out,
GetSandboxeeCppType(type_mapper, param->getType()));
}));
return out;
}
absl::StatusOr<std::string> Emitter::DoEmitFunction(
const clang::FunctionDecl* decl) {
TypeMapper type_mapper(decl->getASTContext(), options_.namespace_name);
const clang::QualType return_type = decl->getDeclaredReturnType();
// Skip functions returning record by value.
if (return_type->isRecordType()) {
return MakeStatusWithDiagnostic(
decl->getBeginLoc(), absl::StatusCode::kCancelled,
"Returning record by value, skipping function.");
}
// Skip variadic functions.
if (decl->isVariadic()) {
return MakeStatusWithDiagnostic(decl->getBeginLoc(),
absl::StatusCode::kCancelled,
"Variadic functions are not supported.");
}
ABSL_ASSIGN_OR_RETURN(std::string prototype,
PrintFunctionPrototypeComment(type_mapper, decl));
std::string out;
absl::StrAppend(&out, "\n", prototype);
auto function_name = ToStringView(decl->getName());
const bool returns_void = return_type->isVoidType();
absl::StrAppend(&out, type_mapper.MapQualTypeReturn(return_type), " ",
function_name, "(");
struct ParameterInfo {
clang::QualType qual;
std::string name;
};
std::vector<ParameterInfo> params;
// Process the function parameter list.
std::string print_separator;
for (int i = 0; i < decl->getNumParams(); ++i) {
const clang::ParmVarDecl* param = decl->getParamDecl(i);
// Skip functions with record parameters passed by value.
if (param->getType()->isRecordType()) {
return MakeStatusWithDiagnostic(
param->getBeginLoc(), absl::StatusCode::kCancelled,
absl::StrCat("Passing record parameter '",
ToStringView(param->getName()),
"' by value, skipping function."));
}
ParameterInfo& param_info = params.emplace_back();
param_info.qual = param->getType();
param_info.name = GetParamName(param, i);
absl::StrAppend(&out, print_separator);
print_separator = ", ";
absl::StrAppend(&out, type_mapper.MapQualTypeParameter(param_info.qual),
" ", param_info.name);
}
absl::StrAppend(&out, ") {\n");
// Declare the return value of the SAPI function. The variable is not
// suffixed with an underscore like the parameter variables below, so that a
// parameter named `ret` cannot collide with it.
absl::StrAppend(&out, type_mapper.MapQualType(return_type), " v_ret;\n");
// Declare the local variables for the parameters.
for (const auto& [qual, name] : params) {
if (!IsPointerOrReference(qual)) {
absl::StrAppend(&out, type_mapper.MapQualType(qual), " v_", name, "(",
name, ");\n");
}
}
// Call the sandboxed function.
absl::StrAppend(&out, "\nABSL_RETURN_IF_ERROR(sandbox_->Call(\"",
function_name, "\", &v_ret");
for (const auto& [qual, name] : params) {
absl::StrAppend(&out, ", ", IsPointerOrReference(qual) ? "" : "&v_", name);
}
// End the sandboxed function call and return `ok` if the unsandboxed function
// returns void, or else return the value of the SAPI function.
absl::StrAppend(&out, "));\nreturn ",
(returns_void ? "::absl::OkStatus()" : "v_ret.GetValue()"),
";\n}\n");
return out;
}
absl::StatusOr<std::string> Emitter::DoEmitSandboxeeSrc() {
std::string out;
absl::StrAppend(&out, kGeneratorComment, kSandboxeeCommonIncludes);
std::string call_msg_prefix =
options_.sandbox_mode == SandboxMode::kPassthrough ? options_.name : "";
std::vector<std::string> rendered_functions_unqualified_ordered(
rendered_functions_unqualified_.begin(),
rendered_functions_unqualified_.end());
std::sort(rendered_functions_unqualified_ordered.begin(),
rendered_functions_unqualified_ordered.end());
std::vector<std::string> entries;
entries.reserve(rendered_functions_unqualified_ordered.size() + 1);
for (const auto& func : rendered_functions_unqualified_ordered) {
entries.push_back(
absl::StrFormat("{\"%1$s\", reinterpret_cast<void*>(&%1$s)}", func));
}
entries.push_back(R"(#if defined(__x86_64__) || defined(__aarch64__)
{"sapi_callback_trampolines", reinterpret_cast<void*>(sapi_callback_trampolines)}
#endif)");
absl::StrAppend(
&out, absl::StrFormat(
kSandboxeeSrcTemplate,
absl::StrJoin(rendered_sandboxee_prototypes_ordered_, "\n"),
absl::StrJoin(rendered_sandboxee_handler_ordered_, "\n"),
call_msg_prefix,
absl::StrJoin(rendered_functions_unqualified_ordered, ",\n",
[](std::string* out, std::string_view func) {
absl::StrAppend(
out,
absl::StrFormat(
"{\"%1$s\", HandleCall_%1$s}", func));
}),
absl::StrJoin(entries, ",\n")));
return out;
}
namespace {
void EmitInNamespaces(std::string& out, absl::string_view base_ns_name,
const std::vector<const RenderedType*>& items) {
absl::string_view last_ns_name;
const std::string ns_prefix = absl::StrCat(base_ns_name, "::");
for (const auto* item : items) {
absl::string_view ns_name = item->ns_name;
if (ns_name == base_ns_name) {
ns_name = "";
} else {
absl::ConsumePrefix(&ns_name, ns_prefix);
}
if (ns_name != last_ns_name) {
if (!last_ns_name.empty()) {
absl::StrAppend(&out, "} // namespace ", last_ns_name, "\n");
}
if (!ns_name.empty()) {
absl::StrAppend(&out, "namespace ", ns_name, " {\n");
}
last_ns_name = ns_name;
}
absl::StrAppend(&out, item->spelling, ";\n");
}
if (!last_ns_name.empty()) {
absl::StrAppend(&out, "} // namespace ", last_ns_name, "\n");
}
}
} // namespace
absl::StatusOr<std::string> Emitter::DoEmitHeader() {
// Log a warning message if the number of requested functions is not equal to
// the number of functions generated.
if (!options_.function_names.empty() &&
(options_.function_names.size() != rendered_functions_ordered_.size())) {
LOG(WARNING) << "Generated output has fewer functions than expected - some "
"function signatures might use language features that "
"SAPI does not support. For debugging, we recommend you "
"compare the list of functions in your sapi_library() rule "
"with the generated *.sapi.h file. Expected: "
<< options_.function_names.size()
<< ", generated: " << rendered_functions_ordered_.size();
}
std::string out;
const std::string include_guard = GetIncludeGuard(options_.out_file);
absl::StrAppend(&out, kGeneratorComment);
absl::StrAppendFormat(&out, kHeaderProlog, include_guard);
// Emit the collected includes.
absl::StrAppend(&out, absl::StrJoin(rendered_includes_ordered_, "\n"));
// Emit the common includes.
absl::StrAppend(&out, kHeaderIncludes);
absl::StrAppendFormat(&out, kSandboxBackendInclude,
options_.sandbox_mode == SandboxMode::kSandbox2
? "sandbox2"
: "passthrough");
// When embedding the sandboxee, add embed header include
if (!options_.embed_name.empty()) {
// Not using JoinPath() because even on Windows include paths use plain
// slashes.
std::string include_file(absl::StripSuffix(
absl::StrReplaceAll(options_.embed_dir, {{"\\", "/"}}), "/"));
if (!include_file.empty()) {
absl::StrAppend(&include_file, "/");
}
absl::StrAppend(&include_file, options_.embed_name);
absl::StrAppendFormat(&out, kEmbedInclude, include_file);
}
std::string handle_msg_prefix =
options_.has_sandboxee_src_out() ? options_.name : "";
if (options_.sandbox_mode == SandboxMode::kPassthrough) {
absl::StrAppendFormat(&out, kHandleMsgDeclarationTemplate,
handle_msg_prefix);
}
// If specified, wrap the generated API in a namespace
if (options_.has_namespace()) {
absl::StrAppendFormat(&out, kNamespaceBeginTemplate,
options_.namespace_name);
}
// Emit type dependencies
if (!rendered_tag_decls_ordered_.empty()) {
// Forward declare record types to ensure inner-namespace resolution takes
// precedence over global scope.
absl::StrAppend(&out, "// Incomplete type declarations\n");
EmitInNamespaces(out, options_.namespace_name, rendered_tag_decls_ordered_);
}
if (!rendered_types_ordered_.empty()) {
absl::StrAppend(&out, "// Types this API depends on\n");
EmitInNamespaces(out, options_.namespace_name, rendered_types_ordered_);
}
// Optionally emit a default sandbox that instantiates an embedded sandboxee
std::string sandbox_class_name = absl::StrCat(options_.name, "Sandbox");
switch (options_.sandbox_mode) {
case SandboxMode::kSandbox2: {
if (!options_.embed_name.empty()) {
absl::StrAppendFormat(
&out, kEmbedClassTemplate, sandbox_class_name,
absl::StrReplaceAll(options_.embed_name, {{"-", "_"}}));
} else {
// Or a typedef for the sandbox class if no embedded sandboxee is used.
absl::StrAppendFormat(&out, kSandboxTypedefTemplate,
sandbox_class_name);
}
break;
}
case SandboxMode::kPassthrough: {
absl::StrAppendFormat(
&out, kPassthroughClassTemplate, sandbox_class_name,
absl::StrCat("::sapi::client::", handle_msg_prefix, "HandleCallMsg"),
absl::StrCat("::sapi::client::", handle_msg_prefix,
"HandleSymbolMsg"));
break;
}
}
// Emit the actual Sandboxed API
absl::StrAppendFormat(&out, kClassHeaderTemplate,
absl::StrCat(options_.name, "Api"));
absl::StrAppend(&out, absl::StrJoin(rendered_functions_ordered_, "\n"));
absl::StrAppend(&out, kClassFooterTemplate);
// Close out the header: close namespace (if needed) and end include guard
if (options_.has_namespace()) {
absl::StrAppendFormat(&out, kNamespaceEndTemplate, options_.namespace_name);
}
absl::StrAppendFormat(&out, kHeaderEpilog, include_guard);
return out;
}
absl::Status Emitter::AddFunction(clang::FunctionDecl* decl) {
if (rendered_functions_.insert(decl->getQualifiedNameAsString()).second) {
rendered_functions_unqualified_.insert(decl->getNameAsString());
ABSL_ASSIGN_OR_RETURN(std::string function, DoEmitFunction(decl));
if (options_.has_sandboxee_src_out()) {
ABSL_ASSIGN_OR_RETURN(std::string sandboxee_function,
DoEmitSandboxeeStub(decl));
ABSL_ASSIGN_OR_RETURN(std::string prototype_sandboxee_function,
DoEmitPrototypeSandboxeeFunction(decl));
rendered_sandboxee_prototypes_ordered_.push_back(
prototype_sandboxee_function);
rendered_sandboxee_handler_ordered_.push_back(sandboxee_function);
}
rendered_functions_ordered_.push_back(function);
}
return absl::OkStatus();
}
absl::StatusOr<std::string> Emitter::EmitHeader() {
ABSL_ASSIGN_OR_RETURN(const std::string header, DoEmitHeader());
return ReformatGoogleStyle(options_.out_file, header);
}
absl::StatusOr<std::string> Emitter::EmitSandboxeeSrc() {
ABSL_ASSIGN_OR_RETURN(const std::string src, DoEmitSandboxeeSrc());
return ReformatGoogleStyle(options_.sandboxee_src_out, src);
}
} // namespace sapi