/* vcc/plugins/m4/m4.c
*
* This file is part of vcc.
*
* vcc is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* vcc is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with vcc. If not, see
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
int m4_init(void);
int do_cmd_m4def(int, char **);
char *m4cachep;
int m4cache_size;
struct cmdtable m4_cmdtab[] = {
{ "-m4def", do_cmd_m4def, "Define a macro which i will remember. " },
{ NULL, NULL, NULL }
};
struct plugin plg_m4 = {
.state = 0,
.name = "m4",
.descr = "GNU M4 Expanding. ",
.init = m4_init,
/* the hook will remove by plugins.c */
.cmdtab = m4_cmdtab
};
#define this_plg (&plg_m4)
int do_cmd_m4def(int argc, char **argv) {
char buf[MSG_SIZE];
int size, i = 0, t;
(void) argv;
plg_check_enabled();
if (argc != 1) {
fprintf(stderr, "usage: -m4def\n");
return 1;
}
memset(buf, 0, MSG_SIZE);
for (i = 0; i < (int) MSG_SIZE; i += t) {
fprintf(stderr, "m4> ");
t = read(0, buf + i, MSG_SIZE);
if (!strncmp(buf + i, "finish", 6))
break;
size = t;
/* remember it */
if (unlikely(!(m4cachep = realloc(m4cachep, m4cache_size + size)))) {
fprintf(stderr, "*** malloc() failed\n");
return 1;
}
memset(m4cachep + m4cache_size, 0, size);
strcat(m4cachep, buf + i);
m4cache_size += size;
}
return 0;
}
char *m4_msghook(char *s) {
int fdt, size;
FILE *fp;
char *p;
if (unlikely((fdt = open("/tmp/.vcc-tmp", O_WRONLY | O_TRUNC | O_CREAT, 0666)) < 0)) {
perror("open");
return NULL;
}
write(fdt, m4cachep, m4cache_size);
size = strlen(s) + 1;
write(fdt, s, size);
close(fdt);
if (unlikely(!(fp = popen("/bin/m4 /tmp/.vcc-tmp", "r")))) {
perror("popen");
return NULL;
}
if (unlikely(!(p = malloc(MSG_SIZE)))) {
fprintf(stderr, "*** malloc() failed\n");
return NULL;
}
memset(p, 0, size);
fread(p, 1, MSG_SIZE, fp);
return p;
}
int m4_init(void) {
m4cachep = NULL;
m4cache_size = 0;
return register_msghook(m4_msghook, this_plg);
}