1//===- AutoConvert.cpp - Auto conversion between ASCII/EBCDIC -------------===//
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 contains functions used for auto conversion between
10// ASCII/EBCDIC codepages specific to z/OS.
11//
12//===----------------------------------------------------------------------===//
13
14#ifdef __MVS__
15
16#include "llvm/Support/AutoConvert.h"
17#include <fcntl.h>
18#include <sys/stat.h>
19
20std::error_code llvm::disableAutoConversion(int FD) {
21  static const struct f_cnvrt Convert = {
22      SETCVTOFF,        // cvtcmd
23      0,                // pccsid
24      (short)FT_BINARY, // fccsid
25  };
26  if (fcntl(FD, F_CONTROL_CVT, &Convert) == -1)
27    return std::error_code(errno, std::generic_category());
28  return std::error_code();
29}
30
31std::error_code llvm::enableAutoConversion(int FD) {
32  struct f_cnvrt Query = {
33      QUERYCVT, // cvtcmd
34      0,        // pccsid
35      0,        // fccsid
36  };
37
38  if (fcntl(FD, F_CONTROL_CVT, &Query) == -1)
39    return std::error_code(errno, std::generic_category());
40
41  Query.cvtcmd = SETCVTALL;
42  Query.pccsid =
43      (FD == STDIN_FILENO || FD == STDOUT_FILENO || FD == STDERR_FILENO)
44          ? 0
45          : CCSID_UTF_8;
46  // Assume untagged files to be IBM-1047 encoded.
47  Query.fccsid = (Query.fccsid == FT_UNTAGGED) ? CCSID_IBM_1047 : Query.fccsid;
48  if (fcntl(FD, F_CONTROL_CVT, &Query) == -1)
49    return std::error_code(errno, std::generic_category());
50  return std::error_code();
51}
52
53std::error_code llvm::setFileTag(int FD, int CCSID, bool Text) {
54  assert((!Text || (CCSID != FT_UNTAGGED && CCSID != FT_BINARY)) &&
55         "FT_UNTAGGED and FT_BINARY are not allowed for text files");
56  struct file_tag Tag;
57  Tag.ft_ccsid = CCSID;
58  Tag.ft_txtflag = Text;
59  Tag.ft_deferred = 0;
60  Tag.ft_rsvflags = 0;
61
62  if (fcntl(FD, F_SETTAG, &Tag) == -1)
63    return std::error_code(errno, std::generic_category());
64  return std::error_code();
65}
66
67#endif // __MVS__
68