1//===-- diagnostic.cpp - tool for testing libLLVM and llvm-c API ----------===//
2//
3// 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
6//
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, format: "Executing diagnostic handler\n");
24
25 fprintf(stderr, format: "Diagnostic severity is of type ");
26 switch (LLVMGetDiagInfoSeverity(DI)) {
27 case LLVMDSError:
28 fprintf(stderr, format: "error");
29 break;
30 case LLVMDSWarning:
31 fprintf(stderr, format: "warning");
32 break;
33 case LLVMDSRemark:
34 fprintf(stderr, format: "remark");
35 break;
36 case LLVMDSNote:
37 fprintf(stderr, format: "note");
38 break;
39 }
40 fprintf(stderr, format: "\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, Handler: diagnosticHandler, DiagnosticContext: &handlerCalled);
50
51 if (LLVMContextGetDiagnosticHandler(C) != diagnosticHandler) {
52 fprintf(stderr, format: "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, format: "LLVMContextGetDiagnosticContext failed\n");
59 return 1;
60 }
61
62 LLVMMemoryBufferRef MB;
63 char *msg = NULL;
64 if (LLVMCreateMemoryBufferWithSTDIN(OutMemBuf: &MB, OutMessage: &msg)) {
65 fprintf(stderr, format: "Error reading file: %s\n", msg);
66 LLVMDisposeMessage(Message: msg);
67 return 1;
68 }
69
70
71 LLVMModuleRef M;
72 int Ret = LLVMGetBitcodeModule2(MemBuf: MB, OutM: &M);
73 if (Ret)
74 LLVMDisposeMemoryBuffer(MemBuf: MB);
75
76 if (handlerCalled) {
77 fprintf(stderr, format: "Diagnostic handler was called while loading module\n");
78 } else {
79 fprintf(stderr, format: "Diagnostic handler was not called while loading module\n");
80 }
81
82 return 0;
83}
84