1 /*
2 * %CopyrightBegin%
3 *
4 * Copyright Ericsson AB 2001-2020. All Rights Reserved.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 * %CopyrightEnd%
19 */
20 #include <string.h>
21 #include "eidef.h"
22 #include "eiext.h"
23 #include "putget.h"
24
ei_encode_fun(char * buf,int * index,const erlang_fun * p)25 int ei_encode_fun(char *buf, int *index, const erlang_fun *p)
26 {
27 int ix = *index;
28
29 switch (p->type) {
30 case EI_FUN_CLOSURE:
31 if (p->arity == -1) {
32 /* ERL_FUN_EXT */
33 if (buf != NULL) {
34 char* s = buf + ix;
35 put8(s, ERL_FUN_EXT);
36 put32be(s, p->u.closure.n_free_vars);
37 }
38 ix += sizeof(char) + 4;
39 if (ei_encode_pid(buf, &ix, &p->u.closure.pid) < 0)
40 return -1;
41 if (ei_encode_atom_as(buf, &ix, p->module, ERLANG_UTF8, ERLANG_UTF8) < 0)
42 return -1;
43 if (ei_encode_long(buf, &ix, p->u.closure.index) < 0)
44 return -1;
45 if (ei_encode_long(buf, &ix, p->u.closure.uniq) < 0)
46 return -1;
47 if (buf != NULL)
48 memcpy(buf + ix, p->u.closure.free_vars, p->u.closure.free_var_len);
49 ix += p->u.closure.free_var_len;
50 } else {
51 char *size_p;
52 if (buf != NULL) {
53 char* s = buf + ix;
54 put8(s, ERL_NEW_FUN_EXT);
55 size_p = s;
56 s += 4;
57 put8(s, p->arity);
58 memcpy(s, p->u.closure.md5, sizeof(p->u.closure.md5));
59 s += sizeof(p->u.closure.md5);
60 put32be(s, p->u.closure.index);
61 put32be(s, p->u.closure.n_free_vars);
62 } else
63 size_p = NULL;
64 ix += 1 + 4 + 1 + sizeof(p->u.closure.md5) + 4 + 4;
65 if (ei_encode_atom_as(buf, &ix, p->module, ERLANG_UTF8, ERLANG_UTF8) < 0)
66 return -1;
67 if (ei_encode_long(buf, &ix, p->u.closure.old_index) < 0)
68 return -1;
69 if (ei_encode_long(buf, &ix, p->u.closure.uniq) < 0)
70 return -1;
71 if (ei_encode_pid(buf, &ix, &p->u.closure.pid) < 0)
72 return -1;
73 if (buf != NULL)
74 memcpy(buf + ix, p->u.closure.free_vars, p->u.closure.free_var_len);
75 ix += p->u.closure.free_var_len;
76 if (size_p != NULL) {
77 int sz = buf + ix - size_p;
78 put32be(size_p, sz);
79 }
80 }
81 break;
82 case EI_FUN_EXPORT:
83 if (buf != NULL) {
84 char* s = buf + ix;
85 put8(s, ERL_EXPORT_EXT);
86 }
87 ix++;
88 if (ei_encode_atom_as(buf, &ix, p->module, ERLANG_UTF8, ERLANG_UTF8) < 0)
89 return -1;
90 if (ei_encode_atom_as(buf, &ix, p->u.exprt.func, ERLANG_UTF8, ERLANG_UTF8) < 0)
91 return -1;
92 if (ei_encode_long(buf, &ix, p->arity) < 0)
93 return -1;
94 break;
95 }
96 *index = ix;
97 return 0;
98 }
99
100