GenerateJfrFiles.java 29.5 KB
Newer Older
A
apetushkov 已提交
1 2 3 4 5 6 7 8 9 10 11
package build.tools.jfr;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
12
import java.util.Iterator;
A
apetushkov 已提交
13
import java.util.LinkedHashMap;
14
import java.util.LinkedList;
A
apetushkov 已提交
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
import java.util.List;
import java.util.Map;

import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.SchemaFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public class GenerateJfrFiles {

    public static void main(String... args) throws Exception {
        if (args.length != 3) {
            System.err.println("Incorrect number of command line arguments.");
            System.err.println("Usage:");
            System.err.println("java GenerateJfrFiles[.java] <path-to-metadata.xml> <path-to-metadata.xsd> <output-directory>");
            System.exit(1);
        }
        try {
            File metadataXml = new File(args[0]);
            File metadataSchema = new File(args[1]);
            File outputDirectory = new File(args[2]);

            Metadata metadata = new Metadata(metadataXml, metadataSchema);
            metadata.verify();
            metadata.wireUpTypes();

            printJfrPeriodicHpp(metadata, outputDirectory);
            printJfrEventIdsHpp(metadata, outputDirectory);
            printJfrEventControlHpp(metadata, outputDirectory);
            printJfrTypesHpp(metadata, outputDirectory);
            printJfrEventClassesHpp(metadata, outputDirectory);

        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    static class XmlType {
        final String fieldType;
        final String parameterType;
        XmlType(String fieldType, String parameterType) {
            this.fieldType = fieldType;
            this.parameterType = parameterType;
        }
    }

    static class TypeElement {
        List<FieldElement> fields = new ArrayList<>();
        String name;
        String fieldType;
        String parameterType;
        boolean supportStruct;
    }

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
    interface TypePredicate {
        boolean isType(TypeElement type);
    }

    static class StringJoiner {
        private final CharSequence delimiter;
        private final List<CharSequence> elements;

        public StringJoiner(CharSequence delimiter) {
            this.delimiter = delimiter;
            elements = new LinkedList<CharSequence>();
        }

        public StringJoiner add(CharSequence newElement) {
            elements.add(newElement);
            return this;
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            Iterator<CharSequence> i = elements.iterator();
            while (i.hasNext()) {
                builder.append(i.next());
                if (i.hasNext()) {
                    builder.append(delimiter);
                }
            }
            return builder.toString();
        }
    }

A
apetushkov 已提交
108 109 110 111 112 113 114 115 116 117 118 119
    static class Metadata {
        final Map<String, TypeElement> types = new LinkedHashMap<>();
        final Map<String, XmlType> xmlTypes = new HashMap<>();
        Metadata(File metadataXml, File metadataSchema) throws ParserConfigurationException, SAXException, FileNotFoundException, IOException {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setSchema(schemaFactory.newSchema(metadataSchema));
            SAXParser sp = factory.newSAXParser();
            sp.parse(metadataXml, new MetadataHandler(this));
        }

        List<EventElement> getEvents() {
120 121 122 123 124 125
            return getList(new TypePredicate() {
                @Override
                public boolean isType(TypeElement t) {
                    return t.getClass() == EventElement.class;
                }
            });
A
apetushkov 已提交
126 127 128
        }

        List<TypeElement> getEventsAndStructs() {
129 130 131 132 133 134
            return getList(new TypePredicate() {
                @Override
                public boolean isType(TypeElement t) {
                    return t.getClass() == EventElement.class || t.supportStruct;
                }
            });
A
apetushkov 已提交
135 136 137
        }

        List<TypeElement> getTypesAndStructs() {
138 139 140 141 142 143
            return getList(new TypePredicate() {
                @Override
                public boolean isType(TypeElement t) {
                    return t.getClass() == TypeElement.class || t.supportStruct;
                }
            });
A
apetushkov 已提交
144 145 146
        }

        @SuppressWarnings("unchecked")
147
        <T> List<T> getList(TypePredicate pred) {
A
apetushkov 已提交
148 149
            List<T> result = new ArrayList<>(types.size());
            for (TypeElement t : types.values()) {
150
                if (pred.isType(t)) {
A
apetushkov 已提交
151 152 153 154 155 156 157
                    result.add((T) t);
                }
            }
            return result;
        }

        List<EventElement> getPeriodicEvents() {
158 159 160 161 162 163
            return getList(new TypePredicate() {
                @Override
                public boolean isType(TypeElement t) {
                    return t.getClass() == EventElement.class && ((EventElement) t).periodic;
                }
            });
A
apetushkov 已提交
164 165 166
        }

        List<TypeElement> getNonEventsAndNonStructs() {
167 168 169 170 171 172
            return getList(new TypePredicate() {
                @Override
                public boolean isType(TypeElement t) {
                    return t.getClass() != EventElement.class && !t.supportStruct;
                }
            });
A
apetushkov 已提交
173 174 175
        }

        List<TypeElement> getTypes() {
176 177 178 179 180 181
            return getList(new TypePredicate() {
                @Override
                public boolean isType(TypeElement t) {
                    return t.getClass() == TypeElement.class && !t.supportStruct;
                }
            });
A
apetushkov 已提交
182 183 184
        }

        List<TypeElement> getStructs() {
185 186 187 188 189 190
            return getList(new TypePredicate() {
                @Override
                public boolean isType(TypeElement t) {
                    return t.getClass() == TypeElement.class && t.supportStruct;
                }
            });
A
apetushkov 已提交
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
        }

        void verify()  {
            for (TypeElement t : types.values()) {
                for (FieldElement f : t.fields) {
                    if (!xmlTypes.containsKey(f.typeName)) { // ignore primitives
                        if (!types.containsKey(f.typeName)) {
                            throw new IllegalStateException("Could not find definition of type '" + f.typeName + "' used by " + t.name + "#" + f.name);
                        }
                    }
                }
            }
        }

        void wireUpTypes() {
            for (TypeElement t : types.values()) {
                for (FieldElement f : t.fields) {
                    TypeElement type = types.get(f.typeName);
                    if (f.struct) {
                        type.supportStruct = true;
                    }
                    f.type = type;
                }
            }
        }
    }

    static class EventElement extends TypeElement {
        String representation;
        boolean thread;
        boolean stackTrace;
        boolean startTime;
        boolean periodic;
        boolean cutoff;
225
        String commitState;
A
apetushkov 已提交
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
    }

    static class FieldElement {
        final Metadata metadata;
        TypeElement type;
        String name;
        String typeName;
        boolean struct;

        FieldElement(Metadata metadata) {
            this.metadata = metadata;
        }

        String getParameterType() {
            if (struct) {
                return "const JfrStruct" + typeName + "&";
            }
            XmlType xmlType = metadata.xmlTypes.get(typeName);
            if (xmlType != null) {
                return xmlType.parameterType;
            }
            return type != null ? "u8" : typeName;
        }

        String getParameterName() {
            return struct ? "value" : "new_value";
        }

        String getFieldType() {
            if (struct) {
                return "JfrStruct" + typeName;
            }
            XmlType xmlType = metadata.xmlTypes.get(typeName);
            if (xmlType != null) {
                return xmlType.fieldType;
            }
            return type != null ? "u8" : typeName;
        }
    }

    static class MetadataHandler extends DefaultHandler {
        final Metadata metadata;
        FieldElement currentField;
        TypeElement currentType;
        MetadataHandler(Metadata metadata) {
            this.metadata = metadata;
        }
        @Override
        public void error(SAXParseException e) throws SAXException {
          throw e;
        }
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            switch (qName) {
            case "XmlType":
                String name = attributes.getValue("name");
                String parameterType = attributes.getValue("parameterType");
                String fieldType = attributes.getValue("fieldType");
                metadata.xmlTypes.put(name, new XmlType(fieldType, parameterType));
                break;
            case "Type":
                currentType = new TypeElement();
                currentType.name = attributes.getValue("name");
                break;
            case "Event":
291 292 293 294 295 296 297 298 299
                EventElement eventType = new EventElement();
                eventType.name = attributes.getValue("name");
                eventType.thread = getBoolean(attributes, "thread", false);
                eventType.stackTrace = getBoolean(attributes, "stackTrace", false);
                eventType.startTime = getBoolean(attributes, "startTime", true);
                eventType.periodic = attributes.getValue("period") != null;
                eventType.cutoff = getBoolean(attributes, "cutoff", false);
                eventType.commitState = attributes.getValue("commitState");
                currentType = eventType;
A
apetushkov 已提交
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
                break;
            case "Field":
                currentField = new FieldElement(metadata);
                currentField.struct = getBoolean(attributes, "struct", false);
                currentField.name = attributes.getValue("name");
                currentField.typeName = attributes.getValue("type");
                break;
            }
        }

        private boolean getBoolean(Attributes attributes, String name, boolean defaultValue) {
            String value = attributes.getValue(name);
            return value == null ? defaultValue : Boolean.valueOf(value);
        }

        @Override
        public void endElement(String uri, String localName, String qName) {
            switch (qName) {
            case "Type":
            case "Event":
                metadata.types.put(currentType.name, currentType);
                currentType = null;
                break;
            case "Field":
                currentType.fields.add(currentField);
                currentField = null;
                break;
            }
        }
    }

    static class Printer implements AutoCloseable {
        final PrintStream out;
        Printer(File outputDirectory, String filename) throws FileNotFoundException {
            out = new PrintStream(new BufferedOutputStream(new FileOutputStream(new File(outputDirectory, filename))));
            write("/* AUTOMATICALLY GENERATED FILE - DO NOT EDIT */");
            write("");
        }

        void write(String text) {
            out.print(text);
            out.print("\n"); // Don't use Windows line endings
        }

        @Override
        public void close() throws Exception {
            out.close();
        }
    }

    private static void printJfrPeriodicHpp(Metadata metadata, File outputDirectory) throws Exception {
        try (Printer out = new Printer(outputDirectory, "jfrPeriodic.hpp")) {
            out.write("#ifndef JFRFILES_JFRPERIODICEVENTSET_HPP");
            out.write("#define JFRFILES_JFRPERIODICEVENTSET_HPP");
            out.write("");
            out.write("#include \"utilities/macros.hpp\"");
            out.write("#if INCLUDE_JFR");
            out.write("#include \"jfrfiles/jfrEventIds.hpp\"");
            out.write("#include \"memory/allocation.hpp\"");
            out.write("");
            out.write("class JfrPeriodicEventSet : public AllStatic {");
            out.write(" public:");
            out.write("  static void requestEvent(JfrEventId id) {");
            out.write("    switch(id) {");
            out.write("  ");
            for (EventElement e : metadata.getPeriodicEvents()) {
                out.write("      case Jfr" + e.name + "Event:");
                out.write("        request" + e.name + "();");
                out.write("        break;");
                out.write("  ");
            }
            out.write("      default:");
            out.write("        break;");
            out.write("      }");
            out.write("    }");
            out.write("");
            out.write(" private:");
            out.write("");
            for (EventElement e : metadata.getPeriodicEvents()) {
                out.write("  static void request" + e.name + "(void);");
                out.write("");
            }
            out.write("};");
            out.write("");
            out.write("#endif // INCLUDE_JFR");
            out.write("#endif // JFRFILES_JFRPERIODICEVENTSET_HPP");
        }
    }

    private static void printJfrEventControlHpp(Metadata metadata, File outputDirectory) throws Exception {
        try (Printer out = new Printer(outputDirectory, "jfrEventControl.hpp")) {
            out.write("#ifndef JFRFILES_JFR_NATIVE_EVENTSETTING_HPP");
            out.write("#define JFRFILES_JFR_NATIVE_EVENTSETTING_HPP");
            out.write("");
            out.write("#include \"utilities/macros.hpp\"");
            out.write("#if INCLUDE_JFR");
            out.write("#include \"jfrfiles/jfrEventIds.hpp\"");
            out.write("");
            out.write("/**");
            out.write(" * Event setting. We add some padding so we can use our");
            out.write(" * event IDs as indexes into this.");
            out.write(" */");
            out.write("");
            out.write("struct jfrNativeEventSetting {");
            out.write("  jlong  threshold_ticks;");
            out.write("  jlong  cutoff_ticks;");
            out.write("  u1     stacktrace;");
            out.write("  u1     enabled;");
            out.write("  u1     pad[6]; // Because GCC on linux ia32 at least tries to pack this.");
            out.write("};");
            out.write("");
            out.write("union JfrNativeSettings {");
            out.write("  // Array version.");
            out.write("  jfrNativeEventSetting bits[MaxJfrEventId];");
            out.write("  // Then, to make it easy to debug,");
            out.write("  // add named struct members also.");
            out.write("  struct {");
            out.write("    jfrNativeEventSetting pad[NUM_RESERVED_EVENTS];");
            for (TypeElement t : metadata.getEventsAndStructs()) {
                out.write("    jfrNativeEventSetting " + t.name + ";");
            }
            out.write("  } ev;");
            out.write("};");
            out.write("");
            out.write("#endif // INCLUDE_JFR");
            out.write("#endif // JFRFILES_JFR_NATIVE_EVENTSETTING_HPP");
        }
    }

    private static void printJfrEventIdsHpp(Metadata metadata, File outputDirectory) throws Exception {
        try (Printer out = new Printer(outputDirectory, "jfrEventIds.hpp")) {
            out.write("#ifndef JFRFILES_JFREVENTIDS_HPP");
            out.write("#define JFRFILES_JFREVENTIDS_HPP");
            out.write("");
            out.write("#include \"utilities/macros.hpp\"");
            out.write("#if INCLUDE_JFR");
            out.write("#include \"jfrfiles/jfrTypes.hpp\"");
            out.write("");
            out.write("/**");
            out.write(" * Enum of the event types in the JVM");
            out.write(" */");
            out.write("enum JfrEventId {");
            out.write("  _jfreventbase = (NUM_RESERVED_EVENTS-1), // Make sure we start at right index.");
            out.write("  ");
            out.write("  // Events -> enum entry");
            for (TypeElement t : metadata.getEventsAndStructs()) {
                out.write("  Jfr" + t.name + "Event,");
            }
            out.write("");
            out.write("  MaxJfrEventId");
            out.write("};");
            out.write("");
            out.write("/**");
            out.write(" * Struct types in the JVM");
            out.write(" */");
            out.write("enum JfrStructId {");
            for (TypeElement t : metadata.getNonEventsAndNonStructs()) {
                out.write("  Jfr" + t.name + "Struct,");
            }
            for (TypeElement t : metadata.getEventsAndStructs()) {
                out.write("  Jfr" + t.name + "Struct,");
            }
            out.write("");
            out.write("  MaxJfrStructId");
            out.write("};");
            out.write("");
            out.write("typedef enum JfrEventId JfrEventId;");
            out.write("typedef enum JfrStructId JfrStructId;");
            out.write("");
            out.write("#endif // INCLUDE_JFR");
            out.write("#endif // JFRFILES_JFREVENTIDS_HPP");
        }
    }

    private static void printJfrTypesHpp(Metadata metadata, File outputDirectory) throws Exception {
      List<String> knownTypes = Arrays.asList(new String[] {"Thread", "StackTrace", "Class", "StackFrame"});
        try (Printer out = new Printer(outputDirectory, "jfrTypes.hpp")) {
            out.write("#ifndef JFRFILES_JFRTYPES_HPP");
            out.write("#define JFRFILES_JFRTYPES_HPP");
            out.write("");
            out.write("#include \"utilities/macros.hpp\"");
            out.write("#if INCLUDE_JFR");
            out.write("");
            out.write("enum JfrTypeId {");
            out.write("  TYPE_NONE             = 0,");
            out.write("  TYPE_CLASS            = 20,");
            out.write("  TYPE_STRING           = 21,");
            out.write("  TYPE_THREAD           = 22,");
            out.write("  TYPE_STACKTRACE       = 23,");
            out.write("  TYPE_BYTES            = 24,");
            out.write("  TYPE_EPOCHMILLIS      = 25,");
            out.write("  TYPE_MILLIS           = 26,");
            out.write("  TYPE_NANOS            = 27,");
            out.write("  TYPE_TICKS            = 28,");
            out.write("  TYPE_ADDRESS          = 29,");
            out.write("  TYPE_PERCENTAGE       = 30,");
            out.write("  TYPE_DUMMY,");
            out.write("  TYPE_DUMMY_1,");
            for (TypeElement type : metadata.getTypes()) {
                if (!knownTypes.contains(type.name)) {
                    out.write("  TYPE_" + type.name.toUpperCase() + ",");
                }
            }
            out.write("");
            out.write("  NUM_JFR_TYPES,");
            out.write("  TYPES_END             = 255");
            out.write("};");
            out.write("");
            out.write("enum ReservedEvent {");
            out.write("  EVENT_METADATA,");
            out.write("  EVENT_CHECKPOINT,");
            out.write("  EVENT_BUFFERLOST,");
            out.write("  NUM_RESERVED_EVENTS = TYPES_END");
            out.write("};");
            out.write("");
            out.write("#endif // INCLUDE_JFR");
            out.write("#endif // JFRFILES_JFRTYPES_HPP");
          };
    }

    private static void printJfrEventClassesHpp(Metadata metadata, File outputDirectory) throws Exception {
        try (Printer out = new Printer(outputDirectory, "jfrEventClasses.hpp")) {
            out.write("#ifndef JFRFILES_JFREVENTCLASSES_HPP");
            out.write("#define JFRFILES_JFREVENTCLASSES_HPP");
            out.write("");
            out.write("#include \"oops/klass.hpp\"");
            out.write("#include \"jfrfiles/jfrTypes.hpp\"");
            out.write("#include \"jfr/utilities/jfrTypes.hpp\"");
            out.write("#include \"utilities/macros.hpp\"");
            out.write("#include \"utilities/ticks.hpp\"");
            out.write("#if INCLUDE_JFR");
            out.write("#include \"jfr/recorder/service/jfrEvent.hpp\"");
532
            out.write("#include \"jfr/support/jfrEpochSynchronization.hpp\"");
A
apetushkov 已提交
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
            out.write("/*");
            out.write(" * Each event class has an assert member function verify() which is invoked");
            out.write(" * just before the engine writes the event and its fields to the data stream.");
            out.write(" * The purpose of verify() is to ensure that all fields in the event are initialized");
            out.write(" * and set before attempting to commit.");
            out.write(" *");
            out.write(" * We enforce this requirement because events are generally stack allocated and therefore");
            out.write(" * *not* initialized to default values. This prevents us from inadvertently committing");
            out.write(" * uninitialized values to the data stream.");
            out.write(" *");
            out.write(" * The assert message contains both the index (zero based) as well as the name of the field.");
            out.write(" */");
            out.write("");
            printTypes(out, metadata, false);
            out.write("");
            out.write("");
            out.write("#else // !INCLUDE_JFR");
            out.write("");
551
            out.write("template <typename T>");
A
apetushkov 已提交
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
            out.write("class JfrEvent {");
            out.write(" public:");
            out.write("  JfrEvent() {}");
            out.write("  void set_starttime(const Ticks&) const {}");
            out.write("  void set_endtime(const Ticks&) const {}");
            out.write("  bool should_commit() const { return false; }");
            out.write("  static bool is_enabled() { return false; }");
            out.write("  void commit() {}");
            out.write("};");
            out.write("");
            printTypes(out, metadata, true);
            out.write("");
            out.write("");
            out.write("#endif // INCLUDE_JFR");
            out.write("#endif // JFRFILES_JFREVENTCLASSES_HPP");
        }
    }

    private static void printTypes(Printer out, Metadata metadata, boolean empty) {
        for (TypeElement t : metadata.getStructs()) {
572
            printType(out, t, empty);
A
apetushkov 已提交
573 574 575
            out.write("");
        }
        for (EventElement e : metadata.getEvents()) {
576
            printEvent(out, e, empty);
A
apetushkov 已提交
577 578 579 580
            out.write("");
        }
    }

581
    private static void printType(Printer out, TypeElement t, boolean empty) {
A
apetushkov 已提交
582 583
        out.write("struct JfrStruct" + t.name);
        out.write("{");
584 585 586 587 588 589
        if (!empty) {
          out.write(" private:");
          for (FieldElement f : t.fields) {
              printField(out, f);
          }
          out.write("");
A
apetushkov 已提交
590 591 592
        }
        out.write(" public:");
        for (FieldElement f : t.fields) {
593
           printTypeSetter(out, f, empty);
A
apetushkov 已提交
594 595
        }
        out.write("");
596
        if (!empty) {
597
          printWriteData(out, t.fields, null);
598
        }
A
apetushkov 已提交
599 600 601 602
        out.write("};");
        out.write("");
    }

603
    private static void printEvent(Printer out, EventElement event, boolean empty) {
A
apetushkov 已提交
604 605
        out.write("class Event" + event.name + " : public JfrEvent<Event" + event.name + ">");
        out.write("{");
606 607 608 609 610 611
        if (!empty) {
          out.write(" private:");
          for (FieldElement f : event.fields) {
              printField(out, f);
          }
          out.write("");
A
apetushkov 已提交
612 613
        }
        out.write(" public:");
614 615 616 617 618 619 620 621 622 623 624 625 626 627
        if (!empty) {
          out.write("  static const bool hasThread = " + event.thread + ";");
          out.write("  static const bool hasStackTrace = " + event.stackTrace + ";");
          out.write("  static const bool isInstant = " + !event.startTime + ";");
          out.write("  static const bool hasCutoff = " + event.cutoff + ";");
          out.write("  static const bool isRequestable = " + event.periodic + ";");
          out.write("  static const JfrEventId eventId = Jfr" + event.name + "Event;");
          out.write("");
        }
        if (!empty) {
          out.write("  Event" + event.name + "(EventStartTime timing=TIMED) : JfrEvent<Event" + event.name + ">(timing) {}");
        } else {
          out.write("  Event" + event.name + "(EventStartTime timing=TIMED) {}");
        }
A
apetushkov 已提交
628 629 630 631
        out.write("");
        int index = 0;
        for (FieldElement f : event.fields) {
            out.write("  void set_" + f.name + "(" + f.getParameterType() + " " + f.getParameterName() + ") {");
632 633 634 635
            if (!empty) {
              out.write("    this->_" + f.name + " = " + f.getParameterName() + ";");
              out.write("    DEBUG_ONLY(set_field_bit(" + index++ + "));");
            }
A
apetushkov 已提交
636 637 638
            out.write("  }");
        }
        out.write("");
639
        if (!empty) {
640
          printWriteData(out, event.fields, event.commitState);
641 642
          out.write("");
        }
A
apetushkov 已提交
643
        out.write("  using JfrEvent<Event" + event.name + ">::commit; // else commit() is hidden by overloaded versions in this class");
644 645 646 647 648
        printConstructor2(out, event, empty);
        printCommitMethod(out, event, empty);
        if (!empty) {
          printVerify(out, event.fields);
        }
A
apetushkov 已提交
649 650 651
        out.write("};");
    }

652
    private static void printWriteData(Printer out, List<FieldElement> fields, String commitState) {
A
apetushkov 已提交
653 654
        out.write("  template <typename Writer>");
        out.write("  void writeData(Writer& w) {");
655 656 657 658
        if (("_thread_in_native").equals(commitState)) {
            out.write("    // explicit epoch synchronization check");
            out.write("    JfrEpochSynchronization sync;");
        }
A
apetushkov 已提交
659 660 661 662 663 664 665 666 667 668
        for (FieldElement field : fields) {
            if (field.struct) {
                out.write("    _" + field.name + ".writeData(w);");
            } else {
                out.write("    w.write(_" + field.name + ");");
            }
        }
        out.write("  }");
    }

669 670 671 672 673 674
    private static void printTypeSetter(Printer out, FieldElement field, boolean empty) {
        if (!empty) {
          out.write("  void set_" + field.name + "(" + field.getParameterType() + " new_value) { this->_" + field.name + " = new_value; }");
        } else {
          out.write("  void set_" + field.name + "(" + field.getParameterType() + " new_value) { }");
        }
A
apetushkov 已提交
675 676 677 678 679 680 681 682 683 684 685 686 687 688
    }

    private static void printVerify(Printer out, List<FieldElement> fields) {
        out.write("");
        out.write("#ifdef ASSERT");
        out.write("  void verify() const {");
        int index = 0;
        for (FieldElement f : fields) {
            out.write("    assert(verify_field_bit(" + index++ + "), \"Attempting to write an uninitialized event field: " + f.name + "\");");
        }
        out.write("  }");
        out.write("#endif");
    }

689
    private static void printCommitMethod(Printer out, EventElement event, boolean empty) {
A
apetushkov 已提交
690 691 692 693 694 695 696
        if (event.startTime) {
            StringJoiner sj = new StringJoiner(",\n              ");
            for (FieldElement f : event.fields) {
                sj.add(f.getParameterType() + " " + f.name);
            }
            out.write("");
            out.write("  void commit(" + sj.toString() + ") {");
697 698 699 700 701 702 703
            if (!empty) {
              out.write("    if (should_commit()) {");
              for (FieldElement f : event.fields) {
                  out.write("      set_" + f.name + "(" + f.name + ");");
              }
              out.write("      commit();");
              out.write("    }");
A
apetushkov 已提交
704 705 706 707 708 709 710 711 712 713 714 715 716
            }
            out.write("  }");
        }
        out.write("");
        StringJoiner sj = new StringJoiner(",\n                     ");
        if (event.startTime) {
            sj.add("const Ticks& startTicks");
            sj.add("const Ticks& endTicks");
        }
        for (FieldElement f : event.fields) {
            sj.add(f.getParameterType() + " " + f.name);
        }
        out.write("  static void commit(" + sj.toString() + ") {");
717 718 719 720 721 722 723 724 725 726 727 728 729
        if (!empty) {
          out.write("    Event" + event.name + " me(UNTIMED);");
          out.write("");
          out.write("    if (me.should_commit()) {");
          if (event.startTime) {
              out.write("      me.set_starttime(startTicks);");
              out.write("      me.set_endtime(endTicks);");
          }
          for (FieldElement f : event.fields) {
              out.write("      me.set_" + f.name + "(" + f.name + ");");
          }
          out.write("      me.commit();");
          out.write("    }");
A
apetushkov 已提交
730 731 732 733
        }
        out.write("  }");
    }

734
    private static void printConstructor2(Printer out, EventElement event, boolean empty) {
A
apetushkov 已提交
735 736 737 738 739 740 741 742 743 744 745
        if (!event.startTime) {
            out.write("");
            out.write("");
        }
        if (event.startTime) {
            out.write("");
            out.write("  Event" + event.name + "(");
            StringJoiner sj = new StringJoiner(",\n    ");
            for (FieldElement f : event.fields) {
                sj.add(f.getParameterType() + " " + f.name);
            }
746 747 748 749 750 751 752 753 754
            if (!empty) {
              out.write("    " + sj.toString() + ") : JfrEvent<Event" + event.name + ">(TIMED) {");
              out.write("    if (should_commit()) {");
              for (FieldElement f : event.fields) {
                  out.write("      set_" + f.name + "(" + f.name + ");");
              }
              out.write("    }");
            } else {
              out.write("    " + sj.toString() + ") {");
A
apetushkov 已提交
755 756 757 758 759 760 761 762 763
            }
            out.write("  }");
        }
    }

    private static void printField(Printer out, FieldElement field) {
        out.write("  " + field.getFieldType() + " _" + field.name + ";");
    }
}