blob: d759097e8e962806af628785a243b7c23341b8ac [file] [log] [blame]
Jeroen Ketemaad659c32016-04-08 09:19:02 +00001//===-- diagnostic.cpp - tool for testing libLLVM and llvm-c API ----------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Jeroen Ketemaad659c32016-04-08 09:19:02 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the --test-diagnostic-handler command in llvm-c-test.
10//
11// This command uses the C API to read a module with a custom diagnostic
12// handler set to test the diagnostic handler functionality.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm-c-test.h"
17#include "llvm-c/BitReader.h"
18#include "llvm-c/Core.h"
19
20#include <stdio.h>
21
22static void diagnosticHandler(LLVMDiagnosticInfoRef DI, void *C) {
23 fprintf(stderr, "Executing diagnostic handler\n");
24
25 fprintf(stderr, "Diagnostic severity is of type ");
26 switch (LLVMGetDiagInfoSeverity(DI)) {
27 case LLVMDSError:
28 fprintf(stderr, "error");
29 break;
30 case LLVMDSWarning:
31 fprintf(stderr, "warning");
32 break;
33 case LLVMDSRemark:
34 fprintf(stderr, "remark");
35 break;
36 case LLVMDSNote:
37 fprintf(stderr, "note");
38 break;
39 }
40 fprintf(stderr, "\n");
41
42 (*(int *)C) = 1;
43}
44
45static int handlerCalled = 0;
46
47int llvm_test_diagnostic_handler(void) {
48 LLVMContextRef C = LLVMGetGlobalContext();
49 LLVMContextSetDiagnosticHandler(C, diagnosticHandler, &handlerCalled);
50
51 if (LLVMContextGetDiagnosticHandler(C) != diagnosticHandler) {
52 fprintf(stderr, "LLVMContext{Set,Get}DiagnosticHandler failed\n");
53 return 1;
54 }
55
56 int *DC = (int *)LLVMContextGetDiagnosticContext(C);
57 if (DC != &handlerCalled || *DC) {
58 fprintf(stderr, "LLVMContextGetDiagnosticContext failed\n");
59 return 1;
60 }
61
62 LLVMMemoryBufferRef MB;
63 char *msg = NULL;
64 if (LLVMCreateMemoryBufferWithSTDIN(&MB, &msg)) {
65 fprintf(stderr, "Error reading file: %s\n", msg);
66 LLVMDisposeMessage(msg);
67 return 1;
68 }
69
70
71 LLVMModuleRef M;
72 int Ret = LLVMGetBitcodeModule2(MB, &M);
73 if (Ret) {
74 // We do not return if the bitcode was invalid, as we want to test whether
75 // the diagnostic handler was executed.
76 fprintf(stderr, "Error parsing bitcode: %s\n", msg);
77 }
78
79 LLVMDisposeMemoryBuffer(MB);
80
81 if (handlerCalled) {
82 fprintf(stderr, "Diagnostic handler was called while loading module\n");
83 } else {
84 fprintf(stderr, "Diagnostic handler was not called while loading module\n");
85 }
86
87 return 0;
88}