1 /*
2  * Copyright (C) 2014 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 
17 #pragma once
18 
19 #include <stdarg.h>
20 #include <stdio.h>
21 #include <unistd.h>
22 
23 #include <platform/bionic/macros.h>
24 
25 class MallocXmlElem {
26  public:
27   // Name must be valid throughout lifetime of the object.
28   explicit MallocXmlElem(int fd, const char* name,
fd_(fd)29                          const char* attr_fmt = nullptr, ...) : fd_(fd), name_(name) {
30     dprintf(fd_, "<%s", name_);
31     if (attr_fmt != nullptr) {
32       va_list args;
33       va_start(args, attr_fmt);
34       write(fd_, " ", 1);
35       vdprintf(fd_, attr_fmt, args);
36       va_end(args);
37     }
38     write(fd_, ">", 1);
39   }
40 
~MallocXmlElem()41   ~MallocXmlElem() noexcept {
42     dprintf(fd_, "</%s>", name_);
43   }
44 
Contents(const char * fmt,...)45   void Contents(const char* fmt, ...) {
46     va_list args;
47     va_start(args, fmt);
48     vdprintf(fd_, fmt, args);
49     va_end(args);
50   }
51 
52 private:
53   int fd_;
54   const char* name_;
55 
56   BIONIC_DISALLOW_IMPLICIT_CONSTRUCTORS(MallocXmlElem);
57 };
58